repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rss/maker/dublincore.rb | tools/jruby-1.5.1/lib/ruby/1.8/rss/maker/dublincore.rb | require 'rss/dublincore'
require 'rss/maker/1.0'
module RSS
module Maker
module DublinCoreModel
def self.append_features(klass)
super
::RSS::DublinCoreModel::ELEMENT_NAME_INFOS.each do |name, plural_name|
plural_name ||= "#{name}s"
full_name = "#{RSS::DC_PREFIX}_#{name}"
full_plural_name = "#{RSS::DC_PREFIX}_#{plural_name}"
klass_name = Utils.to_class_name(name)
plural_klass_name = "DublinCore#{Utils.to_class_name(plural_name)}"
full_plural_klass_name = "self.class::#{plural_klass_name}"
full_klass_name = "#{full_plural_klass_name}::#{klass_name}"
klass.def_classed_elements(full_name, "value", plural_klass_name,
full_plural_name, name)
klass.module_eval(<<-EOC, __FILE__, __LINE__ + 1)
def new_#{full_name}(value=nil)
_#{full_name} = #{full_plural_name}.new_#{name}
_#{full_name}.value = value
if block_given?
yield _#{full_name}
else
_#{full_name}
end
end
EOC
end
klass.module_eval(<<-EOC, __FILE__, __LINE__ + 1)
# For backward compatibility
alias #{DC_PREFIX}_rightses #{DC_PREFIX}_rights_list
EOC
end
::RSS::DublinCoreModel::ELEMENT_NAME_INFOS.each do |name, plural_name|
plural_name ||= "#{name}s"
full_name ||= "#{DC_PREFIX}_#{name}"
full_plural_name ||= "#{DC_PREFIX}_#{plural_name}"
klass_name = Utils.to_class_name(name)
full_klass_name = "DublinCore#{klass_name}"
plural_klass_name = "DublinCore#{Utils.to_class_name(plural_name)}"
module_eval(<<-EOC, __FILE__, __LINE__ + 1)
class #{plural_klass_name}Base < Base
def_array_element(#{name.dump}, #{full_plural_name.dump},
#{full_klass_name.dump})
class #{full_klass_name}Base < Base
attr_accessor :value
add_need_initialize_variable("value")
alias_method(:content, :value)
alias_method(:content=, :value=)
def have_required_values?
@value
end
def to_feed(feed, current)
if value and current.respond_to?(:#{full_name})
new_item = current.class::#{full_klass_name}.new(value)
current.#{full_plural_name} << new_item
end
end
end
#{klass_name}Base = #{full_klass_name}Base
end
EOC
end
def self.install_dublin_core(klass)
::RSS::DublinCoreModel::ELEMENT_NAME_INFOS.each do |name, plural_name|
plural_name ||= "#{name}s"
klass_name = Utils.to_class_name(name)
full_klass_name = "DublinCore#{klass_name}"
plural_klass_name = "DublinCore#{Utils.to_class_name(plural_name)}"
klass.module_eval(<<-EOC, __FILE__, __LINE__ + 1)
class #{plural_klass_name} < #{plural_klass_name}Base
class #{full_klass_name} < #{full_klass_name}Base
end
#{klass_name} = #{full_klass_name}
end
EOC
end
end
end
class ChannelBase
include DublinCoreModel
end
class ImageBase; include DublinCoreModel; end
class ItemsBase
class ItemBase
include DublinCoreModel
end
end
class TextinputBase; include DublinCoreModel; end
makers.each do |maker|
maker.module_eval(<<-EOC, __FILE__, __LINE__ + 1)
class Channel
DublinCoreModel.install_dublin_core(self)
end
class Image
DublinCoreModel.install_dublin_core(self)
end
class Items
class Item
DublinCoreModel.install_dublin_core(self)
end
end
class Textinput
DublinCoreModel.install_dublin_core(self)
end
EOC
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rss/maker/itunes.rb | tools/jruby-1.5.1/lib/ruby/1.8/rss/maker/itunes.rb | require 'rss/itunes'
require 'rss/maker/2.0'
module RSS
module Maker
module ITunesBaseModel
def def_class_accessor(klass, name, type, *args)
name = name.gsub(/-/, "_").gsub(/^itunes_/, '')
full_name = "#{RSS::ITUNES_PREFIX}_#{name}"
case type
when nil
klass.def_other_element(full_name)
when :yes_other
def_yes_other_accessor(klass, full_name)
when :yes_clean_other
def_yes_clean_other_accessor(klass, full_name)
when :csv
def_csv_accessor(klass, full_name)
when :element, :attribute
recommended_attribute_name, = *args
klass_name = "ITunes#{Utils.to_class_name(name)}"
klass.def_classed_element(full_name, klass_name,
recommended_attribute_name)
when :elements
plural_name, recommended_attribute_name = args
plural_name ||= "#{name}s"
full_plural_name = "#{RSS::ITUNES_PREFIX}_#{plural_name}"
klass_name = "ITunes#{Utils.to_class_name(name)}"
plural_klass_name = "ITunes#{Utils.to_class_name(plural_name)}"
def_elements_class_accessor(klass, name, full_name, full_plural_name,
klass_name, plural_klass_name,
recommended_attribute_name)
end
end
def def_yes_other_accessor(klass, full_name)
klass.def_other_element(full_name)
klass.module_eval(<<-EOC, __FILE__, __LINE__ + 1)
def #{full_name}?
Utils::YesOther.parse(@#{full_name})
end
EOC
end
def def_yes_clean_other_accessor(klass, full_name)
klass.def_other_element(full_name)
klass.module_eval(<<-EOC, __FILE__, __LINE__ + 1)
def #{full_name}?
Utils::YesCleanOther.parse(#{full_name})
end
EOC
end
def def_csv_accessor(klass, full_name)
klass.def_csv_element(full_name)
end
def def_elements_class_accessor(klass, name, full_name, full_plural_name,
klass_name, plural_klass_name,
recommended_attribute_name=nil)
if recommended_attribute_name
klass.def_classed_elements(full_name, recommended_attribute_name,
plural_klass_name, full_plural_name)
else
klass.def_classed_element(full_plural_name, plural_klass_name)
end
klass.module_eval(<<-EOC, __FILE__, __LINE__ + 1)
def new_#{full_name}(text=nil)
#{full_name} = @#{full_plural_name}.new_#{name}
#{full_name}.text = text
if block_given?
yield #{full_name}
else
#{full_name}
end
end
EOC
end
end
module ITunesChannelModel
extend ITunesBaseModel
class << self
def append_features(klass)
super
::RSS::ITunesChannelModel::ELEMENT_INFOS.each do |name, type, *args|
def_class_accessor(klass, name, type, *args)
end
end
end
class ITunesCategoriesBase < Base
def_array_element("category", "itunes_categories",
"ITunesCategory")
class ITunesCategoryBase < Base
attr_accessor :text
add_need_initialize_variable("text")
def_array_element("category", "itunes_categories",
"ITunesCategory")
def have_required_values?
text
end
alias_method :to_feed_for_categories, :to_feed
def to_feed(feed, current)
if text and current.respond_to?(:itunes_category)
new_item = current.class::ITunesCategory.new(text)
to_feed_for_categories(feed, new_item)
current.itunes_categories << new_item
end
end
end
end
class ITunesImageBase < Base
add_need_initialize_variable("href")
attr_accessor("href")
def to_feed(feed, current)
if @href and current.respond_to?(:itunes_image)
current.itunes_image ||= current.class::ITunesImage.new
current.itunes_image.href = @href
end
end
end
class ITunesOwnerBase < Base
%w(itunes_name itunes_email).each do |name|
add_need_initialize_variable(name)
attr_accessor(name)
end
def to_feed(feed, current)
if current.respond_to?(:itunes_owner=)
_not_set_required_variables = not_set_required_variables
if (required_variable_names - _not_set_required_variables).empty?
return
end
unless have_required_values?
raise NotSetError.new("maker.channel.itunes_owner",
_not_set_required_variables)
end
current.itunes_owner ||= current.class::ITunesOwner.new
current.itunes_owner.itunes_name = @itunes_name
current.itunes_owner.itunes_email = @itunes_email
end
end
private
def required_variable_names
%w(itunes_name itunes_email)
end
end
end
module ITunesItemModel
extend ITunesBaseModel
class << self
def append_features(klass)
super
::RSS::ITunesItemModel::ELEMENT_INFOS.each do |name, type, *args|
def_class_accessor(klass, name, type, *args)
end
end
end
class ITunesDurationBase < Base
attr_reader :content
add_need_initialize_variable("content")
%w(hour minute second).each do |name|
attr_reader(name)
add_need_initialize_variable(name, '0')
end
def content=(content)
if content.nil?
@hour, @minute, @second, @content = nil
else
@hour, @minute, @second =
::RSS::ITunesItemModel::ITunesDuration.parse(content)
@content = content
end
end
def hour=(hour)
@hour = Integer(hour)
update_content
end
def minute=(minute)
@minute = Integer(minute)
update_content
end
def second=(second)
@second = Integer(second)
update_content
end
def to_feed(feed, current)
if @content and current.respond_to?(:itunes_duration=)
current.itunes_duration ||= current.class::ITunesDuration.new
current.itunes_duration.content = @content
end
end
private
def update_content
components = [@hour, @minute, @second]
@content =
::RSS::ITunesItemModel::ITunesDuration.construct(*components)
end
end
end
class ChannelBase
include Maker::ITunesChannelModel
class ITunesCategories < ITunesCategoriesBase
class ITunesCategory < ITunesCategoryBase
ITunesCategory = self
end
end
class ITunesImage < ITunesImageBase; end
class ITunesOwner < ITunesOwnerBase; end
end
class ItemsBase
class ItemBase
include Maker::ITunesItemModel
class ITunesDuration < ITunesDurationBase; end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rss/maker/image.rb | tools/jruby-1.5.1/lib/ruby/1.8/rss/maker/image.rb | require 'rss/image'
require 'rss/maker/1.0'
require 'rss/maker/dublincore'
module RSS
module Maker
module ImageItemModel
def self.append_features(klass)
super
name = "#{RSS::IMAGE_PREFIX}_item"
klass.def_classed_element(name)
end
def self.install_image_item(klass)
klass.module_eval(<<-EOC, __FILE__, __LINE__ + 1)
class ImageItem < ImageItemBase
DublinCoreModel.install_dublin_core(self)
end
EOC
end
class ImageItemBase < Base
include Maker::DublinCoreModel
attr_accessor :about, :resource, :image_width, :image_height
add_need_initialize_variable("about")
add_need_initialize_variable("resource")
add_need_initialize_variable("image_width")
add_need_initialize_variable("image_height")
alias width= image_width=
alias width image_width
alias height= image_height=
alias height image_height
def have_required_values?
@about
end
def to_feed(feed, current)
if current.respond_to?(:image_item=) and have_required_values?
item = current.class::ImageItem.new
setup_values(item)
setup_other_elements(item)
current.image_item = item
end
end
end
end
module ImageFaviconModel
def self.append_features(klass)
super
name = "#{RSS::IMAGE_PREFIX}_favicon"
klass.def_classed_element(name)
end
def self.install_image_favicon(klass)
klass.module_eval(<<-EOC, __FILE__, __LINE__ + 1)
class ImageFavicon < ImageFaviconBase
DublinCoreModel.install_dublin_core(self)
end
EOC
end
class ImageFaviconBase < Base
include Maker::DublinCoreModel
attr_accessor :about, :image_size
add_need_initialize_variable("about")
add_need_initialize_variable("image_size")
alias size image_size
alias size= image_size=
def have_required_values?
@about and @image_size
end
def to_feed(feed, current)
if current.respond_to?(:image_favicon=) and have_required_values?
favicon = current.class::ImageFavicon.new
setup_values(favicon)
setup_other_elements(favicon)
current.image_favicon = favicon
end
end
end
end
class ChannelBase; include Maker::ImageFaviconModel; end
class ItemsBase
class ItemBase; include Maker::ImageItemModel; end
end
makers.each do |maker|
maker.module_eval(<<-EOC, __FILE__, __LINE__ + 1)
class Channel
ImageFaviconModel.install_image_favicon(self)
end
class Items
class Item
ImageItemModel.install_image_item(self)
end
end
EOC
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rss/maker/trackback.rb | tools/jruby-1.5.1/lib/ruby/1.8/rss/maker/trackback.rb | require 'rss/trackback'
require 'rss/maker/1.0'
require 'rss/maker/2.0'
module RSS
module Maker
module TrackBackModel
def self.append_features(klass)
super
klass.def_other_element("#{RSS::TRACKBACK_PREFIX}_ping")
klass.def_classed_elements("#{RSS::TRACKBACK_PREFIX}_about", "value",
"TrackBackAbouts")
end
class TrackBackAboutsBase < Base
def_array_element("about", nil, "TrackBackAbout")
class TrackBackAboutBase < Base
attr_accessor :value
add_need_initialize_variable("value")
alias_method(:resource, :value)
alias_method(:resource=, :value=)
alias_method(:content, :value)
alias_method(:content=, :value=)
def have_required_values?
@value
end
def to_feed(feed, current)
if current.respond_to?(:trackback_abouts) and have_required_values?
about = current.class::TrackBackAbout.new
setup_values(about)
setup_other_elements(about)
current.trackback_abouts << about
end
end
end
end
end
class ItemsBase
class ItemBase; include TrackBackModel; end
end
makers.each do |maker|
maker.module_eval(<<-EOC, __FILE__, __LINE__ + 1)
class Items
class Item
class TrackBackAbouts < TrackBackAboutsBase
class TrackBackAbout < TrackBackAboutBase
end
end
end
end
EOC
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/test/unit.rb | tools/jruby-1.5.1/lib/ruby/1.8/test/unit.rb | require 'test/unit/testcase'
require 'test/unit/autorunner'
module Test # :nodoc:
#
# = Test::Unit - Ruby Unit Testing Framework
#
# == Introduction
#
# Unit testing is making waves all over the place, largely due to the
# fact that it is a core practice of XP. While XP is great, unit testing
# has been around for a long time and has always been a good idea. One
# of the keys to good unit testing, though, is not just writing tests,
# but having tests. What's the difference? Well, if you just _write_ a
# test and throw it away, you have no guarantee that something won't
# change later which breaks your code. If, on the other hand, you _have_
# tests (obviously you have to write them first), and run them as often
# as possible, you slowly build up a wall of things that cannot break
# without you immediately knowing about it. This is when unit testing
# hits its peak usefulness.
#
# Enter Test::Unit, a framework for unit testing in Ruby, helping you to
# design, debug and evaluate your code by making it easy to write and
# have tests for it.
#
#
# == Notes
#
# Test::Unit has grown out of and superceded Lapidary.
#
#
# == Feedback
#
# I like (and do my best to practice) XP, so I value early releases,
# user feedback, and clean, simple, expressive code. There is always
# room for improvement in everything I do, and Test::Unit is no
# exception. Please, let me know what you think of Test::Unit as it
# stands, and what you'd like to see expanded/changed/improved/etc. If
# you find a bug, let me know ASAP; one good way to let me know what the
# bug is is to submit a new test that catches it :-) Also, I'd love to
# hear about any successes you have with Test::Unit, and any
# documentation you might add will be greatly appreciated. My contact
# info is below.
#
#
# == Contact Information
#
# A lot of discussion happens about Ruby in general on the ruby-talk
# mailing list (http://www.ruby-lang.org/en/ml.html), and you can ask
# any questions you might have there. I monitor the list, as do many
# other helpful Rubyists, and you're sure to get a quick answer. Of
# course, you're also welcome to email me (Nathaniel Talbott) directly
# at mailto:testunit@talbott.ws, and I'll do my best to help you out.
#
#
# == Credits
#
# I'd like to thank...
#
# Matz, for a great language!
#
# Masaki Suketa, for his work on RubyUnit, which filled a vital need in
# the Ruby world for a very long time. I'm also grateful for his help in
# polishing Test::Unit and getting the RubyUnit compatibility layer
# right. His graciousness in allowing Test::Unit to supercede RubyUnit
# continues to be a challenge to me to be more willing to defer my own
# rights.
#
# Ken McKinlay, for his interest and work on unit testing, and for his
# willingness to dialog about it. He was also a great help in pointing
# out some of the holes in the RubyUnit compatibility layer.
#
# Dave Thomas, for the original idea that led to the extremely simple
# "require 'test/unit'", plus his code to improve it even more by
# allowing the selection of tests from the command-line. Also, without
# RDoc, the documentation for Test::Unit would stink a lot more than it
# does now.
#
# Everyone who's helped out with bug reports, feature ideas,
# encouragement to continue, etc. It's a real privilege to be a part of
# the Ruby community.
#
# The guys at RoleModel Software, for putting up with me repeating, "But
# this would be so much easier in Ruby!" whenever we're coding in Java.
#
# My Creator, for giving me life, and giving it more abundantly.
#
#
# == License
#
# Test::Unit is copyright (c) 2000-2003 Nathaniel Talbott. It is free
# software, and is distributed under the Ruby license. See the COPYING
# file in the standard Ruby distribution for details.
#
#
# == Warranty
#
# This software is provided "as is" and without any express or
# implied warranties, including, without limitation, the implied
# warranties of merchantibility and fitness for a particular
# purpose.
#
#
# == Author
#
# Nathaniel Talbott.
# Copyright (c) 2000-2003, Nathaniel Talbott
#
# ----
#
# = Usage
#
# The general idea behind unit testing is that you write a _test_
# _method_ that makes certain _assertions_ about your code, working
# against a _test_ _fixture_. A bunch of these _test_ _methods_ are
# bundled up into a _test_ _suite_ and can be run any time the
# developer wants. The results of a run are gathered in a _test_
# _result_ and displayed to the user through some UI. So, lets break
# this down and see how Test::Unit provides each of these necessary
# pieces.
#
#
# == Assertions
#
# These are the heart of the framework. Think of an assertion as a
# statement of expected outcome, i.e. "I assert that x should be equal
# to y". If, when the assertion is executed, it turns out to be
# correct, nothing happens, and life is good. If, on the other hand,
# your assertion turns out to be false, an error is propagated with
# pertinent information so that you can go back and make your
# assertion succeed, and, once again, life is good. For an explanation
# of the current assertions, see Test::Unit::Assertions.
#
#
# == Test Method & Test Fixture
#
# Obviously, these assertions have to be called within a context that
# knows about them and can do something meaningful with their
# pass/fail value. Also, it's handy to collect a bunch of related
# tests, each test represented by a method, into a common test class
# that knows how to run them. The tests will be in a separate class
# from the code they're testing for a couple of reasons. First of all,
# it allows your code to stay uncluttered with test code, making it
# easier to maintain. Second, it allows the tests to be stripped out
# for deployment, since they're really there for you, the developer,
# and your users don't need them. Third, and most importantly, it
# allows you to set up a common test fixture for your tests to run
# against.
#
# What's a test fixture? Well, tests do not live in a vacuum; rather,
# they're run against the code they are testing. Often, a collection
# of tests will run against a common set of data, also called a
# fixture. If they're all bundled into the same test class, they can
# all share the setting up and tearing down of that data, eliminating
# unnecessary duplication and making it much easier to add related
# tests.
#
# Test::Unit::TestCase wraps up a collection of test methods together
# and allows you to easily set up and tear down the same test fixture
# for each test. This is done by overriding #setup and/or #teardown,
# which will be called before and after each test method that is
# run. The TestCase also knows how to collect the results of your
# assertions into a Test::Unit::TestResult, which can then be reported
# back to you... but I'm getting ahead of myself. To write a test,
# follow these steps:
#
# * Make sure Test::Unit is in your library path.
# * require 'test/unit' in your test script.
# * Create a class that subclasses Test::Unit::TestCase.
# * Add a method that begins with "test" to your class.
# * Make assertions in your test method.
# * Optionally define #setup and/or #teardown to set up and/or tear
# down your common test fixture.
# * You can now run your test as you would any other Ruby
# script... try it and see!
#
# A really simple test might look like this (#setup and #teardown are
# commented out to indicate that they are completely optional):
#
# require 'test/unit'
#
# class TC_MyTest < Test::Unit::TestCase
# # def setup
# # end
#
# # def teardown
# # end
#
# def test_fail
# assert(false, 'Assertion was false.')
# end
# end
#
#
# == Test Runners
#
# So, now you have this great test class, but you still need a way to
# run it and view any failures that occur during the run. This is
# where Test::Unit::UI::Console::TestRunner (and others, such as
# Test::Unit::UI::GTK::TestRunner) comes into play. The console test
# runner is automatically invoked for you if you require 'test/unit'
# and simply run the file. To use another runner, or to manually
# invoke a runner, simply call its run class method and pass in an
# object that responds to the suite message with a
# Test::Unit::TestSuite. This can be as simple as passing in your
# TestCase class (which has a class suite method). It might look
# something like this:
#
# require 'test/unit/ui/console/testrunner'
# Test::Unit::UI::Console::TestRunner.run(TC_MyTest)
#
#
# == Test Suite
#
# As more and more unit tests accumulate for a given project, it
# becomes a real drag running them one at a time, and it also
# introduces the potential to overlook a failing test because you
# forget to run it. Suddenly it becomes very handy that the
# TestRunners can take any object that returns a Test::Unit::TestSuite
# in response to a suite method. The TestSuite can, in turn, contain
# other TestSuites or individual tests (typically created by a
# TestCase). In other words, you can easily wrap up a group of
# TestCases and TestSuites like this:
#
# require 'test/unit/testsuite'
# require 'tc_myfirsttests'
# require 'tc_moretestsbyme'
# require 'ts_anothersetoftests'
#
# class TS_MyTests
# def self.suite
# suite = Test::Unit::TestSuite.new
# suite << TC_MyFirstTests.suite
# suite << TC_MoreTestsByMe.suite
# suite << TS_AnotherSetOfTests.suite
# return suite
# end
# end
# Test::Unit::UI::Console::TestRunner.run(TS_MyTests)
#
# Now, this is a bit cumbersome, so Test::Unit does a little bit more
# for you, by wrapping these up automatically when you require
# 'test/unit'. What does this mean? It means you could write the above
# test case like this instead:
#
# require 'test/unit'
# require 'tc_myfirsttests'
# require 'tc_moretestsbyme'
# require 'ts_anothersetoftests'
#
# Test::Unit is smart enough to find all the test cases existing in
# the ObjectSpace and wrap them up into a suite for you. It then runs
# the dynamic suite using the console TestRunner.
#
#
# == Questions?
#
# I'd really like to get feedback from all levels of Ruby
# practitioners about typos, grammatical errors, unclear statements,
# missing points, etc., in this document (or any other).
#
module Unit
# Set true when Test::Unit has run. If set to true Test::Unit
# will not automatically run at exit.
def self.run=(flag)
@run = flag
end
# Already tests have run?
def self.run?
@run ||= false
end
end
end
at_exit do
unless $! || Test::Unit.run?
Kernel.exit Test::Unit::AutoRunner.run
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/test/unit/assertions.rb | tools/jruby-1.5.1/lib/ruby/1.8/test/unit/assertions.rb | # Author:: Nathaniel Talbott.
# Copyright:: Copyright (c) 2000-2003 Nathaniel Talbott. All rights reserved.
# License:: Ruby license.
require 'test/unit/assertionfailederror'
require 'test/unit/util/backtracefilter'
module Test
module Unit
##
# Test::Unit::Assertions contains the standard Test::Unit assertions.
# Assertions is included in Test::Unit::TestCase.
#
# To include it in your own code and use its functionality, you simply
# need to rescue Test::Unit::AssertionFailedError. Additionally you may
# override add_assertion to get notified whenever an assertion is made.
#
# Notes:
# * The message to each assertion, if given, will be propagated with the
# failure.
# * It is easy to add your own assertions based on assert_block().
#
# = Example Custom Assertion
#
# def deny(boolean, message = nil)
# message = build_message message, '<?> is not false or nil.', boolean
# assert_block message do
# not boolean
# end
# end
module Assertions
##
# The assertion upon which all other assertions are based. Passes if the
# block yields true.
#
# Example:
# assert_block "Couldn't do the thing" do
# do_the_thing
# end
public
def assert_block(message="assert_block failed.") # :yields:
_wrap_assertion do
if (! yield)
raise AssertionFailedError.new(message.to_s)
end
end
end
##
# Asserts that +boolean+ is not false or nil.
#
# Example:
# assert [1, 2].include?(5)
public
def assert(boolean, message=nil)
_wrap_assertion do
assert_block("assert should not be called with a block.") { !block_given? }
assert_block(build_message(message, "<?> is not true.", boolean)) { boolean }
end
end
##
# Passes if +expected+ == +actual.
#
# Note that the ordering of arguments is important, since a helpful
# error message is generated when this one fails that tells you the
# values of expected and actual.
#
# Example:
# assert_equal 'MY STRING', 'my string'.upcase
public
def assert_equal(expected, actual, message=nil)
full_message = build_message(message, <<EOT, expected, actual)
<?> expected but was
<?>.
EOT
assert_block(full_message) { expected == actual }
end
private
def _check_exception_class(args) # :nodoc:
args.partition do |klass|
next if klass.instance_of?(Module)
assert(Exception >= klass, "Should expect a class of exception, #{klass}")
true
end
end
private
def _expected_exception?(actual_exception, exceptions, modules) # :nodoc:
exceptions.include?(actual_exception.class) or
modules.any? {|mod| actual_exception.is_a?(mod)}
end
##
# Passes if the block raises one of the given exceptions.
#
# Example:
# assert_raise RuntimeError, LoadError do
# raise 'Boom!!!'
# end
public
def assert_raise(*args)
_wrap_assertion do
if Module === args.last
message = ""
else
message = args.pop
end
exceptions, modules = _check_exception_class(args)
expected = args.size == 1 ? args.first : args
actual_exception = nil
full_message = build_message(message, "<?> exception expected but none was thrown.", expected)
assert_block(full_message) do
begin
yield
rescue Exception => actual_exception
break
end
false
end
full_message = build_message(message, "<?> exception expected but was\n?", expected, actual_exception)
assert_block(full_message) {_expected_exception?(actual_exception, exceptions, modules)}
actual_exception
end
end
##
# Alias of assert_raise.
#
# Will be deprecated in 1.9, and removed in 2.0.
public
def assert_raises(*args, &block)
assert_raise(*args, &block)
end
##
# Passes if +object+ .instance_of? +klass+
#
# Example:
# assert_instance_of String, 'foo'
public
def assert_instance_of(klass, object, message="")
_wrap_assertion do
assert_equal(Class, klass.class, "assert_instance_of takes a Class as its first argument")
full_message = build_message(message, <<EOT, object, klass, object.class)
<?> expected to be an instance of
<?> but was
<?>.
EOT
assert_block(full_message){object.instance_of?(klass)}
end
end
##
# Passes if +object+ is nil.
#
# Example:
# assert_nil [1, 2].uniq!
public
def assert_nil(object, message="")
assert_equal(nil, object, message)
end
##
# Passes if +object+ .kind_of? +klass+
#
# Example:
# assert_kind_of Object, 'foo'
public
def assert_kind_of(klass, object, message="")
_wrap_assertion do
assert(klass.kind_of?(Module), "The first parameter to assert_kind_of should be a kind_of Module.")
full_message = build_message(message, "<?>\nexpected to be kind_of\\?\n<?> but was\n<?>.", object, klass, object.class)
assert_block(full_message){object.kind_of?(klass)}
end
end
##
# Passes if +object+ .respond_to? +method+
#
# Example:
# assert_respond_to 'bugbear', :slice
public
def assert_respond_to(object, method, message="")
_wrap_assertion do
full_message = build_message(nil, "<?>\ngiven as the method name argument to #assert_respond_to must be a Symbol or #respond_to\\?(:to_str).", method)
assert_block(full_message) do
method.kind_of?(Symbol) || method.respond_to?(:to_str)
end
full_message = build_message(message, <<EOT, object, object.class, method)
<?>
of type <?>
expected to respond_to\\?<?>.
EOT
assert_block(full_message) { object.respond_to?(method) }
end
end
##
# Passes if +string+ =~ +pattern+.
#
# Example:
# assert_match(/\d+/, 'five, 6, seven')
public
def assert_match(pattern, string, message="")
_wrap_assertion do
pattern = case(pattern)
when String
Regexp.new(Regexp.escape(pattern))
else
pattern
end
full_message = build_message(message, "<?> expected to be =~\n<?>.", string, pattern)
assert_block(full_message) { string =~ pattern }
end
end
##
# Passes if +actual+ .equal? +expected+ (i.e. they are the same
# instance).
#
# Example:
# o = Object.new
# assert_same o, o
public
def assert_same(expected, actual, message="")
full_message = build_message(message, <<EOT, expected, expected.__id__, actual, actual.__id__)
<?>
with id <?> expected to be equal\\? to
<?>
with id <?>.
EOT
assert_block(full_message) { actual.equal?(expected) }
end
##
# Compares the +object1+ with +object2+ using +operator+.
#
# Passes if object1.__send__(operator, object2) is true.
#
# Example:
# assert_operator 5, :>=, 4
public
def assert_operator(object1, operator, object2, message="")
_wrap_assertion do
full_message = build_message(nil, "<?>\ngiven as the operator for #assert_operator must be a Symbol or #respond_to\\?(:to_str).", operator)
assert_block(full_message){operator.kind_of?(Symbol) || operator.respond_to?(:to_str)}
full_message = build_message(message, <<EOT, object1, AssertionMessage.literal(operator), object2)
<?> expected to be
?
<?>.
EOT
assert_block(full_message) { object1.__send__(operator, object2) }
end
end
##
# Passes if block does not raise an exception.
#
# Example:
# assert_nothing_raised do
# [1, 2].uniq
# end
public
def assert_nothing_raised(*args)
_wrap_assertion do
if Module === args.last
message = ""
else
message = args.pop
end
exceptions, modules = _check_exception_class(args)
begin
yield
rescue Exception => e
if ((args.empty? && !e.instance_of?(AssertionFailedError)) ||
_expected_exception?(e, exceptions, modules))
assert_block(build_message(message, "Exception raised:\n?", e)){false}
else
raise
end
end
nil
end
end
##
# Flunk always fails.
#
# Example:
# flunk 'Not done testing yet.'
public
def flunk(message="Flunked")
assert_block(build_message(message)){false}
end
##
# Passes if ! +actual+ .equal? +expected+
#
# Example:
# assert_not_same Object.new, Object.new
public
def assert_not_same(expected, actual, message="")
full_message = build_message(message, <<EOT, expected, expected.__id__, actual, actual.__id__)
<?>
with id <?> expected to not be equal\\? to
<?>
with id <?>.
EOT
assert_block(full_message) { !actual.equal?(expected) }
end
##
# Passes if +expected+ != +actual+
#
# Example:
# assert_not_equal 'some string', 5
public
def assert_not_equal(expected, actual, message="")
full_message = build_message(message, "<?> expected to be != to\n<?>.", expected, actual)
assert_block(full_message) { expected != actual }
end
##
# Passes if ! +object+ .nil?
#
# Example:
# assert_not_nil '1 two 3'.sub!(/two/, '2')
public
def assert_not_nil(object, message="")
full_message = build_message(message, "<?> expected to not be nil.", object)
assert_block(full_message){!object.nil?}
end
##
# Passes if +regexp+ !~ +string+
#
# Example:
# assert_no_match(/two/, 'one 2 three')
public
def assert_no_match(regexp, string, message="")
_wrap_assertion do
assert_instance_of(Regexp, regexp, "The first argument to assert_no_match should be a Regexp.")
full_message = build_message(message, "<?> expected to not match\n<?>.", regexp, string)
assert_block(full_message) { regexp !~ string }
end
end
UncaughtThrow = {NameError => /^uncaught throw \`(.+)\'$/,
ThreadError => /^uncaught throw \`(.+)\' in thread /} #`
##
# Passes if the block throws +expected_symbol+
#
# Example:
# assert_throws :done do
# throw :done
# end
public
def assert_throws(expected_symbol, message="", &proc)
_wrap_assertion do
assert_instance_of(Symbol, expected_symbol, "assert_throws expects the symbol that should be thrown for its first argument")
assert_block("Should have passed a block to assert_throws."){block_given?}
caught = true
begin
catch(expected_symbol) do
proc.call
caught = false
end
full_message = build_message(message, "<?> should have been thrown.", expected_symbol)
assert_block(full_message){caught}
rescue NameError, ThreadError => error
if UncaughtThrow[error.class] !~ error.message
raise error
end
full_message = build_message(message, "<?> expected to be thrown but\n<?> was thrown.", expected_symbol, $1.intern)
flunk(full_message)
end
end
end
##
# Passes if block does not throw anything.
#
# Example:
# assert_nothing_thrown do
# [1, 2].uniq
# end
public
def assert_nothing_thrown(message="", &proc)
_wrap_assertion do
assert(block_given?, "Should have passed a block to assert_nothing_thrown")
begin
proc.call
rescue NameError, ThreadError => error
if UncaughtThrow[error.class] !~ error.message
raise error
end
full_message = build_message(message, "<?> was thrown when nothing was expected", $1.intern)
flunk(full_message)
end
assert(true, "Expected nothing to be thrown")
end
end
##
# Passes if +expected_float+ and +actual_float+ are equal
# within +delta+ tolerance.
#
# Example:
# assert_in_delta 0.05, (50000.0 / 10**6), 0.00001
public
def assert_in_delta(expected_float, actual_float, delta, message="")
_wrap_assertion do
{expected_float => "first float", actual_float => "second float", delta => "delta"}.each do |float, name|
assert_respond_to(float, :to_f, "The arguments must respond to to_f; the #{name} did not")
end
assert_operator(delta, :>=, 0.0, "The delta should not be negative")
full_message = build_message(message, <<EOT, expected_float, actual_float, delta)
<?> and
<?> expected to be within
<?> of each other.
EOT
assert_block(full_message) { (expected_float.to_f - actual_float.to_f).abs <= delta.to_f }
end
end
##
# Passes if the method send returns a true value.
#
# +send_array+ is composed of:
# * A receiver
# * A method
# * Arguments to the method
#
# Example:
# assert_send [[1, 2], :include?, 4]
public
def assert_send(send_array, message="")
_wrap_assertion do
assert_instance_of(Array, send_array, "assert_send requires an array of send information")
assert(send_array.size >= 2, "assert_send requires at least a receiver and a message name")
full_message = build_message(message, <<EOT, send_array[0], AssertionMessage.literal(send_array[1].to_s), send_array[2..-1])
<?> expected to respond to
<?(?)> with a true value.
EOT
assert_block(full_message) { send_array[0].__send__(send_array[1], *send_array[2..-1]) }
end
end
##
# Builds a failure message. +head+ is added before the +template+ and
# +arguments+ replaces the '?'s positionally in the template.
public
def build_message(head, template=nil, *arguments)
template &&= template.chomp
return AssertionMessage.new(head, template, arguments)
end
private
def _wrap_assertion
@_assertion_wrapped ||= false
unless (@_assertion_wrapped)
@_assertion_wrapped = true
begin
add_assertion
return yield
ensure
@_assertion_wrapped = false
end
else
return yield
end
end
##
# Called whenever an assertion is made. Define this in classes that
# include Test::Unit::Assertions to record assertion counts.
private
def add_assertion
end
##
# Select whether or not to use the pretty-printer. If this option is set
# to false before any assertions are made, pp.rb will not be required.
public
def self.use_pp=(value)
AssertionMessage.use_pp = value
end
# :stopdoc:
class AssertionMessage
@use_pp = true
class << self
attr_accessor :use_pp
end
class Literal
def initialize(value)
@value = value
end
def inspect
@value.to_s
end
end
class Template
def self.create(string)
parts = (string ? string.scan(/(?=[^\\])\?|(?:\\\?|[^\?])+/m) : [])
self.new(parts)
end
attr_reader :count
def initialize(parts)
@parts = parts
@count = parts.find_all{|e| e == '?'}.size
end
def result(parameters)
raise "The number of parameters does not match the number of substitutions." if(parameters.size != count)
params = parameters.dup
@parts.collect{|e| e == '?' ? params.shift : e.gsub(/\\\?/m, '?')}.join('')
end
end
def self.literal(value)
Literal.new(value)
end
include Util::BacktraceFilter
def initialize(head, template_string, parameters)
@head = head
@template_string = template_string
@parameters = parameters
end
def convert(object)
case object
when Exception
<<EOM.chop
Class: <#{convert(object.class)}>
Message: <#{convert(object.message)}>
---Backtrace---
#{filter_backtrace(object.backtrace).join("\n")}
---------------
EOM
else
if(self.class.use_pp)
begin
require 'pp'
rescue LoadError
self.class.use_pp = false
return object.inspect
end unless(defined?(PP))
PP.pp(object, '').chomp
else
object.inspect
end
end
end
def template
@template ||= Template.create(@template_string)
end
def add_period(string)
(string =~ /\.\Z/ ? string : string + '.')
end
def to_s
message_parts = []
if (@head)
head = @head.to_s
unless(head.empty?)
message_parts << add_period(head)
end
end
tail = template.result(@parameters.collect{|e| convert(e)})
message_parts << tail unless(tail.empty?)
message_parts.join("\n")
end
end
# :startdoc:
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/test/unit/autorunner.rb | tools/jruby-1.5.1/lib/ruby/1.8/test/unit/autorunner.rb | require 'test/unit'
require 'test/unit/ui/testrunnerutilities'
require 'optparse'
module Test
module Unit
class AutoRunner
def self.run(force_standalone=false, default_dir=nil, argv=ARGV, &block)
r = new(force_standalone || standalone?, &block)
r.base = default_dir
r.process_args(argv)
r.run
end
def self.standalone?
return false unless("-e" == $0)
ObjectSpace.each_object(Class) do |klass|
return false if(klass < TestCase)
end
true
end
RUNNERS = {
:console => proc do |r|
require 'test/unit/ui/console/testrunner'
Test::Unit::UI::Console::TestRunner
end,
:gtk => proc do |r|
require 'test/unit/ui/gtk/testrunner'
Test::Unit::UI::GTK::TestRunner
end,
:gtk2 => proc do |r|
require 'test/unit/ui/gtk2/testrunner'
Test::Unit::UI::GTK2::TestRunner
end,
:fox => proc do |r|
require 'test/unit/ui/fox/testrunner'
Test::Unit::UI::Fox::TestRunner
end,
:tk => proc do |r|
require 'test/unit/ui/tk/testrunner'
Test::Unit::UI::Tk::TestRunner
end,
}
OUTPUT_LEVELS = [
[:silent, UI::SILENT],
[:progress, UI::PROGRESS_ONLY],
[:normal, UI::NORMAL],
[:verbose, UI::VERBOSE],
]
COLLECTORS = {
:objectspace => proc do |r|
require 'test/unit/collector/objectspace'
c = Collector::ObjectSpace.new
c.filter = r.filters
c.collect($0.sub(/\.rb\Z/, ''))
end,
:dir => proc do |r|
require 'test/unit/collector/dir'
c = Collector::Dir.new
c.filter = r.filters
c.pattern.concat(r.pattern) if(r.pattern)
c.exclude.concat(r.exclude) if(r.exclude)
c.base = r.base
$:.push(r.base) if r.base
c.collect(*(r.to_run.empty? ? ['.'] : r.to_run))
end,
}
attr_reader :suite
attr_accessor :output_level, :filters, :to_run, :pattern, :exclude, :base, :workdir
attr_writer :runner, :collector
def initialize(standalone)
Unit.run = true
@standalone = standalone
@runner = RUNNERS[:console]
@collector = COLLECTORS[(standalone ? :dir : :objectspace)]
@filters = []
@to_run = []
@output_level = UI::NORMAL
@workdir = nil
yield(self) if(block_given?)
end
def process_args(args = ARGV)
begin
options.order!(args) {|arg| @to_run << arg}
rescue OptionParser::ParseError => e
puts e
puts options
$! = nil
abort
else
@filters << proc{false} unless(@filters.empty?)
end
not @to_run.empty?
end
def options
@options ||= OptionParser.new do |o|
o.banner = "Test::Unit automatic runner."
o.banner << "\nUsage: #{$0} [options] [-- untouched arguments]"
o.on
o.on('-r', '--runner=RUNNER', RUNNERS,
"Use the given RUNNER.",
"(" + keyword_display(RUNNERS) + ")") do |r|
@runner = r
end
if(@standalone)
o.on('-b', '--basedir=DIR', "Base directory of test suites.") do |b|
@base = b
end
o.on('-w', '--workdir=DIR', "Working directory to run tests.") do |w|
@workdir = w
end
o.on('-a', '--add=TORUN', Array,
"Add TORUN to the list of things to run;",
"can be a file or a directory.") do |a|
@to_run.concat(a)
end
@pattern = []
o.on('-p', '--pattern=PATTERN', Regexp,
"Match files to collect against PATTERN.") do |e|
@pattern << e
end
@exclude = []
o.on('-x', '--exclude=PATTERN', Regexp,
"Ignore files to collect against PATTERN.") do |e|
@exclude << e
end
end
o.on('-n', '--name=NAME', String,
"Runs tests matching NAME.",
"(patterns may be used).") do |n|
n = (%r{\A/(.*)/\Z} =~ n ? Regexp.new($1) : n)
case n
when Regexp
@filters << proc{|t| n =~ t.method_name ? true : nil}
else
@filters << proc{|t| n == t.method_name ? true : nil}
end
end
o.on('-t', '--testcase=TESTCASE', String,
"Runs tests in TestCases matching TESTCASE.",
"(patterns may be used).") do |n|
n = (%r{\A/(.*)/\Z} =~ n ? Regexp.new($1) : n)
case n
when Regexp
@filters << proc{|t| n =~ t.class.name ? true : nil}
else
@filters << proc{|t| n == t.class.name ? true : nil}
end
end
o.on('-I', "--load-path=DIR[#{File::PATH_SEPARATOR}DIR...]",
"Appends directory list to $LOAD_PATH.") do |dirs|
$LOAD_PATH.concat(dirs.split(File::PATH_SEPARATOR))
end
o.on('-v', '--verbose=[LEVEL]', OUTPUT_LEVELS,
"Set the output level (default is verbose).",
"(" + keyword_display(OUTPUT_LEVELS) + ")") do |l|
@output_level = l || UI::VERBOSE
end
o.on('--',
"Stop processing options so that the",
"remaining options will be passed to the",
"test."){o.terminate}
o.on('-h', '--help', 'Display this help.'){puts o; exit}
o.on_tail
o.on_tail('Deprecated options:')
o.on_tail('--console', 'Console runner (use --runner).') do
warn("Deprecated option (--console).")
@runner = RUNNERS[:console]
end
o.on_tail('--gtk', 'GTK runner (use --runner).') do
warn("Deprecated option (--gtk).")
@runner = RUNNERS[:gtk]
end
o.on_tail('--fox', 'Fox runner (use --runner).') do
warn("Deprecated option (--fox).")
@runner = RUNNERS[:fox]
end
o.on_tail
end
end
def keyword_display(array)
list = array.collect {|e, *| e.to_s}
Array === array or list.sort!
list.collect {|e| e.sub(/^(.)([A-Za-z]+)(?=\w*$)/, '\\1[\\2]')}.join(", ")
end
def run
@suite = @collector[self]
result = @runner[self] or return false
Dir.chdir(@workdir) if @workdir
result.run(@suite, @output_level).passed?
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/test/unit/collector.rb | tools/jruby-1.5.1/lib/ruby/1.8/test/unit/collector.rb | module Test
module Unit
module Collector
def initialize
@filters = []
end
def filter=(filters)
@filters = case(filters)
when Proc
[filters]
when Array
filters
end
end
def add_suite(destination, suite)
to_delete = suite.tests.find_all{|t| !include?(t)}
to_delete.each{|t| suite.delete(t)}
destination << suite unless(suite.size == 0)
end
def include?(test)
return true if(@filters.empty?)
@filters.each do |filter|
result = filter[test]
if(result.nil?)
next
elsif(!result)
return false
else
return true
end
end
true
end
def sort(suites)
suites.sort_by{|s| s.name}
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/test/unit/testsuite.rb | tools/jruby-1.5.1/lib/ruby/1.8/test/unit/testsuite.rb | #--
#
# Author:: Nathaniel Talbott.
# Copyright:: Copyright (c) 2000-2003 Nathaniel Talbott. All rights reserved.
# License:: Ruby license.
module Test
module Unit
# A collection of tests which can be #run.
#
# Note: It is easy to confuse a TestSuite instance with
# something that has a static suite method; I know because _I_
# have trouble keeping them straight. Think of something that
# has a suite method as simply providing a way to get a
# meaningful TestSuite instance.
class TestSuite
attr_reader :name, :tests
STARTED = name + "::STARTED"
FINISHED = name + "::FINISHED"
# Creates a new TestSuite with the given name.
def initialize(name="Unnamed TestSuite")
@name = name
@tests = []
end
# Runs the tests and/or suites contained in this
# TestSuite.
def run(result, &progress_block)
yield(STARTED, name)
@tests.each do |test|
test.run(result, &progress_block)
end
yield(FINISHED, name)
end
# Adds the test to the suite.
def <<(test)
@tests << test
self
end
def delete(test)
@tests.delete(test)
end
# Retuns the rolled up number of tests in this suite;
# i.e. if the suite contains other suites, it counts the
# tests within those suites, not the suites themselves.
def size
total_size = 0
@tests.each { |test| total_size += test.size }
total_size
end
def empty?
tests.empty?
end
# Overridden to return the name given the suite at
# creation.
def to_s
@name
end
# It's handy to be able to compare TestSuite instances.
def ==(other)
return false unless(other.kind_of?(self.class))
return false unless(@name == other.name)
@tests == other.tests
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/test/unit/failure.rb | tools/jruby-1.5.1/lib/ruby/1.8/test/unit/failure.rb | #--
#
# Author:: Nathaniel Talbott.
# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
# License:: Ruby license.
module Test
module Unit
# Encapsulates a test failure. Created by Test::Unit::TestCase
# when an assertion fails.
class Failure
attr_reader :test_name, :location, :message
SINGLE_CHARACTER = 'F'
# Creates a new Failure with the given location and
# message.
def initialize(test_name, location, message)
@test_name = test_name
@location = location
@message = message
end
# Returns a single character representation of a failure.
def single_character_display
SINGLE_CHARACTER
end
# Returns a brief version of the error description.
def short_display
"#@test_name: #{@message.split("\n")[0]}"
end
# Returns a verbose version of the error description.
def long_display
location_display = if(location.size == 1)
location[0].sub(/\A(.+:\d+).*/, ' [\\1]')
else
"\n [#{location.join("\n ")}]"
end
"Failure:\n#@test_name#{location_display}:\n#@message"
end
# Overridden to return long_display.
def to_s
long_display
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/test/unit/testresult.rb | tools/jruby-1.5.1/lib/ruby/1.8/test/unit/testresult.rb | #--
# Author:: Nathaniel Talbott.
# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
# License:: Ruby license.
require 'test/unit/util/observable'
module Test
module Unit
# Collects Test::Unit::Failure and Test::Unit::Error so that
# they can be displayed to the user. To this end, observers
# can be added to it, allowing the dynamic updating of, say, a
# UI.
class TestResult
include Util::Observable
CHANGED = "CHANGED"
FAULT = "FAULT"
attr_reader(:run_count, :assertion_count)
# Constructs a new, empty TestResult.
def initialize
@run_count, @assertion_count = 0, 0
@failures, @errors = Array.new, Array.new
end
# Records a test run.
def add_run
@run_count += 1
notify_listeners(CHANGED, self)
end
# Records a Test::Unit::Failure.
def add_failure(failure)
@failures << failure
notify_listeners(FAULT, failure)
notify_listeners(CHANGED, self)
end
# Records a Test::Unit::Error.
def add_error(error)
@errors << error
notify_listeners(FAULT, error)
notify_listeners(CHANGED, self)
end
# Records an individual assertion.
def add_assertion
@assertion_count += 1
notify_listeners(CHANGED, self)
end
# Returns a string contain the recorded runs, assertions,
# failures and errors in this TestResult.
def to_s
"#{run_count} tests, #{assertion_count} assertions, #{failure_count} failures, #{error_count} errors"
end
# Returns whether or not this TestResult represents
# successful completion.
def passed?
return @failures.empty? && @errors.empty?
end
# Returns the number of failures this TestResult has
# recorded.
def failure_count
return @failures.size
end
# Returns the number of errors this TestResult has
# recorded.
def error_count
return @errors.size
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/test/unit/error.rb | tools/jruby-1.5.1/lib/ruby/1.8/test/unit/error.rb | #--
#
# Author:: Nathaniel Talbott.
# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
# License:: Ruby license.
require 'test/unit/util/backtracefilter'
module Test
module Unit
# Encapsulates an error in a test. Created by
# Test::Unit::TestCase when it rescues an exception thrown
# during the processing of a test.
class Error
include Util::BacktraceFilter
attr_reader(:test_name, :exception)
SINGLE_CHARACTER = 'E'
# Creates a new Error with the given test_name and
# exception.
def initialize(test_name, exception)
@test_name = test_name
@exception = exception
end
# Returns a single character representation of an error.
def single_character_display
SINGLE_CHARACTER
end
# Returns the message associated with the error.
def message
"#{@exception.class.name}: #{@exception.message}"
end
# Returns a brief version of the error description.
def short_display
"#@test_name: #{message.split("\n")[0]}"
end
# Returns a verbose version of the error description.
def long_display
backtrace = filter_backtrace(@exception.backtrace).join("\n ")
"Error:\n#@test_name:\n#{message}\n #{backtrace}"
end
# Overridden to return long_display.
def to_s
long_display
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/test/unit/testcase.rb | tools/jruby-1.5.1/lib/ruby/1.8/test/unit/testcase.rb | #--
#
# Author:: Nathaniel Talbott.
# Copyright:: Copyright (c) 2000-2003 Nathaniel Talbott. All rights reserved.
# License:: Ruby license.
require 'test/unit/assertions'
require 'test/unit/failure'
require 'test/unit/error'
require 'test/unit/testsuite'
require 'test/unit/assertionfailederror'
require 'test/unit/util/backtracefilter'
module Test
module Unit
# Ties everything together. If you subclass and add your own
# test methods, it takes care of making them into tests and
# wrapping those tests into a suite. It also does the
# nitty-gritty of actually running an individual test and
# collecting its results into a Test::Unit::TestResult object.
class TestCase
include Assertions
include Util::BacktraceFilter
attr_reader :method_name
STARTED = name + "::STARTED"
FINISHED = name + "::FINISHED"
##
# These exceptions are not caught by #run.
PASSTHROUGH_EXCEPTIONS = [NoMemoryError, SignalException, Interrupt,
SystemExit]
# Creates a new instance of the fixture for running the
# test represented by test_method_name.
def initialize(test_method_name)
unless(respond_to?(test_method_name) and
(method(test_method_name).arity == 0 ||
method(test_method_name).arity == -1))
throw :invalid_test
end
@method_name = test_method_name
@test_passed = true
end
# Rolls up all of the test* methods in the fixture into
# one suite, creating a new instance of the fixture for
# each method.
def self.suite
method_names = public_instance_methods(true)
tests = method_names.delete_if {|method_name| method_name !~ /^test./}
suite = TestSuite.new(name)
tests.sort.each do
|test|
catch(:invalid_test) do
suite << new(test)
end
end
if (suite.empty?)
catch(:invalid_test) do
suite << new("default_test")
end
end
return suite
end
# Runs the individual test method represented by this
# instance of the fixture, collecting statistics, failures
# and errors in result.
def run(result)
yield(STARTED, name)
@_result = result
begin
setup
__send__(@method_name)
rescue AssertionFailedError => e
add_failure(e.message, e.backtrace)
rescue Exception
raise if PASSTHROUGH_EXCEPTIONS.include? $!.class
add_error($!)
ensure
begin
teardown
rescue AssertionFailedError => e
add_failure(e.message, e.backtrace)
rescue Exception
raise if PASSTHROUGH_EXCEPTIONS.include? $!.class
add_error($!)
end
end
result.add_run
yield(FINISHED, name)
end
# Called before every test method runs. Can be used
# to set up fixture information.
def setup
end
# Called after every test method runs. Can be used to tear
# down fixture information.
def teardown
end
def default_test
flunk("No tests were specified")
end
# Returns whether this individual test passed or
# not. Primarily for use in teardown so that artifacts
# can be left behind if the test fails.
def passed?
return @test_passed
end
private :passed?
def size
1
end
def add_assertion
@_result.add_assertion
end
private :add_assertion
def add_failure(message, all_locations=caller())
@test_passed = false
@_result.add_failure(Failure.new(name, filter_backtrace(all_locations), message))
end
private :add_failure
def add_error(exception)
@test_passed = false
@_result.add_error(Error.new(name, exception))
end
private :add_error
# Returns a human-readable name for the specific test that
# this instance of TestCase represents.
def name
"#{@method_name}(#{self.class.name})"
end
# Overridden to return #name.
def to_s
name
end
# It's handy to be able to compare TestCase instances.
def ==(other)
return false unless(other.kind_of?(self.class))
return false unless(@method_name == other.method_name)
self.class == other.class
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/test/unit/assertionfailederror.rb | tools/jruby-1.5.1/lib/ruby/1.8/test/unit/assertionfailederror.rb | #--
#
# Author:: Nathaniel Talbott.
# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
# License:: Ruby license.
module Test
module Unit
# Thrown by Test::Unit::Assertions when an assertion fails.
class AssertionFailedError < StandardError
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/test/unit/collector/dir.rb | tools/jruby-1.5.1/lib/ruby/1.8/test/unit/collector/dir.rb | require 'test/unit/testsuite'
require 'test/unit/collector'
module Test
module Unit
module Collector
class Dir
include Collector
attr_reader :pattern, :exclude
attr_accessor :base
def initialize(dir=::Dir, file=::File, object_space=::ObjectSpace, req=nil)
super()
@dir = dir
@file = file
@object_space = object_space
@req = req
@pattern = [/\btest_.*\.rb\Z/m]
@exclude = []
end
def collect(*from)
basedir = @base
$:.push(basedir) if basedir
if(from.empty?)
recursive_collect('.', find_test_cases)
elsif(from.size == 1)
recursive_collect(from.first, find_test_cases)
else
suites = []
from.each do |f|
suite = recursive_collect(f, find_test_cases)
suites << suite unless(suite.tests.empty?)
end
suite = TestSuite.new("[#{from.join(', ')}]")
sort(suites).each{|s| suite << s}
suite
end
ensure
$:.delete_at($:.rindex(basedir)) if basedir
end
def find_test_cases(ignore=[])
cases = []
@object_space.each_object(Class) do |c|
cases << c if(c < TestCase && !ignore.include?(c))
end
ignore.concat(cases)
cases
end
def recursive_collect(name, already_gathered)
sub_suites = []
path = realdir(name)
if @file.directory?(path)
dir_name = name unless name == '.'
@dir.entries(path).each do |e|
next if(e == '.' || e == '..')
e_name = dir_name ? @file.join(dir_name, e) : e
if @file.directory?(realdir(e_name))
next if /\ACVS\z/ =~ e
sub_suite = recursive_collect(e_name, already_gathered)
sub_suites << sub_suite unless(sub_suite.empty?)
else
next if /~\z/ =~ e_name or /\A\.\#/ =~ e
if @pattern and !@pattern.empty?
next unless @pattern.any? {|pat| pat =~ e_name}
end
if @exclude and !@exclude.empty?
next if @exclude.any? {|pat| pat =~ e_name}
end
collect_file(e_name, sub_suites, already_gathered)
end
end
else
collect_file(name, sub_suites, already_gathered)
end
suite = TestSuite.new(@file.basename(name))
sort(sub_suites).each{|s| suite << s}
suite
end
def collect_file(name, suites, already_gathered)
dir = @file.dirname(@file.expand_path(name, @base))
$:.unshift(dir)
if(@req)
@req.require(name)
else
require(name)
end
find_test_cases(already_gathered).each{|t| add_suite(suites, t.suite)}
ensure
$:.delete_at($:.rindex(dir)) if(dir)
end
def realdir(path)
if @base
@file.join(@base, path)
else
path
end
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/test/unit/collector/objectspace.rb | tools/jruby-1.5.1/lib/ruby/1.8/test/unit/collector/objectspace.rb | # Author:: Nathaniel Talbott.
# Copyright:: Copyright (c) 2000-2003 Nathaniel Talbott. All rights reserved.
# License:: Ruby license.
require 'test/unit/collector'
module Test
module Unit
module Collector
class ObjectSpace
include Collector
NAME = 'collected from the ObjectSpace'
def initialize(source=::ObjectSpace)
super()
@source = source
end
def collect(name=NAME)
suite = TestSuite.new(name)
sub_suites = []
@source.each_object(Class) do |klass|
if(Test::Unit::TestCase > klass)
add_suite(sub_suites, klass.suite)
end
end
sort(sub_suites).each{|s| suite << s}
suite
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/test/unit/util/backtracefilter.rb | tools/jruby-1.5.1/lib/ruby/1.8/test/unit/util/backtracefilter.rb | module Test
module Unit
module Util
module BacktraceFilter
TESTUNIT_FILE_SEPARATORS = %r{[\\/:]}
TESTUNIT_PREFIX = __FILE__.split(TESTUNIT_FILE_SEPARATORS)[0..-3]
TESTUNIT_RB_FILE = /\.rb\Z/
def filter_backtrace(backtrace, prefix=nil)
return ["No backtrace"] unless(backtrace)
split_p = if(prefix)
prefix.split(TESTUNIT_FILE_SEPARATORS)
else
TESTUNIT_PREFIX
end
match = proc do |e|
split_e = e.split(TESTUNIT_FILE_SEPARATORS)[0, split_p.size]
next false unless(split_e[0..-2] == split_p[0..-2])
split_e[-1].sub(TESTUNIT_RB_FILE, '') == split_p[-1]
end
return backtrace unless(backtrace.detect(&match))
found_prefix = false
new_backtrace = backtrace.reverse.reject do |e|
if(match[e])
found_prefix = true
true
elsif(found_prefix)
false
else
true
end
end.reverse
new_backtrace = (new_backtrace.empty? ? backtrace : new_backtrace)
new_backtrace = new_backtrace.reject(&match)
new_backtrace.empty? ? backtrace : new_backtrace
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/test/unit/util/procwrapper.rb | tools/jruby-1.5.1/lib/ruby/1.8/test/unit/util/procwrapper.rb | #--
#
# Author:: Nathaniel Talbott.
# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
# License:: Ruby license.
module Test
module Unit
module Util
# Allows the storage of a Proc passed through '&' in a
# hash.
#
# Note: this may be inefficient, since the hash being
# used is not necessarily very good. In Observable,
# efficiency is not too important, since the hash is
# only accessed when adding and removing listeners,
# not when notifying.
class ProcWrapper
# Creates a new wrapper for a_proc.
def initialize(a_proc)
@a_proc = a_proc
@hash = a_proc.inspect.sub(/^(#<#{a_proc.class}:)/){''}.sub(/(>)$/){''}.hex
end
def hash
return @hash
end
def ==(other)
case(other)
when ProcWrapper
return @a_proc == other.to_proc
else
return super
end
end
alias :eql? :==
def to_proc
return @a_proc
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/test/unit/util/observable.rb | tools/jruby-1.5.1/lib/ruby/1.8/test/unit/util/observable.rb | #--
#
# Author:: Nathaniel Talbott.
# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
# License:: Ruby license.
require 'test/unit/util/procwrapper'
module Test
module Unit
module Util
# This is a utility class that allows anything mixing
# it in to notify a set of listeners about interesting
# events.
module Observable
# We use this for defaults since nil might mean something
NOTHING = "NOTHING/#{__id__}"
# Adds the passed proc as a listener on the
# channel indicated by channel_name. listener_key
# is used to remove the listener later; if none is
# specified, the proc itself is used.
#
# Whatever is used as the listener_key is
# returned, making it very easy to use the proc
# itself as the listener_key:
#
# listener = add_listener("Channel") { ... }
# remove_listener("Channel", listener)
def add_listener(channel_name, listener_key=NOTHING, &listener) # :yields: value
unless(block_given?)
raise ArgumentError.new("No callback was passed as a listener")
end
key = listener_key
if (listener_key == NOTHING)
listener_key = listener
key = ProcWrapper.new(listener)
end
channels[channel_name] ||= {}
channels[channel_name][key] = listener
return listener_key
end
# Removes the listener indicated by listener_key
# from the channel indicated by
# channel_name. Returns the registered proc, or
# nil if none was found.
def remove_listener(channel_name, listener_key)
channel = channels[channel_name]
return nil unless (channel)
key = listener_key
if (listener_key.instance_of?(Proc))
key = ProcWrapper.new(listener_key)
end
if (channel.has_key?(key))
return channel.delete(key)
end
return nil
end
# Calls all the procs registered on the channel
# indicated by channel_name. If value is
# specified, it is passed in to the procs,
# otherwise they are called with no arguments.
#
#--
#
# Perhaps this should be private? Would it ever
# make sense for an external class to call this
# method directly?
def notify_listeners(channel_name, *arguments)
channel = channels[channel_name]
return 0 unless (channel)
listeners = channel.values
listeners.each { |listener| listener.call(*arguments) }
return listeners.size
end
private
def channels
@channels ||= {}
return @channels
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/test/unit/ui/testrunnermediator.rb | tools/jruby-1.5.1/lib/ruby/1.8/test/unit/ui/testrunnermediator.rb | #--
#
# Author:: Nathaniel Talbott.
# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
# License:: Ruby license.
require 'test/unit'
require 'test/unit/util/observable'
require 'test/unit/testresult'
module Test
module Unit
module UI
# Provides an interface to write any given UI against,
# hopefully making it easy to write new UIs.
class TestRunnerMediator
RESET = name + "::RESET"
STARTED = name + "::STARTED"
FINISHED = name + "::FINISHED"
include Util::Observable
# Creates a new TestRunnerMediator initialized to run
# the passed suite.
def initialize(suite)
@suite = suite
end
# Runs the suite the TestRunnerMediator was created
# with.
def run_suite
Unit.run = true
begin_time = Time.now
notify_listeners(RESET, @suite.size)
result = create_result
notify_listeners(STARTED, result)
result_listener = result.add_listener(TestResult::CHANGED) do |updated_result|
notify_listeners(TestResult::CHANGED, updated_result)
end
fault_listener = result.add_listener(TestResult::FAULT) do |fault|
notify_listeners(TestResult::FAULT, fault)
end
@suite.run(result) do |channel, value|
notify_listeners(channel, value)
end
result.remove_listener(TestResult::FAULT, fault_listener)
result.remove_listener(TestResult::CHANGED, result_listener)
end_time = Time.now
elapsed_time = end_time - begin_time
notify_listeners(FINISHED, elapsed_time) #"Finished in #{elapsed_time} seconds.")
return result
end
private
# A factory method to create the result the mediator
# should run with. Can be overridden by subclasses if
# one wants to use a different result.
def create_result
return TestResult.new
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/test/unit/ui/testrunnerutilities.rb | tools/jruby-1.5.1/lib/ruby/1.8/test/unit/ui/testrunnerutilities.rb | #--
#
# Author:: Nathaniel Talbott.
# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
# License:: Ruby license.
module Test
module Unit
module UI
SILENT = 0
PROGRESS_ONLY = 1
NORMAL = 2
VERBOSE = 3
# Provides some utilities common to most, if not all,
# TestRunners.
#
#--
#
# Perhaps there ought to be a TestRunner superclass? There
# seems to be a decent amount of shared code between test
# runners.
module TestRunnerUtilities
# Creates a new TestRunner and runs the suite.
def run(suite, output_level=NORMAL)
return new(suite, output_level).start
end
# Takes care of the ARGV parsing and suite
# determination necessary for running one of the
# TestRunners from the command line.
def start_command_line_test
if ARGV.empty?
puts "You should supply the name of a test suite file to the runner"
exit
end
require ARGV[0].gsub(/.+::/, '')
new(eval(ARGV[0])).start
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/test/unit/ui/gtk/testrunner.rb | tools/jruby-1.5.1/lib/ruby/1.8/test/unit/ui/gtk/testrunner.rb | #--
#
# Author:: Nathaniel Talbott.
# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
# License:: Ruby license.
require 'gtk'
require 'test/unit/ui/testrunnermediator'
require 'test/unit/ui/testrunnerutilities'
module Test
module Unit
module UI
module GTK
# Runs a Test::Unit::TestSuite in a Gtk UI. Obviously,
# this one requires you to have Gtk
# (http://www.gtk.org/) and the Ruby Gtk extension
# (http://ruby-gnome.sourceforge.net/) installed.
class TestRunner
extend TestRunnerUtilities
# Creates a new TestRunner for running the passed
# suite.
def initialize(suite, output_level = NORMAL)
if (suite.respond_to?(:suite))
@suite = suite.suite
else
@suite = suite
end
@result = nil
@runner = Thread.current
@restart_signal = Class.new(Exception)
@viewer = Thread.start do
@runner.join rescue @runner.run
Gtk.main
end
@viewer.join rescue nil # wait deadlock to handshake
end
# Begins the test run.
def start
setup_mediator
setup_ui
attach_to_mediator
start_ui
@result
end
private
def setup_mediator
@mediator = TestRunnerMediator.new(@suite)
suite_name = @suite.to_s
if ( @suite.kind_of?(Module) )
suite_name = @suite.name
end
suite_name_entry.set_text(suite_name)
end
def attach_to_mediator
run_button.signal_connect("clicked", nil, &method(:run_test))
@mediator.add_listener(TestRunnerMediator::RESET, &method(:reset_ui))
@mediator.add_listener(TestResult::FAULT, &method(:add_fault))
@mediator.add_listener(TestResult::CHANGED, &method(:result_changed))
@mediator.add_listener(TestRunnerMediator::STARTED, &method(:started))
@mediator.add_listener(TestCase::STARTED, &method(:test_started))
@mediator.add_listener(TestCase::FINISHED, &method(:test_finished))
@mediator.add_listener(TestRunnerMediator::FINISHED, &method(:finished))
end
def run_test(*)
@runner.raise(@restart_signal)
end
def start_ui
@viewer.run
running = false
begin
loop do
if (running ^= true)
run_button.child.text = "Stop"
@mediator.run_suite
else
run_button.child.text = "Run"
@viewer.join
break
end
end
rescue @restart_signal
retry
rescue
end
end
def stop(*)
Gtk.main_quit
end
def reset_ui(count)
test_progress_bar.set_style(green_style)
test_progress_bar.configure(0, 0, count)
@red = false
run_count_label.set_text("0")
assertion_count_label.set_text("0")
failure_count_label.set_text("0")
error_count_label.set_text("0")
fault_list.remove_items(fault_list.children)
end
def add_fault(fault)
if ( ! @red )
test_progress_bar.set_style(red_style)
@red = true
end
item = FaultListItem.new(fault)
item.show
fault_list.append_items([item])
end
def show_fault(fault)
raw_show_fault(fault.long_display)
end
def raw_show_fault(string)
fault_detail_label.set_text(string)
outer_detail_sub_panel.queue_resize
end
def clear_fault
raw_show_fault("")
end
def result_changed(result)
run_count_label.set_text(result.run_count.to_s)
assertion_count_label.set_text(result.assertion_count.to_s)
failure_count_label.set_text(result.failure_count.to_s)
error_count_label.set_text(result.error_count.to_s)
end
def started(result)
@result = result
output_status("Started...")
end
def test_started(test_name)
output_status("Running #{test_name}...")
end
def test_finished(test_name)
test_progress_bar.set_value(test_progress_bar.get_value + 1)
end
def finished(elapsed_time)
output_status("Finished in #{elapsed_time} seconds")
end
def output_status(string)
status_entry.set_text(string)
end
def setup_ui
main_window.signal_connect("destroy", nil, &method(:stop))
main_window.show_all
fault_list.signal_connect("select-child", nil) {
| list, item, data |
show_fault(item.fault)
}
fault_list.signal_connect("unselect-child", nil) {
clear_fault
}
@red = false
end
def main_window
lazy_initialize(:main_window) {
@main_window = Gtk::Window.new(Gtk::WINDOW_TOPLEVEL)
@main_window.set_title("Test::Unit TestRunner")
@main_window.set_usize(800, 600)
@main_window.set_uposition(20, 20)
@main_window.set_policy(true, true, false)
@main_window.add(main_panel)
}
end
def main_panel
lazy_initialize(:main_panel) {
@main_panel = Gtk::VBox.new(false, 0)
@main_panel.pack_start(suite_panel, false, false, 0)
@main_panel.pack_start(progress_panel, false, false, 0)
@main_panel.pack_start(info_panel, false, false, 0)
@main_panel.pack_start(list_panel, false, false, 0)
@main_panel.pack_start(detail_panel, true, true, 0)
@main_panel.pack_start(status_panel, false, false, 0)
}
end
def suite_panel
lazy_initialize(:suite_panel) {
@suite_panel = Gtk::HBox.new(false, 10)
@suite_panel.border_width(10)
@suite_panel.pack_start(Gtk::Label.new("Suite:"), false, false, 0)
@suite_panel.pack_start(suite_name_entry, true, true, 0)
@suite_panel.pack_start(run_button, false, false, 0)
}
end
def suite_name_entry
lazy_initialize(:suite_name_entry) {
@suite_name_entry = Gtk::Entry.new
@suite_name_entry.set_editable(false)
}
end
def run_button
lazy_initialize(:run_button) {
@run_button = Gtk::Button.new("Run")
}
end
def progress_panel
lazy_initialize(:progress_panel) {
@progress_panel = Gtk::HBox.new(false, 10)
@progress_panel.border_width(10)
@progress_panel.pack_start(test_progress_bar, true, true, 0)
}
end
def test_progress_bar
lazy_initialize(:test_progress_bar) {
@test_progress_bar = EnhancedProgressBar.new
@test_progress_bar.set_usize(@test_progress_bar.allocation.width,
info_panel.size_request.height)
@test_progress_bar.set_style(green_style)
}
end
def green_style
lazy_initialize(:green_style) {
@green_style = Gtk::Style.new
@green_style.set_bg(Gtk::STATE_PRELIGHT, 0x0000, 0xFFFF, 0x0000)
}
end
def red_style
lazy_initialize(:red_style) {
@red_style = Gtk::Style.new
@red_style.set_bg(Gtk::STATE_PRELIGHT, 0xFFFF, 0x0000, 0x0000)
}
end
def info_panel
lazy_initialize(:info_panel) {
@info_panel = Gtk::HBox.new(false, 0)
@info_panel.border_width(10)
@info_panel.pack_start(Gtk::Label.new("Runs:"), false, false, 0)
@info_panel.pack_start(run_count_label, true, false, 0)
@info_panel.pack_start(Gtk::Label.new("Assertions:"), false, false, 0)
@info_panel.pack_start(assertion_count_label, true, false, 0)
@info_panel.pack_start(Gtk::Label.new("Failures:"), false, false, 0)
@info_panel.pack_start(failure_count_label, true, false, 0)
@info_panel.pack_start(Gtk::Label.new("Errors:"), false, false, 0)
@info_panel.pack_start(error_count_label, true, false, 0)
}
end
def run_count_label
lazy_initialize(:run_count_label) {
@run_count_label = Gtk::Label.new("0")
@run_count_label.set_justify(Gtk::JUSTIFY_LEFT)
}
end
def assertion_count_label
lazy_initialize(:assertion_count_label) {
@assertion_count_label = Gtk::Label.new("0")
@assertion_count_label.set_justify(Gtk::JUSTIFY_LEFT)
}
end
def failure_count_label
lazy_initialize(:failure_count_label) {
@failure_count_label = Gtk::Label.new("0")
@failure_count_label.set_justify(Gtk::JUSTIFY_LEFT)
}
end
def error_count_label
lazy_initialize(:error_count_label) {
@error_count_label = Gtk::Label.new("0")
@error_count_label.set_justify(Gtk::JUSTIFY_LEFT)
}
end
def list_panel
lazy_initialize(:list_panel) {
@list_panel = Gtk::HBox.new
@list_panel.border_width(10)
@list_panel.pack_start(list_scrolled_window, true, true, 0)
}
end
def list_scrolled_window
lazy_initialize(:list_scrolled_window) {
@list_scrolled_window = Gtk::ScrolledWindow.new
@list_scrolled_window.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC)
@list_scrolled_window.set_usize(@list_scrolled_window.allocation.width, 150)
@list_scrolled_window.add_with_viewport(fault_list)
}
end
def fault_list
lazy_initialize(:fault_list) {
@fault_list = Gtk::List.new
}
end
def detail_panel
lazy_initialize(:detail_panel) {
@detail_panel = Gtk::HBox.new
@detail_panel.border_width(10)
@detail_panel.pack_start(detail_scrolled_window, true, true, 0)
}
end
def detail_scrolled_window
lazy_initialize(:detail_scrolled_window) {
@detail_scrolled_window = Gtk::ScrolledWindow.new
@detail_scrolled_window.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC)
@detail_scrolled_window.set_usize(400, @detail_scrolled_window.allocation.height)
@detail_scrolled_window.add_with_viewport(outer_detail_sub_panel)
}
end
def outer_detail_sub_panel
lazy_initialize(:outer_detail_sub_panel) {
@outer_detail_sub_panel = Gtk::VBox.new
@outer_detail_sub_panel.pack_start(inner_detail_sub_panel, false, false, 0)
}
end
def inner_detail_sub_panel
lazy_initialize(:inner_detail_sub_panel) {
@inner_detail_sub_panel = Gtk::HBox.new
@inner_detail_sub_panel.pack_start(fault_detail_label, false, false, 0)
}
end
def fault_detail_label
lazy_initialize(:fault_detail_label) {
@fault_detail_label = EnhancedLabel.new("")
style = Gtk::Style.new
font = Gdk::Font.font_load("-*-Courier New-medium-r-normal--*-120-*-*-*-*-*-*")
begin
style.set_font(font)
rescue ArgumentError; end
@fault_detail_label.set_style(style)
@fault_detail_label.set_justify(Gtk::JUSTIFY_LEFT)
@fault_detail_label.set_line_wrap(false)
}
end
def status_panel
lazy_initialize(:status_panel) {
@status_panel = Gtk::HBox.new
@status_panel.border_width(10)
@status_panel.pack_start(status_entry, true, true, 0)
}
end
def status_entry
lazy_initialize(:status_entry) {
@status_entry = Gtk::Entry.new
@status_entry.set_editable(false)
}
end
def lazy_initialize(symbol)
if (!instance_eval("defined?(@#{symbol.to_s})"))
yield
end
return instance_eval("@" + symbol.to_s)
end
end
class EnhancedProgressBar < Gtk::ProgressBar
def set_style(style)
super
hide
show
end
end
class EnhancedLabel < Gtk::Label
def set_text(text)
super(text.gsub(/\n\t/, "\n" + (" " * 4)))
end
end
class FaultListItem < Gtk::ListItem
attr_reader(:fault)
def initialize(fault)
super(fault.short_display)
@fault = fault
end
end
end
end
end
end
if __FILE__ == $0
Test::Unit::UI::GTK::TestRunner.start_command_line_test
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/test/unit/ui/tk/testrunner.rb | tools/jruby-1.5.1/lib/ruby/1.8/test/unit/ui/tk/testrunner.rb | #--
#
# Original Author:: Nathaniel Talbott.
# Author:: Kazuhiro NISHIYAMA.
# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
# Copyright:: Copyright (c) 2003 Kazuhiro NISHIYAMA. All rights reserved.
# License:: Ruby license.
require 'tk'
require 'test/unit/ui/testrunnermediator'
require 'test/unit/ui/testrunnerutilities'
module Test
module Unit
module UI
module Tk
# Runs a Test::Unit::TestSuite in a Tk UI. Obviously,
# this one requires you to have Tk
# and the Ruby Tk extension installed.
class TestRunner
extend TestRunnerUtilities
# Creates a new TestRunner for running the passed
# suite.
def initialize(suite, output_level = NORMAL)
if (suite.respond_to?(:suite))
@suite = suite.suite
else
@suite = suite
end
@result = nil
@red = false
@fault_detail_list = []
@runner = Thread.current
@restart_signal = Class.new(Exception)
@viewer = Thread.start do
@runner.join rescue @runner.run
::Tk.mainloop
end
@viewer.join rescue nil # wait deadlock to handshake
end
# Begins the test run.
def start
setup_ui
setup_mediator
attach_to_mediator
start_ui
@result
end
private
def setup_mediator
@mediator = TestRunnerMediator.new(@suite)
suite_name = @suite.to_s
if ( @suite.kind_of?(Module) )
suite_name = @suite.name
end
@suite_name_entry.value = suite_name
end
def attach_to_mediator
@run_button.command(method(:run_test))
@fault_list.bind('ButtonPress-1', proc{|y|
fault = @fault_detail_list[@fault_list.nearest(y)]
if fault
show_fault(fault)
end
}, '%y')
@mediator.add_listener(TestRunnerMediator::RESET, &method(:reset_ui))
@mediator.add_listener(TestResult::FAULT, &method(:add_fault))
@mediator.add_listener(TestResult::CHANGED, &method(:result_changed))
@mediator.add_listener(TestRunnerMediator::STARTED, &method(:started))
@mediator.add_listener(TestCase::STARTED, &method(:test_started))
@mediator.add_listener(TestRunnerMediator::FINISHED, &method(:finished))
end
def run_test
@runner.raise(@restart_signal)
end
def start_ui
@viewer.run
running = false
begin
loop do
if (running ^= true)
@run_button.configure('text'=>'Stop')
@mediator.run_suite
else
@run_button.configure('text'=>'Run')
@viewer.join
break
end
end
rescue @restart_signal
retry
rescue
end
end
def stop
::Tk.exit
end
def reset_ui(count)
@test_total_count = count.to_f
@test_progress_bar.configure('background'=>'green')
@test_progress_bar.place('relwidth'=>(count.zero? ? 0 : 0/count))
@red = false
@test_count_label.value = 0
@assertion_count_label.value = 0
@failure_count_label.value = 0
@error_count_label.value = 0
@fault_list.delete(0, 'end')
@fault_detail_list = []
clear_fault
end
def add_fault(fault)
if ( ! @red )
@test_progress_bar.configure('background'=>'red')
@red = true
end
@fault_detail_list.push fault
@fault_list.insert('end', fault.short_display)
end
def show_fault(fault)
raw_show_fault(fault.long_display)
end
def raw_show_fault(string)
@detail_text.value = string
end
def clear_fault
raw_show_fault("")
end
def result_changed(result)
@test_count_label.value = result.run_count
@test_progress_bar.place('relwidth'=>result.run_count/@test_total_count)
@assertion_count_label.value = result.assertion_count
@failure_count_label.value = result.failure_count
@error_count_label.value = result.error_count
end
def started(result)
@result = result
output_status("Started...")
end
def test_started(test_name)
output_status("Running #{test_name}...")
end
def finished(elapsed_time)
output_status("Finished in #{elapsed_time} seconds")
end
def output_status(string)
@status_entry.value = string
end
def setup_ui
@status_entry = TkVariable.new
l = TkLabel.new(nil, 'textvariable'=>@status_entry, 'relief'=>'sunken')
l.pack('side'=>'bottom', 'fill'=>'x')
suite_frame = TkFrame.new.pack('fill'=>'x')
@run_button = TkButton.new(suite_frame, 'text'=>'Run')
@run_button.pack('side'=>'right')
TkLabel.new(suite_frame, 'text'=>'Suite:').pack('side'=>'left')
@suite_name_entry = TkVariable.new
l = TkLabel.new(suite_frame, 'textvariable'=>@suite_name_entry, 'relief'=>'sunken')
l.pack('side'=>'left', 'fill'=>'x', 'expand'=>true)
f = TkFrame.new(nil, 'relief'=>'sunken', 'borderwidth'=>3, 'height'=>20).pack('fill'=>'x', 'padx'=>1)
@test_progress_bar = TkFrame.new(f, 'background'=>'green').place('anchor'=>'nw', 'relwidth'=>0.0, 'relheight'=>1.0)
info_frame = TkFrame.new.pack('fill'=>'x')
@test_count_label = create_count_label(info_frame, 'Tests:')
@assertion_count_label = create_count_label(info_frame, 'Assertions:')
@failure_count_label = create_count_label(info_frame, 'Failures:')
@error_count_label = create_count_label(info_frame, 'Errors:')
if (::Tk.info('command', TkPanedWindow::TkCommandNames[0]) != "")
# use panedwindow
paned_frame = TkPanedWindow.new("orient"=>"vertical").pack('fill'=>'both', 'expand'=>true)
fault_list_frame = TkFrame.new(paned_frame)
detail_frame = TkFrame.new(paned_frame)
paned_frame.add(fault_list_frame, detail_frame)
else
# no panedwindow
paned_frame = nil
fault_list_frame = TkFrame.new.pack('fill'=>'both', 'expand'=>true)
detail_frame = TkFrame.new.pack('fill'=>'both', 'expand'=>true)
end
TkGrid.rowconfigure(fault_list_frame, 0, 'weight'=>1, 'minsize'=>0)
TkGrid.columnconfigure(fault_list_frame, 0, 'weight'=>1, 'minsize'=>0)
fault_scrollbar_y = TkScrollbar.new(fault_list_frame)
fault_scrollbar_x = TkScrollbar.new(fault_list_frame)
@fault_list = TkListbox.new(fault_list_frame)
@fault_list.yscrollbar(fault_scrollbar_y)
@fault_list.xscrollbar(fault_scrollbar_x)
TkGrid.rowconfigure(detail_frame, 0, 'weight'=>1, 'minsize'=>0)
TkGrid.columnconfigure(detail_frame, 0, 'weight'=>1, 'minsize'=>0)
::Tk.grid(@fault_list, fault_scrollbar_y, 'sticky'=>'news')
::Tk.grid(fault_scrollbar_x, 'sticky'=>'news')
detail_scrollbar_y = TkScrollbar.new(detail_frame)
detail_scrollbar_x = TkScrollbar.new(detail_frame)
@detail_text = TkText.new(detail_frame, 'height'=>10, 'wrap'=>'none') {
bindtags(bindtags - [TkText])
}
@detail_text.yscrollbar(detail_scrollbar_y)
@detail_text.xscrollbar(detail_scrollbar_x)
::Tk.grid(@detail_text, detail_scrollbar_y, 'sticky'=>'news')
::Tk.grid(detail_scrollbar_x, 'sticky'=>'news')
# rubber-style pane
if paned_frame
::Tk.update
@height = paned_frame.winfo_height
paned_frame.bind('Configure', proc{|h|
paned_frame.sash_place(0, 0, paned_frame.sash_coord(0)[1] * h / @height)
@height = h
}, '%h')
end
end
def create_count_label(parent, label)
TkLabel.new(parent, 'text'=>label).pack('side'=>'left', 'expand'=>true)
v = TkVariable.new(0)
TkLabel.new(parent, 'textvariable'=>v).pack('side'=>'left', 'expand'=>true)
v
end
end
end
end
end
end
if __FILE__ == $0
Test::Unit::UI::Tk::TestRunner.start_command_line_test
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/test/unit/ui/console/testrunner.rb | tools/jruby-1.5.1/lib/ruby/1.8/test/unit/ui/console/testrunner.rb | #--
#
# Author:: Nathaniel Talbott.
# Copyright:: Copyright (c) 2000-2003 Nathaniel Talbott. All rights reserved.
# License:: Ruby license.
require 'test/unit/ui/testrunnermediator'
require 'test/unit/ui/testrunnerutilities'
module Test
module Unit
module UI
module Console
# Runs a Test::Unit::TestSuite on the console.
class TestRunner
extend TestRunnerUtilities
# Creates a new TestRunner for running the passed
# suite. If quiet_mode is true, the output while
# running is limited to progress dots, errors and
# failures, and the final result. io specifies
# where runner output should go to; defaults to
# STDOUT.
def initialize(suite, output_level=NORMAL, io=STDOUT)
if (suite.respond_to?(:suite))
@suite = suite.suite
else
@suite = suite
end
@output_level = output_level
@io = io
@already_outputted = false
@faults = []
end
# Begins the test run.
def start
setup_mediator
attach_to_mediator
return start_mediator
end
private
def setup_mediator
@mediator = create_mediator(@suite)
suite_name = @suite.to_s
if ( @suite.kind_of?(Module) )
suite_name = @suite.name
end
output("Loaded suite #{suite_name}")
end
def create_mediator(suite)
return TestRunnerMediator.new(suite)
end
def attach_to_mediator
@mediator.add_listener(TestResult::FAULT, &method(:add_fault))
@mediator.add_listener(TestRunnerMediator::STARTED, &method(:started))
@mediator.add_listener(TestRunnerMediator::FINISHED, &method(:finished))
@mediator.add_listener(TestCase::STARTED, &method(:test_started))
@mediator.add_listener(TestCase::FINISHED, &method(:test_finished))
end
def start_mediator
return @mediator.run_suite
end
def add_fault(fault)
@faults << fault
output_single(fault.single_character_display, PROGRESS_ONLY)
@already_outputted = true
end
def started(result)
@result = result
output("Started")
end
def finished(elapsed_time)
nl
output("Finished in #{elapsed_time} seconds.")
@faults.each_with_index do |fault, index|
nl
output("%3d) %s" % [index + 1, fault.long_display])
end
nl
output(@result)
end
def test_started(name)
output_single(name + ": ", VERBOSE)
end
def test_finished(name)
output_single(".", PROGRESS_ONLY) unless (@already_outputted)
nl(VERBOSE)
@already_outputted = false
end
def nl(level=NORMAL)
output("", level)
end
def output(something, level=NORMAL)
@io.puts(something) if (output?(level))
@io.flush
end
def output_single(something, level=NORMAL)
@io.write(something) if (output?(level))
@io.flush
end
def output?(level)
level <= @output_level
end
end
end
end
end
end
if __FILE__ == $0
Test::Unit::UI::Console::TestRunner.start_command_line_test
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/test/unit/ui/gtk2/testrunner.rb | tools/jruby-1.5.1/lib/ruby/1.8/test/unit/ui/gtk2/testrunner.rb | #--
#
# Author:: Kenta MURATA.
# Copyright:: Copyright (c) 2000-2002 Kenta MURATA. All rights reserved.
# License:: Ruby license.
require "gtk2"
require "test/unit/ui/testrunnermediator"
require "test/unit/ui/testrunnerutilities"
module Test
module Unit
module UI
module GTK2
Gtk.init
class EnhancedLabel < Gtk::Label
def set_text(text)
super(text.gsub(/\n\t/, "\n "))
end
end
class FaultList < Gtk::TreeView
def initialize
@faults = []
@model = Gtk::ListStore.new(String, String)
super(@model)
column = Gtk::TreeViewColumn.new
column.visible = false
append_column(column)
renderer = Gtk::CellRendererText.new
column = Gtk::TreeViewColumn.new("Failures", renderer, {:text => 1})
append_column(column)
selection.mode = Gtk::SELECTION_SINGLE
set_rules_hint(true)
set_headers_visible(false)
end # def initialize
def add_fault(fault)
@faults.push(fault)
iter = @model.append
iter.set_value(0, (@faults.length - 1).to_s)
iter.set_value(1, fault.short_display)
end # def add_fault(fault)
def get_fault(iter)
@faults[iter.get_value(0).to_i]
end # def get_fault
def clear
model.clear
end # def clear
end
class TestRunner
extend TestRunnerUtilities
def lazy_initialize(symbol)
if !instance_eval("defined?(@#{symbol})") then
yield
end
return instance_eval("@#{symbol}")
end
private :lazy_initialize
def status_entry
lazy_initialize(:status_entry) do
@status_entry = Gtk::Entry.new
@status_entry.editable = false
end
end
private :status_entry
def status_panel
lazy_initialize(:status_panel) do
@status_panel = Gtk::HBox.new
@status_panel.border_width = 10
@status_panel.pack_start(status_entry, true, true, 0)
end
end
private :status_panel
def fault_detail_label
lazy_initialize(:fault_detail_label) do
@fault_detail_label = EnhancedLabel.new("")
# style = Gtk::Style.new
# font = Gdk::Font.
# font_load("-*-Courier 10 Pitch-medium-r-normal--*-120-*-*-*-*-*-*")
# style.set_font(font)
# @fault_detail_label.style = style
@fault_detail_label.justify = Gtk::JUSTIFY_LEFT
@fault_detail_label.wrap = false
end
end
private :fault_detail_label
def inner_detail_sub_panel
lazy_initialize(:inner_detail_sub_panel) do
@inner_detail_sub_panel = Gtk::HBox.new
@inner_detail_sub_panel.pack_start(fault_detail_label, false, false, 0)
end
end
private :inner_detail_sub_panel
def outer_detail_sub_panel
lazy_initialize(:outer_detail_sub_panel) do
@outer_detail_sub_panel = Gtk::VBox.new
@outer_detail_sub_panel.pack_start(inner_detail_sub_panel, false, false, 0)
end
end
private :outer_detail_sub_panel
def detail_scrolled_window
lazy_initialize(:detail_scrolled_window) do
@detail_scrolled_window = Gtk::ScrolledWindow.new
@detail_scrolled_window.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC)
@detail_scrolled_window.
set_size_request(400, @detail_scrolled_window.allocation.height)
@detail_scrolled_window.add_with_viewport(outer_detail_sub_panel)
end
end
private :detail_scrolled_window
def detail_panel
lazy_initialize(:detail_panel) do
@detail_panel = Gtk::HBox.new
@detail_panel.border_width = 10
@detail_panel.pack_start(detail_scrolled_window, true, true, 0)
end
end
private :detail_panel
def fault_list
lazy_initialize(:fault_list) do
@fault_list = FaultList.new
end
end
private :fault_list
def list_scrolled_window
lazy_initialize(:list_scrolled_window) do
@list_scrolled_window = Gtk::ScrolledWindow.new
@list_scrolled_window.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC)
@list_scrolled_window.
set_size_request(@list_scrolled_window.allocation.width, 150)
@list_scrolled_window.add_with_viewport(fault_list)
end
end
private :list_scrolled_window
def list_panel
lazy_initialize(:list_panel) do
@list_panel = Gtk::HBox.new
@list_panel.border_width = 10
@list_panel.pack_start(list_scrolled_window, true, true, 0)
end
end
private :list_panel
def error_count_label
lazy_initialize(:error_count_label) do
@error_count_label = Gtk::Label.new("0")
@error_count_label.justify = Gtk::JUSTIFY_LEFT
end
end
private :error_count_label
def failure_count_label
lazy_initialize(:failure_count_label) do
@failure_count_label = Gtk::Label.new("0")
@failure_count_label.justify = Gtk::JUSTIFY_LEFT
end
end
private :failure_count_label
def assertion_count_label
lazy_initialize(:assertion_count_label) do
@assertion_count_label = Gtk::Label.new("0")
@assertion_count_label.justify = Gtk::JUSTIFY_LEFT
end
end
private :assertion_count_label
def run_count_label
lazy_initialize(:run_count_label) do
@run_count_label = Gtk::Label.new("0")
@run_count_label.justify = Gtk::JUSTIFY_LEFT
end
end
private :run_count_label
def info_panel
lazy_initialize(:info_panel) do
@info_panel = Gtk::HBox.new(false, 0)
@info_panel.border_width = 10
@info_panel.pack_start(Gtk::Label.new("Runs:"), false, false, 0)
@info_panel.pack_start(run_count_label, true, false, 0)
@info_panel.pack_start(Gtk::Label.new("Assertions:"), false, false, 0)
@info_panel.pack_start(assertion_count_label, true, false, 0)
@info_panel.pack_start(Gtk::Label.new("Failures:"), false, false, 0)
@info_panel.pack_start(failure_count_label, true, false, 0)
@info_panel.pack_start(Gtk::Label.new("Errors:"), false, false, 0)
@info_panel.pack_start(error_count_label, true, false, 0)
end
end # def info_panel
private :info_panel
def green_style
lazy_initialize(:green_style) do
@green_style = Gtk::Style.new
@green_style.set_bg(Gtk::STATE_PRELIGHT, 0x0000, 0xFFFF, 0x0000)
end
end # def green_style
private :green_style
def red_style
lazy_initialize(:red_style) do
@red_style = Gtk::Style.new
@red_style.set_bg(Gtk::STATE_PRELIGHT, 0xFFFF, 0x0000, 0x0000)
end
end # def red_style
private :red_style
def test_progress_bar
lazy_initialize(:test_progress_bar) {
@test_progress_bar = Gtk::ProgressBar.new
@test_progress_bar.fraction = 0.0
@test_progress_bar.
set_size_request(@test_progress_bar.allocation.width,
info_panel.size_request[1])
@test_progress_bar.style = green_style
}
end # def test_progress_bar
private :test_progress_bar
def progress_panel
lazy_initialize(:progress_panel) do
@progress_panel = Gtk::HBox.new(false, 10)
@progress_panel.border_width = 10
@progress_panel.pack_start(test_progress_bar, true, true, 0)
end
end # def progress_panel
def run_button
lazy_initialize(:run_button) do
@run_button = Gtk::Button.new("Run")
end
end # def run_button
def suite_name_entry
lazy_initialize(:suite_name_entry) do
@suite_name_entry = Gtk::Entry.new
@suite_name_entry.editable = false
end
end # def suite_name_entry
private :suite_name_entry
def suite_panel
lazy_initialize(:suite_panel) do
@suite_panel = Gtk::HBox.new(false, 10)
@suite_panel.border_width = 10
@suite_panel.pack_start(Gtk::Label.new("Suite:"), false, false, 0)
@suite_panel.pack_start(suite_name_entry, true, true, 0)
@suite_panel.pack_start(run_button, false, false, 0)
end
end # def suite_panel
private :suite_panel
def main_panel
lazy_initialize(:main_panel) do
@main_panel = Gtk::VBox.new(false, 0)
@main_panel.pack_start(suite_panel, false, false, 0)
@main_panel.pack_start(progress_panel, false, false, 0)
@main_panel.pack_start(info_panel, false, false, 0)
@main_panel.pack_start(list_panel, false, false, 0)
@main_panel.pack_start(detail_panel, true, true, 0)
@main_panel.pack_start(status_panel, false, false, 0)
end
end # def main_panel
private :main_panel
def main_window
lazy_initialize(:main_window) do
@main_window = Gtk::Window.new(Gtk::Window::TOPLEVEL)
@main_window.set_title("Test::Unit TestRunner")
@main_window.set_default_size(800, 600)
@main_window.set_resizable(true)
@main_window.add(main_panel)
end
end # def main_window
private :main_window
def setup_ui
main_window.signal_connect("destroy", nil) { stop }
main_window.show_all
fault_list.selection.signal_connect("changed", nil) do
|selection, data|
if selection.selected then
show_fault(fault_list.get_fault(selection.selected))
else
clear_fault
end
end
end # def setup_ui
private :setup_ui
def output_status(string)
status_entry.set_text(string)
end # def output_status(string)
private :output_status
def finished(elapsed_time)
test_progress_bar.fraction = 1.0
output_status("Finished in #{elapsed_time} seconds")
end # def finished(elapsed_time)
private :finished
def test_started(test_name)
output_status("Running #{test_name}...")
end # def test_started(test_name)
private :test_started
def started(result)
@result = result
output_status("Started...")
end # def started(result)
private :started
def test_finished(result)
test_progress_bar.fraction += 1.0 / @count
end # def test_finished(result)
def result_changed(result)
run_count_label.label = result.run_count.to_s
assertion_count_label.label = result.assertion_count.to_s
failure_count_label.label = result.failure_count.to_s
error_count_label.label = result.error_count.to_s
end # def result_changed(result)
private :result_changed
def clear_fault
raw_show_fault("")
end # def clear_fault
private :clear_fault
def raw_show_fault(string)
fault_detail_label.set_text(string)
outer_detail_sub_panel.queue_resize
end # def raw_show_fault(string)
private :raw_show_fault
def show_fault(fault)
raw_show_fault(fault.long_display)
end # def show_fault(fault)
private :show_fault
def add_fault(fault)
if not @red then
test_progress_bar.style = red_style
@red = true
end
fault_list.add_fault(fault)
end # def add_fault(fault)
private :add_fault
def reset_ui(count)
test_progress_bar.style = green_style
test_progress_bar.fraction = 0.0
@count = count + 1
@red = false
run_count_label.set_text("0")
assertion_count_label.set_text("0")
failure_count_label.set_text("0")
error_count_label.set_text("0")
fault_list.clear
end # def reset_ui(count)
private :reset_ui
def stop
Gtk.main_quit
end # def stop
private :stop
def run_test
@runner.raise(@restart_signal)
end
private :run_test
def start_ui
@viewer.run
running = false
begin
loop do
if (running ^= true)
run_button.child.text = "Stop"
@mediator.run_suite
else
run_button.child.text = "Run"
@viewer.join
break
end
end
rescue @restart_signal
retry
rescue
end
end # def start_ui
private :start_ui
def attach_to_mediator
run_button.signal_connect("clicked", nil) { run_test }
@mediator.add_listener(TestRunnerMediator::RESET, &method(:reset_ui))
@mediator.add_listener(TestRunnerMediator::STARTED, &method(:started))
@mediator.add_listener(TestRunnerMediator::FINISHED, &method(:finished))
@mediator.add_listener(TestResult::FAULT, &method(:add_fault))
@mediator.add_listener(TestResult::CHANGED, &method(:result_changed))
@mediator.add_listener(TestCase::STARTED, &method(:test_started))
@mediator.add_listener(TestCase::FINISHED, &method(:test_finished))
end # def attach_to_mediator
private :attach_to_mediator
def setup_mediator
@mediator = TestRunnerMediator.new(@suite)
suite_name = @suite.to_s
if @suite.kind_of?(Module) then
suite_name = @suite.name
end
suite_name_entry.set_text(suite_name)
end # def setup_mediator
private :setup_mediator
def start
setup_mediator
setup_ui
attach_to_mediator
start_ui
@result
end # def start
def initialize(suite, output_level = NORMAL)
if suite.respond_to?(:suite) then
@suite = suite.suite
else
@suite = suite
end
@result = nil
@runner = Thread.current
@restart_signal = Class.new(Exception)
@viewer = Thread.start do
@runner.join rescue @runner.run
Gtk.main
end
@viewer.join rescue nil # wait deadlock to handshake
end # def initialize(suite)
end # class TestRunner
end # module GTK2
end # module UI
end # module Unit
end # module Test
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/test/unit/ui/fox/testrunner.rb | tools/jruby-1.5.1/lib/ruby/1.8/test/unit/ui/fox/testrunner.rb | #--
#
# Author:: Nathaniel Talbott.
# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
# License:: Ruby license.
require 'fox'
require 'test/unit/ui/testrunnermediator'
require 'test/unit/ui/testrunnerutilities'
include Fox
module Test
module Unit
module UI
module Fox
# Runs a Test::Unit::TestSuite in a Fox UI. Obviously,
# this one requires you to have Fox
# (http://www.fox-toolkit.org/fox.html) and the Ruby
# Fox extension (http://fxruby.sourceforge.net/)
# installed.
class TestRunner
extend TestRunnerUtilities
RED_STYLE = FXRGBA(0xFF,0,0,0xFF) #0xFF000000
GREEN_STYLE = FXRGBA(0,0xFF,0,0xFF) #0x00FF0000
# Creates a new TestRunner for running the passed
# suite.
def initialize(suite, output_level = NORMAL)
if (suite.respond_to?(:suite))
@suite = suite.suite
else
@suite = suite
end
@result = nil
@red = false
end
# Begins the test run.
def start
setup_ui
setup_mediator
attach_to_mediator
start_ui
@result
end
def setup_mediator
@mediator = TestRunnerMediator.new(@suite)
suite_name = @suite.to_s
if ( @suite.kind_of?(Module) )
suite_name = @suite.name
end
@suite_name_entry.text = suite_name
end
def attach_to_mediator
@mediator.add_listener(TestRunnerMediator::RESET, &method(:reset_ui))
@mediator.add_listener(TestResult::FAULT, &method(:add_fault))
@mediator.add_listener(TestResult::CHANGED, &method(:result_changed))
@mediator.add_listener(TestRunnerMediator::STARTED, &method(:started))
@mediator.add_listener(TestCase::STARTED, &method(:test_started))
@mediator.add_listener(TestRunnerMediator::FINISHED, &method(:finished))
end
def start_ui
@application.create
@window.show(PLACEMENT_SCREEN)
@application.addTimeout(1) do
@mediator.run_suite
end
@application.run
end
def stop
@application.exit(0)
end
def reset_ui(count)
@test_progress_bar.barColor = GREEN_STYLE
@test_progress_bar.total = count
@test_progress_bar.progress = 0
@red = false
@test_count_label.text = "0"
@assertion_count_label.text = "0"
@failure_count_label.text = "0"
@error_count_label.text = "0"
@fault_list.clearItems
end
def add_fault(fault)
if ( ! @red )
@test_progress_bar.barColor = RED_STYLE
@red = true
end
item = FaultListItem.new(fault)
@fault_list.appendItem(item)
end
def show_fault(fault)
raw_show_fault(fault.long_display)
end
def raw_show_fault(string)
@detail_text.setText(string)
end
def clear_fault
raw_show_fault("")
end
def result_changed(result)
@test_progress_bar.progress = result.run_count
@test_count_label.text = result.run_count.to_s
@assertion_count_label.text = result.assertion_count.to_s
@failure_count_label.text = result.failure_count.to_s
@error_count_label.text = result.error_count.to_s
# repaint now!
@info_panel.repaint
@application.flush
end
def started(result)
@result = result
output_status("Started...")
end
def test_started(test_name)
output_status("Running #{test_name}...")
end
def finished(elapsed_time)
output_status("Finished in #{elapsed_time} seconds")
end
def output_status(string)
@status_entry.text = string
@status_entry.repaint
end
def setup_ui
@application = create_application
create_tooltip(@application)
@window = create_window(@application)
@status_entry = create_entry(@window)
main_panel = create_main_panel(@window)
suite_panel = create_suite_panel(main_panel)
create_label(suite_panel, "Suite:")
@suite_name_entry = create_entry(suite_panel)
create_button(suite_panel, "&Run\tRun the current suite", proc { @mediator.run_suite })
@test_progress_bar = create_progress_bar(main_panel)
@info_panel = create_info_panel(main_panel)
create_label(@info_panel, "Tests:")
@test_count_label = create_label(@info_panel, "0")
create_label(@info_panel, "Assertions:")
@assertion_count_label = create_label(@info_panel, "0")
create_label(@info_panel, "Failures:")
@failure_count_label = create_label(@info_panel, "0")
create_label(@info_panel, "Errors:")
@error_count_label = create_label(@info_panel, "0")
list_panel = create_list_panel(main_panel)
@fault_list = create_fault_list(list_panel)
detail_panel = create_detail_panel(main_panel)
@detail_text = create_text(detail_panel)
end
def create_application
app = FXApp.new("TestRunner", "Test::Unit")
app.init([])
app
end
def create_window(app)
FXMainWindow.new(app, "Test::Unit TestRunner", nil, nil, DECOR_ALL, 0, 0, 450)
end
def create_tooltip(app)
FXTooltip.new(app)
end
def create_main_panel(parent)
panel = FXVerticalFrame.new(parent, LAYOUT_FILL_X | LAYOUT_FILL_Y)
panel.vSpacing = 10
panel
end
def create_suite_panel(parent)
FXHorizontalFrame.new(parent, LAYOUT_SIDE_LEFT | LAYOUT_FILL_X)
end
def create_button(parent, text, action)
FXButton.new(parent, text).connect(SEL_COMMAND, &action)
end
def create_progress_bar(parent)
FXProgressBar.new(parent, nil, 0, PROGRESSBAR_NORMAL | LAYOUT_FILL_X)
end
def create_info_panel(parent)
FXMatrix.new(parent, 1, MATRIX_BY_ROWS | LAYOUT_FILL_X)
end
def create_label(parent, text)
FXLabel.new(parent, text, nil, JUSTIFY_CENTER_X | LAYOUT_FILL_COLUMN)
end
def create_list_panel(parent)
FXHorizontalFrame.new(parent, LAYOUT_FILL_X | FRAME_SUNKEN | FRAME_THICK)
end
def create_fault_list(parent)
list = FXList.new(parent, 10, nil, 0, LIST_SINGLESELECT | LAYOUT_FILL_X) #, 0, 0, 0, 150)
list.connect(SEL_COMMAND) do |sender, sel, ptr|
if sender.retrieveItem(sender.currentItem).selected?
show_fault(sender.retrieveItem(sender.currentItem).fault)
else
clear_fault
end
end
list
end
def create_detail_panel(parent)
FXHorizontalFrame.new(parent, LAYOUT_FILL_X | LAYOUT_FILL_Y | FRAME_SUNKEN | FRAME_THICK)
end
def create_text(parent)
FXText.new(parent, nil, 0, TEXT_READONLY | LAYOUT_FILL_X | LAYOUT_FILL_Y)
end
def create_entry(parent)
entry = FXTextField.new(parent, 30, nil, 0, TEXTFIELD_NORMAL | LAYOUT_SIDE_BOTTOM | LAYOUT_FILL_X)
entry.disable
entry
end
end
class FaultListItem < FXListItem
attr_reader(:fault)
def initialize(fault)
super(fault.short_display)
@fault = fault
end
end
end
end
end
end
if __FILE__ == $0
Test::Unit::UI::Fox::TestRunner.start_command_line_test
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/net/http.rb | tools/jruby-1.5.1/lib/ruby/1.8/net/http.rb | #
# = net/http.rb
#
# Copyright (c) 1999-2006 Yukihiro Matsumoto
# Copyright (c) 1999-2006 Minero Aoki
# Copyright (c) 2001 GOTOU Yuuzou
#
# Written and maintained by Minero Aoki <aamine@loveruby.net>.
# HTTPS support added by GOTOU Yuuzou <gotoyuzo@notwork.org>.
#
# This file is derived from "http-access.rb".
#
# Documented by Minero Aoki; converted to RDoc by William Webber.
#
# This program is free software. You can re-distribute and/or
# modify this program under the same terms of ruby itself ---
# Ruby Distribution License or GNU General Public License.
#
# See Net::HTTP for an overview and examples.
#
# NOTE: You can find Japanese version of this document here:
# http://www.ruby-lang.org/ja/man/?cmd=view;name=net%2Fhttp.rb
#
#--
# $Id: http.rb 25851 2009-11-19 06:32:19Z shyouhei $
#++
require 'net/protocol'
require 'uri'
module Net #:nodoc:
# :stopdoc:
class HTTPBadResponse < StandardError; end
class HTTPHeaderSyntaxError < StandardError; end
# :startdoc:
# == What Is This Library?
#
# This library provides your program functions to access WWW
# documents via HTTP, Hyper Text Transfer Protocol version 1.1.
# For details of HTTP, refer [RFC2616]
# (http://www.ietf.org/rfc/rfc2616.txt).
#
# == Examples
#
# === Getting Document From WWW Server
#
# Example #1: Simple GET+print
#
# require 'net/http'
# Net::HTTP.get_print 'www.example.com', '/index.html'
#
# Example #2: Simple GET+print by URL
#
# require 'net/http'
# require 'uri'
# Net::HTTP.get_print URI.parse('http://www.example.com/index.html')
#
# Example #3: More generic GET+print
#
# require 'net/http'
# require 'uri'
#
# url = URI.parse('http://www.example.com/index.html')
# res = Net::HTTP.start(url.host, url.port) {|http|
# http.get('/index.html')
# }
# puts res.body
#
# Example #4: More generic GET+print
#
# require 'net/http'
#
# url = URI.parse('http://www.example.com/index.html')
# req = Net::HTTP::Get.new(url.path)
# res = Net::HTTP.start(url.host, url.port) {|http|
# http.request(req)
# }
# puts res.body
#
# === Posting Form Data
#
# require 'net/http'
# require 'uri'
#
# #1: Simple POST
# res = Net::HTTP.post_form(URI.parse('http://www.example.com/search.cgi'),
# {'q'=>'ruby', 'max'=>'50'})
# puts res.body
#
# #2: POST with basic authentication
# res = Net::HTTP.post_form(URI.parse('http://jack:pass@www.example.com/todo.cgi'),
# {'from'=>'2005-01-01', 'to'=>'2005-03-31'})
# puts res.body
#
# #3: Detailed control
# url = URI.parse('http://www.example.com/todo.cgi')
# req = Net::HTTP::Post.new(url.path)
# req.basic_auth 'jack', 'pass'
# req.set_form_data({'from'=>'2005-01-01', 'to'=>'2005-03-31'}, ';')
# res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
# case res
# when Net::HTTPSuccess, Net::HTTPRedirection
# # OK
# else
# res.error!
# end
#
# === Accessing via Proxy
#
# Net::HTTP.Proxy creates http proxy class. It has same
# methods of Net::HTTP but its instances always connect to
# proxy, instead of given host.
#
# require 'net/http'
#
# proxy_addr = 'your.proxy.host'
# proxy_port = 8080
# :
# Net::HTTP::Proxy(proxy_addr, proxy_port).start('www.example.com') {|http|
# # always connect to your.proxy.addr:8080
# :
# }
#
# Since Net::HTTP.Proxy returns Net::HTTP itself when proxy_addr is nil,
# there's no need to change code if there's proxy or not.
#
# There are two additional parameters in Net::HTTP.Proxy which allow to
# specify proxy user name and password:
#
# Net::HTTP::Proxy(proxy_addr, proxy_port, proxy_user = nil, proxy_pass = nil)
#
# You may use them to work with authorization-enabled proxies:
#
# require 'net/http'
# require 'uri'
#
# proxy_host = 'your.proxy.host'
# proxy_port = 8080
# uri = URI.parse(ENV['http_proxy'])
# proxy_user, proxy_pass = uri.userinfo.split(/:/) if uri.userinfo
# Net::HTTP::Proxy(proxy_host, proxy_port,
# proxy_user, proxy_pass).start('www.example.com') {|http|
# # always connect to your.proxy.addr:8080 using specified username and password
# :
# }
#
# Note that net/http never rely on HTTP_PROXY environment variable.
# If you want to use proxy, set it explicitly.
#
# === Following Redirection
#
# require 'net/http'
# require 'uri'
#
# def fetch(uri_str, limit = 10)
# # You should choose better exception.
# raise ArgumentError, 'HTTP redirect too deep' if limit == 0
#
# response = Net::HTTP.get_response(URI.parse(uri_str))
# case response
# when Net::HTTPSuccess then response
# when Net::HTTPRedirection then fetch(response['location'], limit - 1)
# else
# response.error!
# end
# end
#
# print fetch('http://www.ruby-lang.org')
#
# Net::HTTPSuccess and Net::HTTPRedirection is a HTTPResponse class.
# All HTTPResponse objects belong to its own response class which
# indicate HTTP result status. For details of response classes,
# see section "HTTP Response Classes".
#
# === Basic Authentication
#
# require 'net/http'
#
# Net::HTTP.start('www.example.com') {|http|
# req = Net::HTTP::Get.new('/secret-page.html')
# req.basic_auth 'account', 'password'
# response = http.request(req)
# print response.body
# }
#
# === HTTP Request Classes
#
# Here is HTTP request class hierarchy.
#
# Net::HTTPRequest
# Net::HTTP::Get
# Net::HTTP::Head
# Net::HTTP::Post
# Net::HTTP::Put
# Net::HTTP::Proppatch
# Net::HTTP::Lock
# Net::HTTP::Unlock
# Net::HTTP::Options
# Net::HTTP::Propfind
# Net::HTTP::Delete
# Net::HTTP::Move
# Net::HTTP::Copy
# Net::HTTP::Mkcol
# Net::HTTP::Trace
#
# === HTTP Response Classes
#
# Here is HTTP response class hierarchy.
# All classes are defined in Net module.
#
# HTTPResponse
# HTTPUnknownResponse
# HTTPInformation # 1xx
# HTTPContinue # 100
# HTTPSwitchProtocl # 101
# HTTPSuccess # 2xx
# HTTPOK # 200
# HTTPCreated # 201
# HTTPAccepted # 202
# HTTPNonAuthoritativeInformation # 203
# HTTPNoContent # 204
# HTTPResetContent # 205
# HTTPPartialContent # 206
# HTTPRedirection # 3xx
# HTTPMultipleChoice # 300
# HTTPMovedPermanently # 301
# HTTPFound # 302
# HTTPSeeOther # 303
# HTTPNotModified # 304
# HTTPUseProxy # 305
# HTTPTemporaryRedirect # 307
# HTTPClientError # 4xx
# HTTPBadRequest # 400
# HTTPUnauthorized # 401
# HTTPPaymentRequired # 402
# HTTPForbidden # 403
# HTTPNotFound # 404
# HTTPMethodNotAllowed # 405
# HTTPNotAcceptable # 406
# HTTPProxyAuthenticationRequired # 407
# HTTPRequestTimeOut # 408
# HTTPConflict # 409
# HTTPGone # 410
# HTTPLengthRequired # 411
# HTTPPreconditionFailed # 412
# HTTPRequestEntityTooLarge # 413
# HTTPRequestURITooLong # 414
# HTTPUnsupportedMediaType # 415
# HTTPRequestedRangeNotSatisfiable # 416
# HTTPExpectationFailed # 417
# HTTPServerError # 5xx
# HTTPInternalServerError # 500
# HTTPNotImplemented # 501
# HTTPBadGateway # 502
# HTTPServiceUnavailable # 503
# HTTPGatewayTimeOut # 504
# HTTPVersionNotSupported # 505
#
# == Switching Net::HTTP versions
#
# You can use net/http.rb 1.1 features (bundled with Ruby 1.6)
# by calling HTTP.version_1_1. Calling Net::HTTP.version_1_2
# allows you to use 1.2 features again.
#
# # example
# Net::HTTP.start {|http1| ...(http1 has 1.2 features)... }
#
# Net::HTTP.version_1_1
# Net::HTTP.start {|http2| ...(http2 has 1.1 features)... }
#
# Net::HTTP.version_1_2
# Net::HTTP.start {|http3| ...(http3 has 1.2 features)... }
#
# This function is NOT thread-safe.
#
class HTTP < Protocol
# :stopdoc:
Revision = %q$Revision: 25851 $.split[1]
HTTPVersion = '1.1'
@newimpl = true
# :startdoc:
# Turns on net/http 1.2 (ruby 1.8) features.
# Defaults to ON in ruby 1.8.
#
# I strongly recommend to call this method always.
#
# require 'net/http'
# Net::HTTP.version_1_2
#
def HTTP.version_1_2
@newimpl = true
end
# Turns on net/http 1.1 (ruby 1.6) features.
# Defaults to OFF in ruby 1.8.
def HTTP.version_1_1
@newimpl = false
end
# true if net/http is in version 1.2 mode.
# Defaults to true.
def HTTP.version_1_2?
@newimpl
end
# true if net/http is in version 1.1 compatible mode.
# Defaults to true.
def HTTP.version_1_1?
not @newimpl
end
class << HTTP
alias is_version_1_1? version_1_1? #:nodoc:
alias is_version_1_2? version_1_2? #:nodoc:
end
#
# short cut methods
#
#
# Get body from target and output it to +$stdout+. The
# target can either be specified as (+uri+), or as
# (+host+, +path+, +port+ = 80); so:
#
# Net::HTTP.get_print URI.parse('http://www.example.com/index.html')
#
# or:
#
# Net::HTTP.get_print 'www.example.com', '/index.html'
#
def HTTP.get_print(uri_or_host, path = nil, port = nil)
get_response(uri_or_host, path, port) {|res|
res.read_body do |chunk|
$stdout.print chunk
end
}
nil
end
# Send a GET request to the target and return the response
# as a string. The target can either be specified as
# (+uri+), or as (+host+, +path+, +port+ = 80); so:
#
# print Net::HTTP.get(URI.parse('http://www.example.com/index.html'))
#
# or:
#
# print Net::HTTP.get('www.example.com', '/index.html')
#
def HTTP.get(uri_or_host, path = nil, port = nil)
get_response(uri_or_host, path, port).body
end
# Send a GET request to the target and return the response
# as a Net::HTTPResponse object. The target can either be specified as
# (+uri+), or as (+host+, +path+, +port+ = 80); so:
#
# res = Net::HTTP.get_response(URI.parse('http://www.example.com/index.html'))
# print res.body
#
# or:
#
# res = Net::HTTP.get_response('www.example.com', '/index.html')
# print res.body
#
def HTTP.get_response(uri_or_host, path = nil, port = nil, &block)
if path
host = uri_or_host
new(host, port || HTTP.default_port).start {|http|
return http.request_get(path, &block)
}
else
uri = uri_or_host
new(uri.host, uri.port).start {|http|
return http.request_get(uri.request_uri, &block)
}
end
end
# Posts HTML form data to the +URL+.
# Form data must be represented as a Hash of String to String, e.g:
#
# { "cmd" => "search", "q" => "ruby", "max" => "50" }
#
# This method also does Basic Authentication iff +URL+.user exists.
#
# Example:
#
# require 'net/http'
# require 'uri'
#
# HTTP.post_form URI.parse('http://www.example.com/search.cgi'),
# { "q" => "ruby", "max" => "50" }
#
def HTTP.post_form(url, params)
req = Post.new(url.path)
req.form_data = params
req.basic_auth url.user, url.password if url.user
new(url.host, url.port).start {|http|
http.request(req)
}
end
#
# HTTP session management
#
# The default port to use for HTTP requests; defaults to 80.
def HTTP.default_port
http_default_port()
end
# The default port to use for HTTP requests; defaults to 80.
def HTTP.http_default_port
80
end
# The default port to use for HTTPS requests; defaults to 443.
def HTTP.https_default_port
443
end
def HTTP.socket_type #:nodoc: obsolete
BufferedIO
end
# creates a new Net::HTTP object and opens its TCP connection and
# HTTP session. If the optional block is given, the newly
# created Net::HTTP object is passed to it and closed when the
# block finishes. In this case, the return value of this method
# is the return value of the block. If no block is given, the
# return value of this method is the newly created Net::HTTP object
# itself, and the caller is responsible for closing it upon completion.
def HTTP.start(address, port = nil, p_addr = nil, p_port = nil, p_user = nil, p_pass = nil, &block) # :yield: +http+
new(address, port, p_addr, p_port, p_user, p_pass).start(&block)
end
class << HTTP
alias newobj new
end
# Creates a new Net::HTTP object.
# If +proxy_addr+ is given, creates an Net::HTTP object with proxy support.
# This method does not open the TCP connection.
def HTTP.new(address, port = nil, p_addr = nil, p_port = nil, p_user = nil, p_pass = nil)
h = Proxy(p_addr, p_port, p_user, p_pass).newobj(address, port)
h.instance_eval {
@newimpl = ::Net::HTTP.version_1_2?
}
h
end
# Creates a new Net::HTTP object for the specified +address+.
# This method does not open the TCP connection.
def initialize(address, port = nil)
@address = address
@port = (port || HTTP.default_port)
@curr_http_version = HTTPVersion
@seems_1_0_server = false
@close_on_empty_response = false
@socket = nil
@started = false
@open_timeout = nil
@read_timeout = 60
@debug_output = nil
@use_ssl = false
@ssl_context = nil
end
def inspect
"#<#{self.class} #{@address}:#{@port} open=#{started?}>"
end
# *WARNING* This method causes serious security hole.
# Never use this method in production code.
#
# Set an output stream for debugging.
#
# http = Net::HTTP.new
# http.set_debug_output $stderr
# http.start { .... }
#
def set_debug_output(output)
warn 'Net::HTTP#set_debug_output called after HTTP started' if started?
@debug_output = output
end
# The host name to connect to.
attr_reader :address
# The port number to connect to.
attr_reader :port
# Seconds to wait until connection is opened.
# If the HTTP object cannot open a connection in this many seconds,
# it raises a TimeoutError exception.
attr_accessor :open_timeout
# Seconds to wait until reading one block (by one read(2) call).
# If the HTTP object cannot open a connection in this many seconds,
# it raises a TimeoutError exception.
attr_reader :read_timeout
# Setter for the read_timeout attribute.
def read_timeout=(sec)
@socket.read_timeout = sec if @socket
@read_timeout = sec
end
# returns true if the HTTP session is started.
def started?
@started
end
alias active? started? #:nodoc: obsolete
attr_accessor :close_on_empty_response
# returns true if use SSL/TLS with HTTP.
def use_ssl?
false # redefined in net/https
end
# Opens TCP connection and HTTP session.
#
# When this method is called with block, gives a HTTP object
# to the block and closes the TCP connection / HTTP session
# after the block executed.
#
# When called with a block, returns the return value of the
# block; otherwise, returns self.
#
def start # :yield: http
raise IOError, 'HTTP session already opened' if @started
if block_given?
begin
do_start
return yield(self)
ensure
do_finish
end
end
do_start
self
end
def do_start
connect
@started = true
end
private :do_start
def connect
D "opening connection to #{conn_address()}..."
s = timeout(@open_timeout) { TCPSocket.open(conn_address(), conn_port()) }
D "opened"
if use_ssl?
unless @ssl_context.verify_mode
warn "warning: peer certificate won't be verified in this SSL session"
@ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
s = OpenSSL::SSL::SSLSocket.new(s, @ssl_context)
s.sync_close = true
end
@socket = BufferedIO.new(s)
@socket.read_timeout = @read_timeout
@socket.debug_output = @debug_output
if use_ssl?
if proxy?
@socket.writeline sprintf('CONNECT %s:%s HTTP/%s',
@address, @port, HTTPVersion)
@socket.writeline "Host: #{@address}:#{@port}"
if proxy_user
credential = ["#{proxy_user}:#{proxy_pass}"].pack('m')
credential.delete!("\r\n")
@socket.writeline "Proxy-Authorization: Basic #{credential}"
end
@socket.writeline ''
HTTPResponse.read_new(@socket).value
end
s.connect
if @ssl_context.verify_mode != OpenSSL::SSL::VERIFY_NONE
s.post_connection_check(@address)
end
end
on_connect
end
private :connect
def on_connect
end
private :on_connect
# Finishes HTTP session and closes TCP connection.
# Raises IOError if not started.
def finish
raise IOError, 'HTTP session not yet started' unless started?
do_finish
end
def do_finish
@started = false
@socket.close if @socket and not @socket.closed?
@socket = nil
end
private :do_finish
#
# proxy
#
public
# no proxy
@is_proxy_class = false
@proxy_addr = nil
@proxy_port = nil
@proxy_user = nil
@proxy_pass = nil
# Creates an HTTP proxy class.
# Arguments are address/port of proxy host and username/password
# if authorization on proxy server is required.
# You can replace the HTTP class with created proxy class.
#
# If ADDRESS is nil, this method returns self (Net::HTTP).
#
# # Example
# proxy_class = Net::HTTP::Proxy('proxy.example.com', 8080)
# :
# proxy_class.start('www.ruby-lang.org') {|http|
# # connecting proxy.foo.org:8080
# :
# }
#
def HTTP.Proxy(p_addr, p_port = nil, p_user = nil, p_pass = nil)
return self unless p_addr
delta = ProxyDelta
proxyclass = Class.new(self)
proxyclass.module_eval {
include delta
# with proxy
@is_proxy_class = true
@proxy_address = p_addr
@proxy_port = p_port || default_port()
@proxy_user = p_user
@proxy_pass = p_pass
}
proxyclass
end
class << HTTP
# returns true if self is a class which was created by HTTP::Proxy.
def proxy_class?
@is_proxy_class
end
attr_reader :proxy_address
attr_reader :proxy_port
attr_reader :proxy_user
attr_reader :proxy_pass
end
# True if self is a HTTP proxy class.
def proxy?
self.class.proxy_class?
end
# Address of proxy host. If self does not use a proxy, nil.
def proxy_address
self.class.proxy_address
end
# Port number of proxy host. If self does not use a proxy, nil.
def proxy_port
self.class.proxy_port
end
# User name for accessing proxy. If self does not use a proxy, nil.
def proxy_user
self.class.proxy_user
end
# User password for accessing proxy. If self does not use a proxy, nil.
def proxy_pass
self.class.proxy_pass
end
alias proxyaddr proxy_address #:nodoc: obsolete
alias proxyport proxy_port #:nodoc: obsolete
private
# without proxy
def conn_address
address()
end
def conn_port
port()
end
def edit_path(path)
path
end
module ProxyDelta #:nodoc: internal use only
private
def conn_address
proxy_address()
end
def conn_port
proxy_port()
end
def edit_path(path)
use_ssl? ? path : "http://#{addr_port()}#{path}"
end
end
#
# HTTP operations
#
public
# Gets data from +path+ on the connected-to host.
# +header+ must be a Hash like { 'Accept' => '*/*', ... }.
#
# In version 1.1 (ruby 1.6), this method returns a pair of objects,
# a Net::HTTPResponse object and the entity body string.
# In version 1.2 (ruby 1.8), this method returns a Net::HTTPResponse
# object.
#
# If called with a block, yields each fragment of the
# entity body in turn as a string as it is read from
# the socket. Note that in this case, the returned response
# object will *not* contain a (meaningful) body.
#
# +dest+ argument is obsolete.
# It still works but you must not use it.
#
# In version 1.1, this method might raise an exception for
# 3xx (redirect). In this case you can get a HTTPResponse object
# by "anException.response".
#
# In version 1.2, this method never raises exception.
#
# # version 1.1 (bundled with Ruby 1.6)
# response, body = http.get('/index.html')
#
# # version 1.2 (bundled with Ruby 1.8 or later)
# response = http.get('/index.html')
#
# # using block
# File.open('result.txt', 'w') {|f|
# http.get('/~foo/') do |str|
# f.write str
# end
# }
#
def get(path, initheader = nil, dest = nil, &block) # :yield: +body_segment+
res = nil
request(Get.new(path, initheader)) {|r|
r.read_body dest, &block
res = r
}
unless @newimpl
res.value
return res, res.body
end
res
end
# Gets only the header from +path+ on the connected-to host.
# +header+ is a Hash like { 'Accept' => '*/*', ... }.
#
# This method returns a Net::HTTPResponse object.
#
# In version 1.1, this method might raise an exception for
# 3xx (redirect). On the case you can get a HTTPResponse object
# by "anException.response".
# In version 1.2, this method never raises an exception.
#
# response = nil
# Net::HTTP.start('some.www.server', 80) {|http|
# response = http.head('/index.html')
# }
# p response['content-type']
#
def head(path, initheader = nil)
res = request(Head.new(path, initheader))
res.value unless @newimpl
res
end
# Posts +data+ (must be a String) to +path+. +header+ must be a Hash
# like { 'Accept' => '*/*', ... }.
#
# In version 1.1 (ruby 1.6), this method returns a pair of objects, a
# Net::HTTPResponse object and an entity body string.
# In version 1.2 (ruby 1.8), this method returns a Net::HTTPResponse object.
#
# If called with a block, yields each fragment of the
# entity body in turn as a string as it are read from
# the socket. Note that in this case, the returned response
# object will *not* contain a (meaningful) body.
#
# +dest+ argument is obsolete.
# It still works but you must not use it.
#
# In version 1.1, this method might raise an exception for
# 3xx (redirect). In this case you can get an HTTPResponse object
# by "anException.response".
# In version 1.2, this method never raises exception.
#
# # version 1.1
# response, body = http.post('/cgi-bin/search.rb', 'query=foo')
#
# # version 1.2
# response = http.post('/cgi-bin/search.rb', 'query=foo')
#
# # using block
# File.open('result.txt', 'w') {|f|
# http.post('/cgi-bin/search.rb', 'query=foo') do |str|
# f.write str
# end
# }
#
# You should set Content-Type: header field for POST.
# If no Content-Type: field given, this method uses
# "application/x-www-form-urlencoded" by default.
#
def post(path, data, initheader = nil, dest = nil, &block) # :yield: +body_segment+
res = nil
request(Post.new(path, initheader), data) {|r|
r.read_body dest, &block
res = r
}
unless @newimpl
res.value
return res, res.body
end
res
end
def put(path, data, initheader = nil) #:nodoc:
res = request(Put.new(path, initheader), data)
res.value unless @newimpl
res
end
# Sends a PROPPATCH request to the +path+ and gets a response,
# as an HTTPResponse object.
def proppatch(path, body, initheader = nil)
request(Proppatch.new(path, initheader), body)
end
# Sends a LOCK request to the +path+ and gets a response,
# as an HTTPResponse object.
def lock(path, body, initheader = nil)
request(Lock.new(path, initheader), body)
end
# Sends a UNLOCK request to the +path+ and gets a response,
# as an HTTPResponse object.
def unlock(path, body, initheader = nil)
request(Unlock.new(path, initheader), body)
end
# Sends a OPTIONS request to the +path+ and gets a response,
# as an HTTPResponse object.
def options(path, initheader = nil)
request(Options.new(path, initheader))
end
# Sends a PROPFIND request to the +path+ and gets a response,
# as an HTTPResponse object.
def propfind(path, body = nil, initheader = {'Depth' => '0'})
request(Propfind.new(path, initheader), body)
end
# Sends a DELETE request to the +path+ and gets a response,
# as an HTTPResponse object.
def delete(path, initheader = {'Depth' => 'Infinity'})
request(Delete.new(path, initheader))
end
# Sends a MOVE request to the +path+ and gets a response,
# as an HTTPResponse object.
def move(path, initheader = nil)
request(Move.new(path, initheader))
end
# Sends a COPY request to the +path+ and gets a response,
# as an HTTPResponse object.
def copy(path, initheader = nil)
request(Copy.new(path, initheader))
end
# Sends a MKCOL request to the +path+ and gets a response,
# as an HTTPResponse object.
def mkcol(path, body = nil, initheader = nil)
request(Mkcol.new(path, initheader), body)
end
# Sends a TRACE request to the +path+ and gets a response,
# as an HTTPResponse object.
def trace(path, initheader = nil)
request(Trace.new(path, initheader))
end
# Sends a GET request to the +path+ and gets a response,
# as an HTTPResponse object.
#
# When called with a block, yields an HTTPResponse object.
# The body of this response will not have been read yet;
# the caller can process it using HTTPResponse#read_body,
# if desired.
#
# Returns the response.
#
# This method never raises Net::* exceptions.
#
# response = http.request_get('/index.html')
# # The entity body is already read here.
# p response['content-type']
# puts response.body
#
# # using block
# http.request_get('/index.html') {|response|
# p response['content-type']
# response.read_body do |str| # read body now
# print str
# end
# }
#
def request_get(path, initheader = nil, &block) # :yield: +response+
request(Get.new(path, initheader), &block)
end
# Sends a HEAD request to the +path+ and gets a response,
# as an HTTPResponse object.
#
# Returns the response.
#
# This method never raises Net::* exceptions.
#
# response = http.request_head('/index.html')
# p response['content-type']
#
def request_head(path, initheader = nil, &block)
request(Head.new(path, initheader), &block)
end
# Sends a POST request to the +path+ and gets a response,
# as an HTTPResponse object.
#
# When called with a block, yields an HTTPResponse object.
# The body of this response will not have been read yet;
# the caller can process it using HTTPResponse#read_body,
# if desired.
#
# Returns the response.
#
# This method never raises Net::* exceptions.
#
# # example
# response = http.request_post('/cgi-bin/nice.rb', 'datadatadata...')
# p response.status
# puts response.body # body is already read
#
# # using block
# http.request_post('/cgi-bin/nice.rb', 'datadatadata...') {|response|
# p response.status
# p response['content-type']
# response.read_body do |str| # read body now
# print str
# end
# }
#
def request_post(path, data, initheader = nil, &block) # :yield: +response+
request Post.new(path, initheader), data, &block
end
def request_put(path, data, initheader = nil, &block) #:nodoc:
request Put.new(path, initheader), data, &block
end
alias get2 request_get #:nodoc: obsolete
alias head2 request_head #:nodoc: obsolete
alias post2 request_post #:nodoc: obsolete
alias put2 request_put #:nodoc: obsolete
# Sends an HTTP request to the HTTP server.
# This method also sends DATA string if DATA is given.
#
# Returns a HTTPResponse object.
#
# This method never raises Net::* exceptions.
#
# response = http.send_request('GET', '/index.html')
# puts response.body
#
def send_request(name, path, data = nil, header = nil)
r = HTTPGenericRequest.new(name,(data ? true : false),true,path,header)
request r, data
end
# Sends an HTTPRequest object REQUEST to the HTTP server.
# This method also sends DATA string if REQUEST is a post/put request.
# Giving DATA for get/head request causes ArgumentError.
#
# When called with a block, yields an HTTPResponse object.
# The body of this response will not have been read yet;
# the caller can process it using HTTPResponse#read_body,
# if desired.
#
# Returns a HTTPResponse object.
#
# This method never raises Net::* exceptions.
#
def request(req, body = nil, &block) # :yield: +response+
unless started?
start {
req['connection'] ||= 'close'
return request(req, body, &block)
}
end
if proxy_user()
unless use_ssl?
req.proxy_basic_auth proxy_user(), proxy_pass()
end
end
req.set_body_internal body
begin
begin_transport req
req.exec @socket, @curr_http_version, edit_path(req.path)
begin
res = HTTPResponse.read_new(@socket)
end while res.kind_of?(HTTPContinue)
res.reading_body(@socket, req.response_body_permitted?) {
yield res if block_given?
}
end_transport req, res
rescue => exception
D "Conn close because of error #{exception}"
@socket.close unless @socket.closed?
raise exception
end
res
end
private
def begin_transport(req)
if @socket.closed?
connect
end
if @seems_1_0_server
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | true |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/net/telnet.rb | tools/jruby-1.5.1/lib/ruby/1.8/net/telnet.rb | # = net/telnet.rb - Simple Telnet Client Library
#
# Author:: Wakou Aoyama <wakou@ruby-lang.org>
# Documentation:: William Webber and Wakou Aoyama
#
# This file holds the class Net::Telnet, which provides client-side
# telnet functionality.
#
# For documentation, see Net::Telnet.
#
require "socket"
require "delegate"
require "timeout"
require "English"
module Net
#
# == Net::Telnet
#
# Provides telnet client functionality.
#
# This class also has, through delegation, all the methods of a
# socket object (by default, a +TCPSocket+, but can be set by the
# +Proxy+ option to <tt>new()</tt>). This provides methods such as
# <tt>close()</tt> to end the session and <tt>sysread()</tt> to read
# data directly from the host, instead of via the <tt>waitfor()</tt>
# mechanism. Note that if you do use <tt>sysread()</tt> directly
# when in telnet mode, you should probably pass the output through
# <tt>preprocess()</tt> to extract telnet command sequences.
#
# == Overview
#
# The telnet protocol allows a client to login remotely to a user
# account on a server and execute commands via a shell. The equivalent
# is done by creating a Net::Telnet class with the +Host+ option
# set to your host, calling #login() with your user and password,
# issuing one or more #cmd() calls, and then calling #close()
# to end the session. The #waitfor(), #print(), #puts(), and
# #write() methods, which #cmd() is implemented on top of, are
# only needed if you are doing something more complicated.
#
# A Net::Telnet object can also be used to connect to non-telnet
# services, such as SMTP or HTTP. In this case, you normally
# want to provide the +Port+ option to specify the port to
# connect to, and set the +Telnetmode+ option to false to prevent
# the client from attempting to interpret telnet command sequences.
# Generally, #login() will not work with other protocols, and you
# have to handle authentication yourself.
#
# For some protocols, it will be possible to specify the +Prompt+
# option once when you create the Telnet object and use #cmd() calls;
# for others, you will have to specify the response sequence to
# look for as the Match option to every #cmd() call, or call
# #puts() and #waitfor() directly; for yet others, you will have
# to use #sysread() instead of #waitfor() and parse server
# responses yourself.
#
# It is worth noting that when you create a new Net::Telnet object,
# you can supply a proxy IO channel via the Proxy option. This
# can be used to attach the Telnet object to other Telnet objects,
# to already open sockets, or to any read-write IO object. This
# can be useful, for instance, for setting up a test fixture for
# unit testing.
#
# == Examples
#
# === Log in and send a command, echoing all output to stdout
#
# localhost = Net::Telnet::new("Host" => "localhost",
# "Timeout" => 10,
# "Prompt" => /[$%#>] \z/n)
# localhost.login("username", "password") { |c| print c }
# localhost.cmd("command") { |c| print c }
# localhost.close
#
#
# === Check a POP server to see if you have mail
#
# pop = Net::Telnet::new("Host" => "your_destination_host_here",
# "Port" => 110,
# "Telnetmode" => false,
# "Prompt" => /^\+OK/n)
# pop.cmd("user " + "your_username_here") { |c| print c }
# pop.cmd("pass " + "your_password_here") { |c| print c }
# pop.cmd("list") { |c| print c }
#
# == References
#
# There are a large number of RFCs relevant to the Telnet protocol.
# RFCs 854-861 define the base protocol. For a complete listing
# of relevant RFCs, see
# http://www.omnifarious.org/~hopper/technical/telnet-rfc.html
#
class Telnet < SimpleDelegator
# :stopdoc:
IAC = 255.chr # "\377" # "\xff" # interpret as command
DONT = 254.chr # "\376" # "\xfe" # you are not to use option
DO = 253.chr # "\375" # "\xfd" # please, you use option
WONT = 252.chr # "\374" # "\xfc" # I won't use option
WILL = 251.chr # "\373" # "\xfb" # I will use option
SB = 250.chr # "\372" # "\xfa" # interpret as subnegotiation
GA = 249.chr # "\371" # "\xf9" # you may reverse the line
EL = 248.chr # "\370" # "\xf8" # erase the current line
EC = 247.chr # "\367" # "\xf7" # erase the current character
AYT = 246.chr # "\366" # "\xf6" # are you there
AO = 245.chr # "\365" # "\xf5" # abort output--but let prog finish
IP = 244.chr # "\364" # "\xf4" # interrupt process--permanently
BREAK = 243.chr # "\363" # "\xf3" # break
DM = 242.chr # "\362" # "\xf2" # data mark--for connect. cleaning
NOP = 241.chr # "\361" # "\xf1" # nop
SE = 240.chr # "\360" # "\xf0" # end sub negotiation
EOR = 239.chr # "\357" # "\xef" # end of record (transparent mode)
ABORT = 238.chr # "\356" # "\xee" # Abort process
SUSP = 237.chr # "\355" # "\xed" # Suspend process
EOF = 236.chr # "\354" # "\xec" # End of file
SYNCH = 242.chr # "\362" # "\xf2" # for telfunc calls
OPT_BINARY = 0.chr # "\000" # "\x00" # Binary Transmission
OPT_ECHO = 1.chr # "\001" # "\x01" # Echo
OPT_RCP = 2.chr # "\002" # "\x02" # Reconnection
OPT_SGA = 3.chr # "\003" # "\x03" # Suppress Go Ahead
OPT_NAMS = 4.chr # "\004" # "\x04" # Approx Message Size Negotiation
OPT_STATUS = 5.chr # "\005" # "\x05" # Status
OPT_TM = 6.chr # "\006" # "\x06" # Timing Mark
OPT_RCTE = 7.chr # "\a" # "\x07" # Remote Controlled Trans and Echo
OPT_NAOL = 8.chr # "\010" # "\x08" # Output Line Width
OPT_NAOP = 9.chr # "\t" # "\x09" # Output Page Size
OPT_NAOCRD = 10.chr # "\n" # "\x0a" # Output Carriage-Return Disposition
OPT_NAOHTS = 11.chr # "\v" # "\x0b" # Output Horizontal Tab Stops
OPT_NAOHTD = 12.chr # "\f" # "\x0c" # Output Horizontal Tab Disposition
OPT_NAOFFD = 13.chr # "\r" # "\x0d" # Output Formfeed Disposition
OPT_NAOVTS = 14.chr # "\016" # "\x0e" # Output Vertical Tabstops
OPT_NAOVTD = 15.chr # "\017" # "\x0f" # Output Vertical Tab Disposition
OPT_NAOLFD = 16.chr # "\020" # "\x10" # Output Linefeed Disposition
OPT_XASCII = 17.chr # "\021" # "\x11" # Extended ASCII
OPT_LOGOUT = 18.chr # "\022" # "\x12" # Logout
OPT_BM = 19.chr # "\023" # "\x13" # Byte Macro
OPT_DET = 20.chr # "\024" # "\x14" # Data Entry Terminal
OPT_SUPDUP = 21.chr # "\025" # "\x15" # SUPDUP
OPT_SUPDUPOUTPUT = 22.chr # "\026" # "\x16" # SUPDUP Output
OPT_SNDLOC = 23.chr # "\027" # "\x17" # Send Location
OPT_TTYPE = 24.chr # "\030" # "\x18" # Terminal Type
OPT_EOR = 25.chr # "\031" # "\x19" # End of Record
OPT_TUID = 26.chr # "\032" # "\x1a" # TACACS User Identification
OPT_OUTMRK = 27.chr # "\e" # "\x1b" # Output Marking
OPT_TTYLOC = 28.chr # "\034" # "\x1c" # Terminal Location Number
OPT_3270REGIME = 29.chr # "\035" # "\x1d" # Telnet 3270 Regime
OPT_X3PAD = 30.chr # "\036" # "\x1e" # X.3 PAD
OPT_NAWS = 31.chr # "\037" # "\x1f" # Negotiate About Window Size
OPT_TSPEED = 32.chr # " " # "\x20" # Terminal Speed
OPT_LFLOW = 33.chr # "!" # "\x21" # Remote Flow Control
OPT_LINEMODE = 34.chr # "\"" # "\x22" # Linemode
OPT_XDISPLOC = 35.chr # "#" # "\x23" # X Display Location
OPT_OLD_ENVIRON = 36.chr # "$" # "\x24" # Environment Option
OPT_AUTHENTICATION = 37.chr # "%" # "\x25" # Authentication Option
OPT_ENCRYPT = 38.chr # "&" # "\x26" # Encryption Option
OPT_NEW_ENVIRON = 39.chr # "'" # "\x27" # New Environment Option
OPT_EXOPL = 255.chr # "\377" # "\xff" # Extended-Options-List
NULL = "\000"
CR = "\015"
LF = "\012"
EOL = CR + LF
REVISION = '$Id: telnet.rb 16458 2008-05-18 15:02:36Z knu $'
# :startdoc:
#
# Creates a new Net::Telnet object.
#
# Attempts to connect to the host (unless the Proxy option is
# provided: see below). If a block is provided, it is yielded
# status messages on the attempt to connect to the server, of
# the form:
#
# Trying localhost...
# Connected to localhost.
#
# +options+ is a hash of options. The following example lists
# all options and their default values.
#
# host = Net::Telnet::new(
# "Host" => "localhost", # default: "localhost"
# "Port" => 23, # default: 23
# "Binmode" => false, # default: false
# "Output_log" => "output_log", # default: nil (no output)
# "Dump_log" => "dump_log", # default: nil (no output)
# "Prompt" => /[$%#>] \z/n, # default: /[$%#>] \z/n
# "Telnetmode" => true, # default: true
# "Timeout" => 10, # default: 10
# # if ignore timeout then set "Timeout" to false.
# "Waittime" => 0, # default: 0
# "Proxy" => proxy # default: nil
# # proxy is Net::Telnet or IO object
# )
#
# The options have the following meanings:
#
# Host:: the hostname or IP address of the host to connect to, as a String.
# Defaults to "localhost".
#
# Port:: the port to connect to. Defaults to 23.
#
# Binmode:: if false (the default), newline substitution is performed.
# Outgoing LF is
# converted to CRLF, and incoming CRLF is converted to LF. If
# true, this substitution is not performed. This value can
# also be set with the #binmode() method. The
# outgoing conversion only applies to the #puts() and #print()
# methods, not the #write() method. The precise nature of
# the newline conversion is also affected by the telnet options
# SGA and BIN.
#
# Output_log:: the name of the file to write connection status messages
# and all received traffic to. In the case of a proper
# Telnet session, this will include the client input as
# echoed by the host; otherwise, it only includes server
# responses. Output is appended verbatim to this file.
# By default, no output log is kept.
#
# Dump_log:: as for Output_log, except that output is written in hexdump
# format (16 bytes per line as hex pairs, followed by their
# printable equivalent), with connection status messages
# preceded by '#', sent traffic preceded by '>', and
# received traffic preceded by '<'. By default, not dump log
# is kept.
#
# Prompt:: a regular expression matching the host's command-line prompt
# sequence. This is needed by the Telnet class to determine
# when the output from a command has finished and the host is
# ready to receive a new command. By default, this regular
# expression is /[$%#>] \z/n.
#
# Telnetmode:: a boolean value, true by default. In telnet mode,
# traffic received from the host is parsed for special
# command sequences, and these sequences are escaped
# in outgoing traffic sent using #puts() or #print()
# (but not #write()). If you are using the Net::Telnet
# object to connect to a non-telnet service (such as
# SMTP or POP), this should be set to "false" to prevent
# undesired data corruption. This value can also be set
# by the #telnetmode() method.
#
# Timeout:: the number of seconds to wait before timing out both the
# initial attempt to connect to host (in this constructor),
# and all attempts to read data from the host (in #waitfor(),
# #cmd(), and #login()). Exceeding this timeout causes a
# TimeoutError to be raised. The default value is 10 seconds.
# You can disable the timeout by setting this value to false.
# In this case, the connect attempt will eventually timeout
# on the underlying connect(2) socket call with an
# Errno::ETIMEDOUT error (but generally only after a few
# minutes), but other attempts to read data from the host
# will hand indefinitely if no data is forthcoming.
#
# Waittime:: the amount of time to wait after seeing what looks like a
# prompt (that is, received data that matches the Prompt
# option regular expression) to see if more data arrives.
# If more data does arrive in this time, Net::Telnet assumes
# that what it saw was not really a prompt. This is to try to
# avoid false matches, but it can also lead to missing real
# prompts (if, for instance, a background process writes to
# the terminal soon after the prompt is displayed). By
# default, set to 0, meaning not to wait for more data.
#
# Proxy:: a proxy object to used instead of opening a direct connection
# to the host. Must be either another Net::Telnet object or
# an IO object. If it is another Net::Telnet object, this
# instance will use that one's socket for communication. If an
# IO object, it is used directly for communication. Any other
# kind of object will cause an error to be raised.
#
def initialize(options) # :yield: mesg
@options = options
@options["Host"] = "localhost" unless @options.has_key?("Host")
@options["Port"] = 23 unless @options.has_key?("Port")
@options["Prompt"] = /[$%#>] \z/n unless @options.has_key?("Prompt")
@options["Timeout"] = 10 unless @options.has_key?("Timeout")
@options["Waittime"] = 0 unless @options.has_key?("Waittime")
unless @options.has_key?("Binmode")
@options["Binmode"] = false
else
unless (true == @options["Binmode"] or false == @options["Binmode"])
raise ArgumentError, "Binmode option must be true or false"
end
end
unless @options.has_key?("Telnetmode")
@options["Telnetmode"] = true
else
unless (true == @options["Telnetmode"] or false == @options["Telnetmode"])
raise ArgumentError, "Telnetmode option must be true or false"
end
end
@telnet_option = { "SGA" => false, "BINARY" => false }
if @options.has_key?("Output_log")
@log = File.open(@options["Output_log"], 'a+')
@log.sync = true
@log.binmode
end
if @options.has_key?("Dump_log")
@dumplog = File.open(@options["Dump_log"], 'a+')
@dumplog.sync = true
@dumplog.binmode
def @dumplog.log_dump(dir, x) # :nodoc:
len = x.length
addr = 0
offset = 0
while 0 < len
if len < 16
line = x[offset, len]
else
line = x[offset, 16]
end
hexvals = line.unpack('H*')[0]
hexvals += ' ' * (32 - hexvals.length)
hexvals = format("%s %s %s %s " * 4, *hexvals.unpack('a2' * 16))
line = line.gsub(/[\000-\037\177-\377]/n, '.')
printf "%s 0x%5.5x: %s%s\n", dir, addr, hexvals, line
addr += 16
offset += 16
len -= 16
end
print "\n"
end
end
if @options.has_key?("Proxy")
if @options["Proxy"].kind_of?(Net::Telnet)
@sock = @options["Proxy"].sock
elsif @options["Proxy"].kind_of?(IO)
@sock = @options["Proxy"]
else
raise "Error: Proxy must be an instance of Net::Telnet or IO."
end
else
message = "Trying " + @options["Host"] + "...\n"
yield(message) if block_given?
@log.write(message) if @options.has_key?("Output_log")
@dumplog.log_dump('#', message) if @options.has_key?("Dump_log")
begin
if @options["Timeout"] == false
@sock = TCPSocket.open(@options["Host"], @options["Port"])
else
timeout(@options["Timeout"]) do
@sock = TCPSocket.open(@options["Host"], @options["Port"])
end
end
rescue TimeoutError
raise TimeoutError, "timed out while opening a connection to the host"
rescue
@log.write($ERROR_INFO.to_s + "\n") if @options.has_key?("Output_log")
@dumplog.log_dump('#', $ERROR_INFO.to_s + "\n") if @options.has_key?("Dump_log")
raise
end
@sock.sync = true
@sock.binmode
message = "Connected to " + @options["Host"] + ".\n"
yield(message) if block_given?
@log.write(message) if @options.has_key?("Output_log")
@dumplog.log_dump('#', message) if @options.has_key?("Dump_log")
end
super(@sock)
end # initialize
# The socket the Telnet object is using. Note that this object becomes
# a delegate of the Telnet object, so normally you invoke its methods
# directly on the Telnet object.
attr :sock
# Set telnet command interpretation on (+mode+ == true) or off
# (+mode+ == false), or return the current value (+mode+ not
# provided). It should be on for true telnet sessions, off if
# using Net::Telnet to connect to a non-telnet service such
# as SMTP.
def telnetmode(mode = nil)
case mode
when nil
@options["Telnetmode"]
when true, false
@options["Telnetmode"] = mode
else
raise ArgumentError, "argument must be true or false, or missing"
end
end
# Turn telnet command interpretation on (true) or off (false). It
# should be on for true telnet sessions, off if using Net::Telnet
# to connect to a non-telnet service such as SMTP.
def telnetmode=(mode)
if (true == mode or false == mode)
@options["Telnetmode"] = mode
else
raise ArgumentError, "argument must be true or false"
end
end
# Turn newline conversion on (+mode+ == false) or off (+mode+ == true),
# or return the current value (+mode+ is not specified).
def binmode(mode = nil)
case mode
when nil
@options["Binmode"]
when true, false
@options["Binmode"] = mode
else
raise ArgumentError, "argument must be true or false"
end
end
# Turn newline conversion on (false) or off (true).
def binmode=(mode)
if (true == mode or false == mode)
@options["Binmode"] = mode
else
raise ArgumentError, "argument must be true or false"
end
end
# Preprocess received data from the host.
#
# Performs newline conversion and detects telnet command sequences.
# Called automatically by #waitfor(). You should only use this
# method yourself if you have read input directly using sysread()
# or similar, and even then only if in telnet mode.
def preprocess(string)
# combine CR+NULL into CR
string = string.gsub(/#{CR}#{NULL}/no, CR) if @options["Telnetmode"]
# combine EOL into "\n"
string = string.gsub(/#{EOL}/no, "\n") unless @options["Binmode"]
string.gsub(/#{IAC}(
[#{IAC}#{AO}#{AYT}#{DM}#{IP}#{NOP}]|
[#{DO}#{DONT}#{WILL}#{WONT}]
[#{OPT_BINARY}-#{OPT_NEW_ENVIRON}#{OPT_EXOPL}]|
#{SB}[^#{IAC}]*#{IAC}#{SE}
)/xno) do
if IAC == $1 # handle escaped IAC characters
IAC
elsif AYT == $1 # respond to "IAC AYT" (are you there)
self.write("nobody here but us pigeons" + EOL)
''
elsif DO[0] == $1[0] # respond to "IAC DO x"
if OPT_BINARY[0] == $1[1]
@telnet_option["BINARY"] = true
self.write(IAC + WILL + OPT_BINARY)
else
self.write(IAC + WONT + $1[1..1])
end
''
elsif DONT[0] == $1[0] # respond to "IAC DON'T x" with "IAC WON'T x"
self.write(IAC + WONT + $1[1..1])
''
elsif WILL[0] == $1[0] # respond to "IAC WILL x"
if OPT_BINARY[0] == $1[1]
self.write(IAC + DO + OPT_BINARY)
elsif OPT_ECHO[0] == $1[1]
self.write(IAC + DO + OPT_ECHO)
elsif OPT_SGA[0] == $1[1]
@telnet_option["SGA"] = true
self.write(IAC + DO + OPT_SGA)
else
self.write(IAC + DONT + $1[1..1])
end
''
elsif WONT[0] == $1[0] # respond to "IAC WON'T x"
if OPT_ECHO[0] == $1[1]
self.write(IAC + DONT + OPT_ECHO)
elsif OPT_SGA[0] == $1[1]
@telnet_option["SGA"] = false
self.write(IAC + DONT + OPT_SGA)
else
self.write(IAC + DONT + $1[1..1])
end
''
else
''
end
end
end # preprocess
# Read data from the host until a certain sequence is matched.
#
# If a block is given, the received data will be yielded as it
# is read in (not necessarily all in one go), or nil if EOF
# occurs before any data is received. Whether a block is given
# or not, all data read will be returned in a single string, or again
# nil if EOF occurs before any data is received. Note that
# received data includes the matched sequence we were looking for.
#
# +options+ can be either a regular expression or a hash of options.
# If a regular expression, this specifies the data to wait for.
# If a hash, this can specify the following options:
#
# Match:: a regular expression, specifying the data to wait for.
# Prompt:: as for Match; used only if Match is not specified.
# String:: as for Match, except a string that will be converted
# into a regular expression. Used only if Match and
# Prompt are not specified.
# Timeout:: the number of seconds to wait for data from the host
# before raising a TimeoutError. If set to false,
# no timeout will occur. If not specified, the
# Timeout option value specified when this instance
# was created will be used, or, failing that, the
# default value of 10 seconds.
# Waittime:: the number of seconds to wait after matching against
# the input data to see if more data arrives. If more
# data arrives within this time, we will judge ourselves
# not to have matched successfully, and will continue
# trying to match. If not specified, the Waittime option
# value specified when this instance was created will be
# used, or, failing that, the default value of 0 seconds,
# which means not to wait for more input.
# FailEOF:: if true, when the remote end closes the connection then an
# EOFError will be raised. Otherwise, defaults to the old
# behaviour that the function will return whatever data
# has been received already, or nil if nothing was received.
#
def waitfor(options) # :yield: recvdata
time_out = @options["Timeout"]
waittime = @options["Waittime"]
fail_eof = @options["FailEOF"]
if options.kind_of?(Hash)
prompt = if options.has_key?("Match")
options["Match"]
elsif options.has_key?("Prompt")
options["Prompt"]
elsif options.has_key?("String")
Regexp.new( Regexp.quote(options["String"]) )
end
time_out = options["Timeout"] if options.has_key?("Timeout")
waittime = options["Waittime"] if options.has_key?("Waittime")
fail_eof = options["FailEOF"] if options.has_key?("FailEOF")
else
prompt = options
end
if time_out == false
time_out = nil
end
line = ''
buf = ''
rest = ''
until(prompt === line and not IO::select([@sock], nil, nil, waittime))
unless IO::select([@sock], nil, nil, time_out)
raise TimeoutError, "timed out while waiting for more data"
end
begin
c = @sock.readpartial(1024 * 1024)
@dumplog.log_dump('<', c) if @options.has_key?("Dump_log")
if @options["Telnetmode"]
c = rest + c
if Integer(c.rindex(/#{IAC}#{SE}/no)) <
Integer(c.rindex(/#{IAC}#{SB}/no))
buf = preprocess(c[0 ... c.rindex(/#{IAC}#{SB}/no)])
rest = c[c.rindex(/#{IAC}#{SB}/no) .. -1]
elsif pt = c.rindex(/#{IAC}[^#{IAC}#{AO}#{AYT}#{DM}#{IP}#{NOP}]?\z/no) ||
c.rindex(/\r\z/no)
buf = preprocess(c[0 ... pt])
rest = c[pt .. -1]
else
buf = preprocess(c)
rest = ''
end
else
# Not Telnetmode.
#
# We cannot use preprocess() on this data, because that
# method makes some Telnetmode-specific assumptions.
buf = rest + c
rest = ''
unless @options["Binmode"]
if pt = buf.rindex(/\r\z/no)
buf = buf[0 ... pt]
rest = buf[pt .. -1]
end
buf.gsub!(/#{EOL}/no, "\n")
end
end
@log.print(buf) if @options.has_key?("Output_log")
line += buf
yield buf if block_given?
rescue EOFError # End of file reached
raise if fail_eof
if line == ''
line = nil
yield nil if block_given?
end
break
end
end
line
end
# Write +string+ to the host.
#
# Does not perform any conversions on +string+. Will log +string+ to the
# dumplog, if the Dump_log option is set.
def write(string)
length = string.length
while 0 < length
IO::select(nil, [@sock])
@dumplog.log_dump('>', string[-length..-1]) if @options.has_key?("Dump_log")
length -= @sock.syswrite(string[-length..-1])
end
end
# Sends a string to the host.
#
# This does _not_ automatically append a newline to the string. Embedded
# newlines may be converted and telnet command sequences escaped
# depending upon the values of telnetmode, binmode, and telnet options
# set by the host.
def print(string)
string = string.gsub(/#{IAC}/no, IAC + IAC) if @options["Telnetmode"]
if @options["Binmode"]
self.write(string)
else
if @telnet_option["BINARY"] and @telnet_option["SGA"]
# IAC WILL SGA IAC DO BIN send EOL --> CR
self.write(string.gsub(/\n/n, CR))
elsif @telnet_option["SGA"]
# IAC WILL SGA send EOL --> CR+NULL
self.write(string.gsub(/\n/n, CR + NULL))
else
# NONE send EOL --> CR+LF
self.write(string.gsub(/\n/n, EOL))
end
end
end
# Sends a string to the host.
#
# Same as #print(), but appends a newline to the string.
def puts(string)
self.print(string + "\n")
end
# Send a command to the host.
#
# More exactly, sends a string to the host, and reads in all received
# data until is sees the prompt or other matched sequence.
#
# If a block is given, the received data will be yielded to it as
# it is read in. Whether a block is given or not, the received data
# will be return as a string. Note that the received data includes
# the prompt and in most cases the host's echo of our command.
#
# +options+ is either a String, specified the string or command to
# send to the host; or it is a hash of options. If a hash, the
# following options can be specified:
#
# String:: the command or other string to send to the host.
# Match:: a regular expression, the sequence to look for in
# the received data before returning. If not specified,
# the Prompt option value specified when this instance
# was created will be used, or, failing that, the default
# prompt of /[$%#>] \z/n.
# Timeout:: the seconds to wait for data from the host before raising
# a Timeout error. If not specified, the Timeout option
# value specified when this instance was created will be
# used, or, failing that, the default value of 10 seconds.
#
# The command or other string will have the newline sequence appended
# to it.
def cmd(options) # :yield: recvdata
match = @options["Prompt"]
time_out = @options["Timeout"]
if options.kind_of?(Hash)
string = options["String"]
match = options["Match"] if options.has_key?("Match")
time_out = options["Timeout"] if options.has_key?("Timeout")
else
string = options
end
self.puts(string)
if block_given?
waitfor({"Prompt" => match, "Timeout" => time_out}){|c| yield c }
else
waitfor({"Prompt" => match, "Timeout" => time_out})
end
end
# Login to the host with a given username and password.
#
# The username and password can either be provided as two string
# arguments in that order, or as a hash with keys "Name" and
# "Password".
#
# This method looks for the strings "login" and "Password" from the
# host to determine when to send the username and password. If the
# login sequence does not follow this pattern (for instance, you
# are connecting to a service other than telnet), you will need
# to handle login yourself.
#
# The password can be omitted, either by only
# provided one String argument, which will be used as the username,
# or by providing a has that has no "Password" key. In this case,
# the method will not look for the "Password:" prompt; if it is
# sent, it will have to be dealt with by later calls.
#
# The method returns all data received during the login process from
# the host, including the echoed username but not the password (which
# the host should not echo). If a block is passed in, this received
# data is also yielded to the block as it is received.
def login(options, password = nil) # :yield: recvdata
login_prompt = /[Ll]ogin[: ]*\z/n
password_prompt = /[Pp]ass(?:word|phrase)[: ]*\z/n
if options.kind_of?(Hash)
username = options["Name"]
password = options["Password"]
login_prompt = options["LoginPrompt"] if options["LoginPrompt"]
password_prompt = options["PasswordPrompt"] if options["PasswordPrompt"]
else
username = options
end
if block_given?
line = waitfor(login_prompt){|c| yield c }
if password
line += cmd({"String" => username,
"Match" => password_prompt}){|c| yield c }
line += cmd(password){|c| yield c }
else
line += cmd(username){|c| yield c }
end
else
line = waitfor(login_prompt)
if password
line += cmd({"String" => username,
"Match" => password_prompt})
line += cmd(password)
else
line += cmd(username)
end
end
line
end
end # class Telnet
end # module Net
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/net/ftp.rb | tools/jruby-1.5.1/lib/ruby/1.8/net/ftp.rb | #
# = net/ftp.rb - FTP Client Library
#
# Written by Shugo Maeda <shugo@ruby-lang.org>.
#
# Documentation by Gavin Sinclair, sourced from "Programming Ruby" (Hunt/Thomas)
# and "Ruby In a Nutshell" (Matsumoto), used with permission.
#
# This library is distributed under the terms of the Ruby license.
# You can freely distribute/modify this library.
#
# It is included in the Ruby standard library.
#
# See the Net::FTP class for an overview.
#
require "socket"
require "monitor"
module Net
# :stopdoc:
class FTPError < StandardError; end
class FTPReplyError < FTPError; end
class FTPTempError < FTPError; end
class FTPPermError < FTPError; end
class FTPProtoError < FTPError; end
# :startdoc:
#
# This class implements the File Transfer Protocol. If you have used a
# command-line FTP program, and are familiar with the commands, you will be
# able to use this class easily. Some extra features are included to take
# advantage of Ruby's style and strengths.
#
# == Example
#
# require 'net/ftp'
#
# === Example 1
#
# ftp = Net::FTP.new('ftp.netlab.co.jp')
# ftp.login
# files = ftp.chdir('pub/lang/ruby/contrib')
# files = ftp.list('n*')
# ftp.getbinaryfile('nif.rb-0.91.gz', 'nif.gz', 1024)
# ftp.close
#
# === Example 2
#
# Net::FTP.open('ftp.netlab.co.jp') do |ftp|
# ftp.login
# files = ftp.chdir('pub/lang/ruby/contrib')
# files = ftp.list('n*')
# ftp.getbinaryfile('nif.rb-0.91.gz', 'nif.gz', 1024)
# end
#
# == Major Methods
#
# The following are the methods most likely to be useful to users:
# - FTP.open
# - #getbinaryfile
# - #gettextfile
# - #putbinaryfile
# - #puttextfile
# - #chdir
# - #nlst
# - #size
# - #rename
# - #delete
#
class FTP
include MonitorMixin
# :stopdoc:
FTP_PORT = 21
CRLF = "\r\n"
DEFAULT_BLOCKSIZE = 4096
# :startdoc:
# When +true+, transfers are performed in binary mode. Default: +true+.
attr_accessor :binary
# When +true+, the connection is in passive mode. Default: +false+.
attr_accessor :passive
# When +true+, all traffic to and from the server is written
# to +$stdout+. Default: +false+.
attr_accessor :debug_mode
# Sets or retrieves the +resume+ status, which decides whether incomplete
# transfers are resumed or restarted. Default: +false+.
attr_accessor :resume
# The server's welcome message.
attr_reader :welcome
# The server's last response code.
attr_reader :last_response_code
alias lastresp last_response_code
# The server's last response.
attr_reader :last_response
#
# A synonym for <tt>FTP.new</tt>, but with a mandatory host parameter.
#
# If a block is given, it is passed the +FTP+ object, which will be closed
# when the block finishes, or when an exception is raised.
#
def FTP.open(host, user = nil, passwd = nil, acct = nil)
if block_given?
ftp = new(host, user, passwd, acct)
begin
yield ftp
ensure
ftp.close
end
else
new(host, user, passwd, acct)
end
end
#
# Creates and returns a new +FTP+ object. If a +host+ is given, a connection
# is made. Additionally, if the +user+ is given, the given user name,
# password, and (optionally) account are used to log in. See #login.
#
def initialize(host = nil, user = nil, passwd = nil, acct = nil)
super()
@binary = true
@passive = false
@debug_mode = false
@resume = false
if host
connect(host)
if user
login(user, passwd, acct)
end
end
end
# Obsolete
def return_code
$stderr.puts("warning: Net::FTP#return_code is obsolete and do nothing")
return "\n"
end
# Obsolete
def return_code=(s)
$stderr.puts("warning: Net::FTP#return_code= is obsolete and do nothing")
end
def open_socket(host, port)
if defined? SOCKSSocket and ENV["SOCKS_SERVER"]
@passive = true
return SOCKSSocket.open(host, port)
else
return TCPSocket.open(host, port)
end
end
private :open_socket
#
# Establishes an FTP connection to host, optionally overriding the default
# port. If the environment variable +SOCKS_SERVER+ is set, sets up the
# connection through a SOCKS proxy. Raises an exception (typically
# <tt>Errno::ECONNREFUSED</tt>) if the connection cannot be established.
#
def connect(host, port = FTP_PORT)
if @debug_mode
print "connect: ", host, ", ", port, "\n"
end
synchronize do
@sock = open_socket(host, port)
voidresp
end
end
#
# WRITEME or make private
#
def set_socket(sock, get_greeting = true)
synchronize do
@sock = sock
if get_greeting
voidresp
end
end
end
def sanitize(s)
if s =~ /^PASS /i
return s[0, 5] + "*" * (s.length - 5)
else
return s
end
end
private :sanitize
def putline(line)
if @debug_mode
print "put: ", sanitize(line), "\n"
end
line = line + CRLF
@sock.write(line)
end
private :putline
def getline
line = @sock.readline # if get EOF, raise EOFError
line.sub!(/(\r\n|\n|\r)\z/n, "")
if @debug_mode
print "get: ", sanitize(line), "\n"
end
return line
end
private :getline
def getmultiline
line = getline
buff = line
if line[3] == ?-
code = line[0, 3]
begin
line = getline
buff << "\n" << line
end until line[0, 3] == code and line[3] != ?-
end
return buff << "\n"
end
private :getmultiline
def getresp
@last_response = getmultiline
@last_response_code = @last_response[0, 3]
case @last_response_code
when /\A[123]/
return @last_response
when /\A4/
raise FTPTempError, @last_response
when /\A5/
raise FTPPermError, @last_response
else
raise FTPProtoError, @last_response
end
end
private :getresp
def voidresp
resp = getresp
if resp[0] != ?2
raise FTPReplyError, resp
end
end
private :voidresp
#
# Sends a command and returns the response.
#
def sendcmd(cmd)
synchronize do
putline(cmd)
return getresp
end
end
#
# Sends a command and expect a response beginning with '2'.
#
def voidcmd(cmd)
synchronize do
putline(cmd)
voidresp
end
end
def sendport(host, port)
af = (@sock.peeraddr)[0]
if af == "AF_INET"
cmd = "PORT " + (host.split(".") + port.divmod(256)).join(",")
elsif af == "AF_INET6"
cmd = sprintf("EPRT |2|%s|%d|", host, port)
else
raise FTPProtoError, host
end
voidcmd(cmd)
end
private :sendport
def makeport
sock = TCPServer.open(@sock.addr[3], 0)
port = sock.addr[1]
host = sock.addr[3]
resp = sendport(host, port)
return sock
end
private :makeport
def makepasv
if @sock.peeraddr[0] == "AF_INET"
host, port = parse227(sendcmd("PASV"))
else
host, port = parse229(sendcmd("EPSV"))
# host, port = parse228(sendcmd("LPSV"))
end
return host, port
end
private :makepasv
def transfercmd(cmd, rest_offset = nil)
if @passive
host, port = makepasv
conn = open_socket(host, port)
if @resume and rest_offset
resp = sendcmd("REST " + rest_offset.to_s)
if resp[0] != ?3
raise FTPReplyError, resp
end
end
resp = sendcmd(cmd)
# skip 2XX for some ftp servers
resp = getresp if resp[0] == ?2
if resp[0] != ?1
raise FTPReplyError, resp
end
else
sock = makeport
if @resume and rest_offset
resp = sendcmd("REST " + rest_offset.to_s)
if resp[0] != ?3
raise FTPReplyError, resp
end
end
resp = sendcmd(cmd)
# skip 2XX for some ftp servers
resp = getresp if resp[0] == ?2
if resp[0] != ?1
raise FTPReplyError, resp
end
conn = sock.accept
sock.close
end
return conn
end
private :transfercmd
def getaddress
thishost = Socket.gethostname rescue ""
if not thishost.index(".")
thishost = Socket.gethostbyname(thishost)[0] rescue ""
end
if ENV.has_key?("LOGNAME")
realuser = ENV["LOGNAME"]
elsif ENV.has_key?("USER")
realuser = ENV["USER"]
else
realuser = "anonymous"
end
return realuser + "@" + thishost
end
private :getaddress
#
# Logs in to the remote host. The session must have been previously
# connected. If +user+ is the string "anonymous" and the +password+ is
# +nil+, a password of <tt>user@host</tt> is synthesized. If the +acct+
# parameter is not +nil+, an FTP ACCT command is sent following the
# successful login. Raises an exception on error (typically
# <tt>Net::FTPPermError</tt>).
#
def login(user = "anonymous", passwd = nil, acct = nil)
if user == "anonymous" and passwd == nil
passwd = getaddress
end
resp = ""
synchronize do
resp = sendcmd('USER ' + user)
if resp[0] == ?3
raise FTPReplyError, resp if passwd.nil?
resp = sendcmd('PASS ' + passwd)
end
if resp[0] == ?3
raise FTPReplyError, resp if acct.nil?
resp = sendcmd('ACCT ' + acct)
end
end
if resp[0] != ?2
raise FTPReplyError, resp
end
@welcome = resp
end
#
# Puts the connection into binary (image) mode, issues the given command,
# and fetches the data returned, passing it to the associated block in
# chunks of +blocksize+ characters. Note that +cmd+ is a server command
# (such as "RETR myfile").
#
def retrbinary(cmd, blocksize, rest_offset = nil) # :yield: data
synchronize do
voidcmd("TYPE I")
conn = transfercmd(cmd, rest_offset)
loop do
data = conn.read(blocksize)
break if data == nil
yield(data)
end
conn.close
voidresp
end
end
#
# Puts the connection into ASCII (text) mode, issues the given command, and
# passes the resulting data, one line at a time, to the associated block. If
# no block is given, prints the lines. Note that +cmd+ is a server command
# (such as "RETR myfile").
#
def retrlines(cmd) # :yield: line
synchronize do
voidcmd("TYPE A")
conn = transfercmd(cmd)
loop do
line = conn.gets
break if line == nil
if line[-2, 2] == CRLF
line = line[0 .. -3]
elsif line[-1] == ?\n
line = line[0 .. -2]
end
yield(line)
end
conn.close
voidresp
end
end
#
# Puts the connection into binary (image) mode, issues the given server-side
# command (such as "STOR myfile"), and sends the contents of the file named
# +file+ to the server. If the optional block is given, it also passes it
# the data, in chunks of +blocksize+ characters.
#
def storbinary(cmd, file, blocksize, rest_offset = nil, &block) # :yield: data
if rest_offset
file.seek(rest_offset, IO::SEEK_SET)
end
synchronize do
voidcmd("TYPE I")
conn = transfercmd(cmd, rest_offset)
loop do
buf = file.read(blocksize)
break if buf == nil
conn.write(buf)
yield(buf) if block
end
conn.close
voidresp
end
end
#
# Puts the connection into ASCII (text) mode, issues the given server-side
# command (such as "STOR myfile"), and sends the contents of the file
# named +file+ to the server, one line at a time. If the optional block is
# given, it also passes it the lines.
#
def storlines(cmd, file, &block) # :yield: line
synchronize do
voidcmd("TYPE A")
conn = transfercmd(cmd)
loop do
buf = file.gets
break if buf == nil
if buf[-2, 2] != CRLF
buf = buf.chomp + CRLF
end
conn.write(buf)
yield(buf) if block
end
conn.close
voidresp
end
end
#
# Retrieves +remotefile+ in binary mode, storing the result in +localfile+.
# If a block is supplied, it is passed the retrieved data in +blocksize+
# chunks.
#
def getbinaryfile(remotefile, localfile = File.basename(remotefile),
blocksize = DEFAULT_BLOCKSIZE, &block) # :yield: data
if @resume
rest_offset = File.size?(localfile)
f = open(localfile, "a")
else
rest_offset = nil
f = open(localfile, "w")
end
begin
f.binmode
retrbinary("RETR " + remotefile, blocksize, rest_offset) do |data|
f.write(data)
yield(data) if block
end
ensure
f.close
end
end
#
# Retrieves +remotefile+ in ASCII (text) mode, storing the result in
# +localfile+. If a block is supplied, it is passed the retrieved data one
# line at a time.
#
def gettextfile(remotefile, localfile = File.basename(remotefile), &block) # :yield: line
f = open(localfile, "w")
begin
retrlines("RETR " + remotefile) do |line|
f.puts(line)
yield(line) if block
end
ensure
f.close
end
end
#
# Retrieves +remotefile+ in whatever mode the session is set (text or
# binary). See #gettextfile and #getbinaryfile.
#
def get(remotefile, localfile = File.basename(remotefile),
blocksize = DEFAULT_BLOCKSIZE, &block) # :yield: data
unless @binary
gettextfile(remotefile, localfile, &block)
else
getbinaryfile(remotefile, localfile, blocksize, &block)
end
end
#
# Transfers +localfile+ to the server in binary mode, storing the result in
# +remotefile+. If a block is supplied, calls it, passing in the transmitted
# data in +blocksize+ chunks.
#
def putbinaryfile(localfile, remotefile = File.basename(localfile),
blocksize = DEFAULT_BLOCKSIZE, &block) # :yield: data
if @resume
begin
rest_offset = size(remotefile)
rescue Net::FTPPermError
rest_offset = nil
end
else
rest_offset = nil
end
f = open(localfile)
begin
f.binmode
storbinary("STOR " + remotefile, f, blocksize, rest_offset, &block)
ensure
f.close
end
end
#
# Transfers +localfile+ to the server in ASCII (text) mode, storing the result
# in +remotefile+. If callback or an associated block is supplied, calls it,
# passing in the transmitted data one line at a time.
#
def puttextfile(localfile, remotefile = File.basename(localfile), &block) # :yield: line
f = open(localfile)
begin
storlines("STOR " + remotefile, f, &block)
ensure
f.close
end
end
#
# Transfers +localfile+ to the server in whatever mode the session is set
# (text or binary). See #puttextfile and #putbinaryfile.
#
def put(localfile, remotefile = File.basename(localfile),
blocksize = DEFAULT_BLOCKSIZE, &block)
unless @binary
puttextfile(localfile, remotefile, &block)
else
putbinaryfile(localfile, remotefile, blocksize, &block)
end
end
#
# Sends the ACCT command. TODO: more info.
#
def acct(account)
cmd = "ACCT " + account
voidcmd(cmd)
end
#
# Returns an array of filenames in the remote directory.
#
def nlst(dir = nil)
cmd = "NLST"
if dir
cmd = cmd + " " + dir
end
files = []
retrlines(cmd) do |line|
files.push(line)
end
return files
end
#
# Returns an array of file information in the directory (the output is like
# `ls -l`). If a block is given, it iterates through the listing.
#
def list(*args, &block) # :yield: line
cmd = "LIST"
args.each do |arg|
cmd = cmd + " " + arg
end
if block
retrlines(cmd, &block)
else
lines = []
retrlines(cmd) do |line|
lines << line
end
return lines
end
end
alias ls list
alias dir list
#
# Renames a file on the server.
#
def rename(fromname, toname)
resp = sendcmd("RNFR " + fromname)
if resp[0] != ?3
raise FTPReplyError, resp
end
voidcmd("RNTO " + toname)
end
#
# Deletes a file on the server.
#
def delete(filename)
resp = sendcmd("DELE " + filename)
if resp[0, 3] == "250"
return
elsif resp[0] == ?5
raise FTPPermError, resp
else
raise FTPReplyError, resp
end
end
#
# Changes the (remote) directory.
#
def chdir(dirname)
if dirname == ".."
begin
voidcmd("CDUP")
return
rescue FTPPermError => e
if e.message[0, 3] != "500"
raise e
end
end
end
cmd = "CWD " + dirname
voidcmd(cmd)
end
#
# Returns the size of the given (remote) filename.
#
def size(filename)
voidcmd("TYPE I")
resp = sendcmd("SIZE " + filename)
if resp[0, 3] != "213"
raise FTPReplyError, resp
end
return resp[3..-1].strip.to_i
end
MDTM_REGEXP = /^(\d\d\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/ # :nodoc:
#
# Returns the last modification time of the (remote) file. If +local+ is
# +true+, it is returned as a local time, otherwise it's a UTC time.
#
def mtime(filename, local = false)
str = mdtm(filename)
ary = str.scan(MDTM_REGEXP)[0].collect {|i| i.to_i}
return local ? Time.local(*ary) : Time.gm(*ary)
end
#
# Creates a remote directory.
#
def mkdir(dirname)
resp = sendcmd("MKD " + dirname)
return parse257(resp)
end
#
# Removes a remote directory.
#
def rmdir(dirname)
voidcmd("RMD " + dirname)
end
#
# Returns the current remote directory.
#
def pwd
resp = sendcmd("PWD")
return parse257(resp)
end
alias getdir pwd
#
# Returns system information.
#
def system
resp = sendcmd("SYST")
if resp[0, 3] != "215"
raise FTPReplyError, resp
end
return resp[4 .. -1]
end
#
# Aborts the previous command (ABOR command).
#
def abort
line = "ABOR" + CRLF
print "put: ABOR\n" if @debug_mode
@sock.send(line, Socket::MSG_OOB)
resp = getmultiline
unless ["426", "226", "225"].include?(resp[0, 3])
raise FTPProtoError, resp
end
return resp
end
#
# Returns the status (STAT command).
#
def status
line = "STAT" + CRLF
print "put: STAT\n" if @debug_mode
@sock.send(line, Socket::MSG_OOB)
return getresp
end
#
# Issues the MDTM command. TODO: more info.
#
def mdtm(filename)
resp = sendcmd("MDTM " + filename)
if resp[0, 3] == "213"
return resp[3 .. -1].strip
end
end
#
# Issues the HELP command.
#
def help(arg = nil)
cmd = "HELP"
if arg
cmd = cmd + " " + arg
end
sendcmd(cmd)
end
#
# Exits the FTP session.
#
def quit
voidcmd("QUIT")
end
#
# Issues a NOOP command.
#
def noop
voidcmd("NOOP")
end
#
# Issues a SITE command.
#
def site(arg)
cmd = "SITE " + arg
voidcmd(cmd)
end
#
# Closes the connection. Further operations are impossible until you open
# a new connection with #connect.
#
def close
@sock.close if @sock and not @sock.closed?
end
#
# Returns +true+ iff the connection is closed.
#
def closed?
@sock == nil or @sock.closed?
end
def parse227(resp)
if resp[0, 3] != "227"
raise FTPReplyError, resp
end
left = resp.index("(")
right = resp.index(")")
if left == nil or right == nil
raise FTPProtoError, resp
end
numbers = resp[left + 1 .. right - 1].split(",")
if numbers.length != 6
raise FTPProtoError, resp
end
host = numbers[0, 4].join(".")
port = (numbers[4].to_i << 8) + numbers[5].to_i
return host, port
end
private :parse227
def parse228(resp)
if resp[0, 3] != "228"
raise FTPReplyError, resp
end
left = resp.index("(")
right = resp.index(")")
if left == nil or right == nil
raise FTPProtoError, resp
end
numbers = resp[left + 1 .. right - 1].split(",")
if numbers[0] == "4"
if numbers.length != 9 || numbers[1] != "4" || numbers[2 + 4] != "2"
raise FTPProtoError, resp
end
host = numbers[2, 4].join(".")
port = (numbers[7].to_i << 8) + numbers[8].to_i
elsif numbers[0] == "6"
if numbers.length != 21 || numbers[1] != "16" || numbers[2 + 16] != "2"
raise FTPProtoError, resp
end
v6 = ["", "", "", "", "", "", "", ""]
for i in 0 .. 7
v6[i] = sprintf("%02x%02x", numbers[(i * 2) + 2].to_i,
numbers[(i * 2) + 3].to_i)
end
host = v6[0, 8].join(":")
port = (numbers[19].to_i << 8) + numbers[20].to_i
end
return host, port
end
private :parse228
def parse229(resp)
if resp[0, 3] != "229"
raise FTPReplyError, resp
end
left = resp.index("(")
right = resp.index(")")
if left == nil or right == nil
raise FTPProtoError, resp
end
numbers = resp[left + 1 .. right - 1].split(resp[left + 1, 1])
if numbers.length != 4
raise FTPProtoError, resp
end
port = numbers[3].to_i
host = (@sock.peeraddr())[3]
return host, port
end
private :parse229
def parse257(resp)
if resp[0, 3] != "257"
raise FTPReplyError, resp
end
if resp[3, 2] != ' "'
return ""
end
dirname = ""
i = 5
n = resp.length
while i < n
c = resp[i, 1]
i = i + 1
if c == '"'
if i > n or resp[i, 1] != '"'
break
end
i = i + 1
end
dirname = dirname + c
end
return dirname
end
private :parse257
end
end
# Documentation comments:
# - sourced from pickaxe and nutshell, with improvements (hopefully)
# - three methods should be private (search WRITEME)
# - two methods need more information (search TODO)
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/net/smtp.rb | tools/jruby-1.5.1/lib/ruby/1.8/net/smtp.rb | # = net/smtp.rb
#
# Copyright (c) 1999-2007 Yukihiro Matsumoto.
#
# Copyright (c) 1999-2007 Minero Aoki.
#
# Written & maintained by Minero Aoki <aamine@loveruby.net>.
#
# Documented by William Webber and Minero Aoki.
#
# This program is free software. You can re-distribute and/or
# modify this program under the same terms as Ruby itself.
#
# NOTE: You can find Japanese version of this document at:
# http://www.ruby-lang.org/ja/man/html/net_smtp.html
#
# $Id: smtp.rb 18353 2008-08-04 05:51:11Z shyouhei $
#
# See Net::SMTP for documentation.
#
require 'net/protocol'
require 'digest/md5'
require 'timeout'
begin
require 'openssl'
rescue LoadError
end
module Net
# Module mixed in to all SMTP error classes
module SMTPError
# This *class* is a module for backward compatibility.
# In later release, this module becomes a class.
end
# Represents an SMTP authentication error.
class SMTPAuthenticationError < ProtoAuthError
include SMTPError
end
# Represents SMTP error code 420 or 450, a temporary error.
class SMTPServerBusy < ProtoServerError
include SMTPError
end
# Represents an SMTP command syntax error (error code 500)
class SMTPSyntaxError < ProtoSyntaxError
include SMTPError
end
# Represents a fatal SMTP error (error code 5xx, except for 500)
class SMTPFatalError < ProtoFatalError
include SMTPError
end
# Unexpected reply code returned from server.
class SMTPUnknownError < ProtoUnknownError
include SMTPError
end
# Command is not supported on server.
class SMTPUnsupportedCommand < ProtocolError
include SMTPError
end
#
# = Net::SMTP
#
# == What is This Library?
#
# This library provides functionality to send internet
# mail via SMTP, the Simple Mail Transfer Protocol. For details of
# SMTP itself, see [RFC2821] (http://www.ietf.org/rfc/rfc2821.txt).
#
# == What is This Library NOT?
#
# This library does NOT provide functions to compose internet mails.
# You must create them by yourself. If you want better mail support,
# try RubyMail or TMail. You can get both libraries from RAA.
# (http://www.ruby-lang.org/en/raa.html)
#
# FYI: the official documentation on internet mail is: [RFC2822] (http://www.ietf.org/rfc/rfc2822.txt).
#
# == Examples
#
# === Sending Messages
#
# You must open a connection to an SMTP server before sending messages.
# The first argument is the address of your SMTP server, and the second
# argument is the port number. Using SMTP.start with a block is the simplest
# way to do this. This way, the SMTP connection is closed automatically
# after the block is executed.
#
# require 'net/smtp'
# Net::SMTP.start('your.smtp.server', 25) do |smtp|
# # Use the SMTP object smtp only in this block.
# end
#
# Replace 'your.smtp.server' with your SMTP server. Normally
# your system manager or internet provider supplies a server
# for you.
#
# Then you can send messages.
#
# msgstr = <<END_OF_MESSAGE
# From: Your Name <your@mail.address>
# To: Destination Address <someone@example.com>
# Subject: test message
# Date: Sat, 23 Jun 2001 16:26:43 +0900
# Message-Id: <unique.message.id.string@example.com>
#
# This is a test message.
# END_OF_MESSAGE
#
# require 'net/smtp'
# Net::SMTP.start('your.smtp.server', 25) do |smtp|
# smtp.send_message msgstr,
# 'your@mail.address',
# 'his_addess@example.com'
# end
#
# === Closing the Session
#
# You MUST close the SMTP session after sending messages, by calling
# the #finish method:
#
# # using SMTP#finish
# smtp = Net::SMTP.start('your.smtp.server', 25)
# smtp.send_message msgstr, 'from@address', 'to@address'
# smtp.finish
#
# You can also use the block form of SMTP.start/SMTP#start. This closes
# the SMTP session automatically:
#
# # using block form of SMTP.start
# Net::SMTP.start('your.smtp.server', 25) do |smtp|
# smtp.send_message msgstr, 'from@address', 'to@address'
# end
#
# I strongly recommend this scheme. This form is simpler and more robust.
#
# === HELO domain
#
# In almost all situations, you must provide a third argument
# to SMTP.start/SMTP#start. This is the domain name which you are on
# (the host to send mail from). It is called the "HELO domain".
# The SMTP server will judge whether it should send or reject
# the SMTP session by inspecting the HELO domain.
#
# Net::SMTP.start('your.smtp.server', 25,
# 'mail.from.domain') { |smtp| ... }
#
# === SMTP Authentication
#
# The Net::SMTP class supports three authentication schemes;
# PLAIN, LOGIN and CRAM MD5. (SMTP Authentication: [RFC2554])
# To use SMTP authentication, pass extra arguments to
# SMTP.start/SMTP#start.
#
# # PLAIN
# Net::SMTP.start('your.smtp.server', 25, 'mail.from.domain',
# 'Your Account', 'Your Password', :plain)
# # LOGIN
# Net::SMTP.start('your.smtp.server', 25, 'mail.from.domain',
# 'Your Account', 'Your Password', :login)
#
# # CRAM MD5
# Net::SMTP.start('your.smtp.server', 25, 'mail.from.domain',
# 'Your Account', 'Your Password', :cram_md5)
#
class SMTP
Revision = %q$Revision: 18353 $.split[1]
# The default SMTP port number, 25.
def SMTP.default_port
25
end
# The default mail submission port number, 587.
def SMTP.default_submission_port
587
end
# The default SMTPS port number, 465.
def SMTP.default_tls_port
465
end
class << self
alias default_ssl_port default_tls_port
end
def SMTP.default_ssl_context
OpenSSL::SSL::SSLContext.new
end
#
# Creates a new Net::SMTP object.
#
# +address+ is the hostname or ip address of your SMTP
# server. +port+ is the port to connect to; it defaults to
# port 25.
#
# This method does not open the TCP connection. You can use
# SMTP.start instead of SMTP.new if you want to do everything
# at once. Otherwise, follow SMTP.new with SMTP#start.
#
def initialize(address, port = nil)
@address = address
@port = (port || SMTP.default_port)
@esmtp = true
@capabilities = nil
@socket = nil
@started = false
@open_timeout = 30
@read_timeout = 60
@error_occured = false
@debug_output = nil
@tls = false
@starttls = false
@ssl_context = nil
end
# Provide human-readable stringification of class state.
def inspect
"#<#{self.class} #{@address}:#{@port} started=#{@started}>"
end
# +true+ if the SMTP object uses ESMTP (which it does by default).
def esmtp?
@esmtp
end
#
# Set whether to use ESMTP or not. This should be done before
# calling #start. Note that if #start is called in ESMTP mode,
# and the connection fails due to a ProtocolError, the SMTP
# object will automatically switch to plain SMTP mode and
# retry (but not vice versa).
#
def esmtp=(bool)
@esmtp = bool
end
alias esmtp esmtp?
# true if server advertises STARTTLS.
# You cannot get valid value before opening SMTP session.
def capable_starttls?
capable?('STARTTLS')
end
def capable?(key)
return nil unless @capabilities
@capabilities[key] ? true : false
end
private :capable?
# true if server advertises AUTH PLAIN.
# You cannot get valid value before opening SMTP session.
def capable_plain_auth?
auth_capable?('PLAIN')
end
# true if server advertises AUTH LOGIN.
# You cannot get valid value before opening SMTP session.
def capable_login_auth?
auth_capable?('LOGIN')
end
# true if server advertises AUTH CRAM-MD5.
# You cannot get valid value before opening SMTP session.
def capable_cram_md5_auth?
auth_capable?('CRAM-MD5')
end
def auth_capable?(type)
return nil unless @capabilities
return false unless @capabilities['AUTH']
@capabilities['AUTH'].include?(type)
end
private :auth_capable?
# Returns supported authentication methods on this server.
# You cannot get valid value before opening SMTP session.
def capable_auth_types
return [] unless @capabilities
return [] unless @capabilities['AUTH']
@capabilities['AUTH']
end
# true if this object uses SMTP/TLS (SMTPS).
def tls?
@tls
end
alias ssl? tls?
# Enables SMTP/TLS (SMTPS: SMTP over direct TLS connection) for
# this object. Must be called before the connection is established
# to have any effect. +context+ is a OpenSSL::SSL::SSLContext object.
def enable_tls(context = SMTP.default_ssl_context)
raise 'openssl library not installed' unless defined?(OpenSSL)
raise ArgumentError, "SMTPS and STARTTLS is exclusive" if @starttls
@tls = true
@ssl_context = context
end
alias enable_ssl enable_tls
# Disables SMTP/TLS for this object. Must be called before the
# connection is established to have any effect.
def disable_tls
@tls = false
@ssl_context = nil
end
alias disable_ssl disable_tls
# Returns truth value if this object uses STARTTLS.
# If this object always uses STARTTLS, returns :always.
# If this object uses STARTTLS when the server support TLS, returns :auto.
def starttls?
@starttls
end
# true if this object uses STARTTLS.
def starttls_always?
@starttls == :always
end
# true if this object uses STARTTLS when server advertises STARTTLS.
def starttls_auto?
@starttls == :auto
end
# Enables SMTP/TLS (STARTTLS) for this object.
# +context+ is a OpenSSL::SSL::SSLContext object.
def enable_starttls(context = SMTP.default_ssl_context)
raise 'openssl library not installed' unless defined?(OpenSSL)
raise ArgumentError, "SMTPS and STARTTLS is exclusive" if @tls
@starttls = :always
@ssl_context = context
end
# Enables SMTP/TLS (STARTTLS) for this object if server accepts.
# +context+ is a OpenSSL::SSL::SSLContext object.
def enable_starttls_auto(context = SMTP.default_ssl_context)
raise 'openssl library not installed' unless defined?(OpenSSL)
raise ArgumentError, "SMTPS and STARTTLS is exclusive" if @tls
@starttls = :auto
@ssl_context = context
end
# Disables SMTP/TLS (STARTTLS) for this object. Must be called
# before the connection is established to have any effect.
def disable_starttls
@starttls = false
@ssl_context = nil
end
# The address of the SMTP server to connect to.
attr_reader :address
# The port number of the SMTP server to connect to.
attr_reader :port
# Seconds to wait while attempting to open a connection.
# If the connection cannot be opened within this time, a
# TimeoutError is raised.
attr_accessor :open_timeout
# Seconds to wait while reading one block (by one read(2) call).
# If the read(2) call does not complete within this time, a
# TimeoutError is raised.
attr_reader :read_timeout
# Set the number of seconds to wait until timing-out a read(2)
# call.
def read_timeout=(sec)
@socket.read_timeout = sec if @socket
@read_timeout = sec
end
#
# WARNING: This method causes serious security holes.
# Use this method for only debugging.
#
# Set an output stream for debug logging.
# You must call this before #start.
#
# # example
# smtp = Net::SMTP.new(addr, port)
# smtp.set_debug_output $stderr
# smtp.start do |smtp|
# ....
# end
#
def debug_output=(arg)
@debug_output = arg
end
alias set_debug_output debug_output=
#
# SMTP session control
#
#
# Creates a new Net::SMTP object and connects to the server.
#
# This method is equivalent to:
#
# Net::SMTP.new(address, port).start(helo_domain, account, password, authtype)
#
# === Example
#
# Net::SMTP.start('your.smtp.server') do |smtp|
# smtp.send_message msgstr, 'from@example.com', ['dest@example.com']
# end
#
# === Block Usage
#
# If called with a block, the newly-opened Net::SMTP object is yielded
# to the block, and automatically closed when the block finishes. If called
# without a block, the newly-opened Net::SMTP object is returned to
# the caller, and it is the caller's responsibility to close it when
# finished.
#
# === Parameters
#
# +address+ is the hostname or ip address of your smtp server.
#
# +port+ is the port to connect to; it defaults to port 25.
#
# +helo+ is the _HELO_ _domain_ provided by the client to the
# server (see overview comments); it defaults to 'localhost.localdomain'.
#
# The remaining arguments are used for SMTP authentication, if required
# or desired. +user+ is the account name; +secret+ is your password
# or other authentication token; and +authtype+ is the authentication
# type, one of :plain, :login, or :cram_md5. See the discussion of
# SMTP Authentication in the overview notes.
#
# === Errors
#
# This method may raise:
#
# * Net::SMTPAuthenticationError
# * Net::SMTPServerBusy
# * Net::SMTPSyntaxError
# * Net::SMTPFatalError
# * Net::SMTPUnknownError
# * IOError
# * TimeoutError
#
def SMTP.start(address, port = nil, helo = 'localhost.localdomain',
user = nil, secret = nil, authtype = nil,
&block) # :yield: smtp
new(address, port).start(helo, user, secret, authtype, &block)
end
# +true+ if the SMTP session has been started.
def started?
@started
end
#
# Opens a TCP connection and starts the SMTP session.
#
# === Parameters
#
# +helo+ is the _HELO_ _domain_ that you'll dispatch mails from; see
# the discussion in the overview notes.
#
# If both of +user+ and +secret+ are given, SMTP authentication
# will be attempted using the AUTH command. +authtype+ specifies
# the type of authentication to attempt; it must be one of
# :login, :plain, and :cram_md5. See the notes on SMTP Authentication
# in the overview.
#
# === Block Usage
#
# When this methods is called with a block, the newly-started SMTP
# object is yielded to the block, and automatically closed after
# the block call finishes. Otherwise, it is the caller's
# responsibility to close the session when finished.
#
# === Example
#
# This is very similar to the class method SMTP.start.
#
# require 'net/smtp'
# smtp = Net::SMTP.new('smtp.mail.server', 25)
# smtp.start(helo_domain, account, password, authtype) do |smtp|
# smtp.send_message msgstr, 'from@example.com', ['dest@example.com']
# end
#
# The primary use of this method (as opposed to SMTP.start)
# is probably to set debugging (#set_debug_output) or ESMTP
# (#esmtp=), which must be done before the session is
# started.
#
# === Errors
#
# If session has already been started, an IOError will be raised.
#
# This method may raise:
#
# * Net::SMTPAuthenticationError
# * Net::SMTPServerBusy
# * Net::SMTPSyntaxError
# * Net::SMTPFatalError
# * Net::SMTPUnknownError
# * IOError
# * TimeoutError
#
def start(helo = 'localhost.localdomain',
user = nil, secret = nil, authtype = nil) # :yield: smtp
if block_given?
begin
do_start helo, user, secret, authtype
return yield(self)
ensure
do_finish
end
else
do_start helo, user, secret, authtype
return self
end
end
# Finishes the SMTP session and closes TCP connection.
# Raises IOError if not started.
def finish
raise IOError, 'not yet started' unless started?
do_finish
end
private
def do_start(helo_domain, user, secret, authtype)
raise IOError, 'SMTP session already started' if @started
if user or secret
check_auth_method(authtype || DEFAULT_AUTH_TYPE)
check_auth_args user, secret
end
s = timeout(@open_timeout) { TCPSocket.open(@address, @port) }
logging "Connection opened: #{@address}:#{@port}"
@socket = new_internet_message_io(tls? ? tlsconnect(s) : s)
check_response critical { recv_response() }
do_helo helo_domain
if starttls_always? or (capable_starttls? and starttls_auto?)
unless capable_starttls?
raise SMTPUnsupportedCommand,
"STARTTLS is not supported on this server"
end
starttls
@socket = new_internet_message_io(tlsconnect(s))
# helo response may be different after STARTTLS
do_helo helo_domain
end
authenticate user, secret, (authtype || DEFAULT_AUTH_TYPE) if user
@started = true
ensure
unless @started
# authentication failed, cancel connection.
s.close if s and not s.closed?
@socket = nil
end
end
def tlsconnect(s)
s = OpenSSL::SSL::SSLSocket.new(s, @ssl_context)
logging "TLS connection started"
s.sync_close = true
s.connect
if @ssl_context.verify_mode != OpenSSL::SSL::VERIFY_NONE
s.post_connection_check(@address)
end
s
end
def new_internet_message_io(s)
io = InternetMessageIO.new(s)
io.read_timeout = @read_timeout
io.debug_output = @debug_output
io
end
def do_helo(helo_domain)
res = @esmtp ? ehlo(helo_domain) : helo(helo_domain)
@capabilities = res.capabilities
rescue SMTPError
if @esmtp
@esmtp = false
@error_occured = false
retry
end
raise
end
def do_finish
quit if @socket and not @socket.closed? and not @error_occured
ensure
@started = false
@error_occured = false
@socket.close if @socket and not @socket.closed?
@socket = nil
end
#
# Message Sending
#
public
#
# Sends +msgstr+ as a message. Single CR ("\r") and LF ("\n") found
# in the +msgstr+, are converted into the CR LF pair. You cannot send a
# binary message with this method. +msgstr+ should include both
# the message headers and body.
#
# +from_addr+ is a String representing the source mail address.
#
# +to_addr+ is a String or Strings or Array of Strings, representing
# the destination mail address or addresses.
#
# === Example
#
# Net::SMTP.start('smtp.example.com') do |smtp|
# smtp.send_message msgstr,
# 'from@example.com',
# ['dest@example.com', 'dest2@example.com']
# end
#
# === Errors
#
# This method may raise:
#
# * Net::SMTPServerBusy
# * Net::SMTPSyntaxError
# * Net::SMTPFatalError
# * Net::SMTPUnknownError
# * IOError
# * TimeoutError
#
def send_message(msgstr, from_addr, *to_addrs)
raise IOError, 'closed session' unless @socket
mailfrom from_addr
rcptto_list to_addrs
data msgstr
end
alias send_mail send_message
alias sendmail send_message # obsolete
#
# Opens a message writer stream and gives it to the block.
# The stream is valid only in the block, and has these methods:
#
# puts(str = ''):: outputs STR and CR LF.
# print(str):: outputs STR.
# printf(fmt, *args):: outputs sprintf(fmt,*args).
# write(str):: outputs STR and returns the length of written bytes.
# <<(str):: outputs STR and returns self.
#
# If a single CR ("\r") or LF ("\n") is found in the message,
# it is converted to the CR LF pair. You cannot send a binary
# message with this method.
#
# === Parameters
#
# +from_addr+ is a String representing the source mail address.
#
# +to_addr+ is a String or Strings or Array of Strings, representing
# the destination mail address or addresses.
#
# === Example
#
# Net::SMTP.start('smtp.example.com', 25) do |smtp|
# smtp.open_message_stream('from@example.com', ['dest@example.com']) do |f|
# f.puts 'From: from@example.com'
# f.puts 'To: dest@example.com'
# f.puts 'Subject: test message'
# f.puts
# f.puts 'This is a test message.'
# end
# end
#
# === Errors
#
# This method may raise:
#
# * Net::SMTPServerBusy
# * Net::SMTPSyntaxError
# * Net::SMTPFatalError
# * Net::SMTPUnknownError
# * IOError
# * TimeoutError
#
def open_message_stream(from_addr, *to_addrs, &block) # :yield: stream
raise IOError, 'closed session' unless @socket
mailfrom from_addr
rcptto_list to_addrs
data(&block)
end
alias ready open_message_stream # obsolete
#
# Authentication
#
public
DEFAULT_AUTH_TYPE = :plain
def authenticate(user, secret, authtype = DEFAULT_AUTH_TYPE)
check_auth_method authtype
check_auth_args user, secret
send auth_method(authtype), user, secret
end
def auth_plain(user, secret)
check_auth_args user, secret
res = critical {
get_response('AUTH PLAIN ' + base64_encode("\0#{user}\0#{secret}"))
}
check_auth_response res
res
end
def auth_login(user, secret)
check_auth_args user, secret
res = critical {
check_auth_continue get_response('AUTH LOGIN')
check_auth_continue get_response(base64_encode(user))
get_response(base64_encode(secret))
}
check_auth_response res
res
end
def auth_cram_md5(user, secret)
check_auth_args user, secret
res = critical {
res0 = get_response('AUTH CRAM-MD5')
check_auth_continue res0
crammed = cram_md5_response(secret, res0.cram_md5_challenge)
get_response(base64_encode("#{user} #{crammed}"))
}
check_auth_response res
res
end
private
def check_auth_method(type)
unless respond_to?(auth_method(type), true)
raise ArgumentError, "wrong authentication type #{type}"
end
end
def auth_method(type)
"auth_#{type.to_s.downcase}".intern
end
def check_auth_args(user, secret)
unless user
raise ArgumentError, 'SMTP-AUTH requested but missing user name'
end
unless secret
raise ArgumentError, 'SMTP-AUTH requested but missing secret phrase'
end
end
def base64_encode(str)
# expects "str" may not become too long
[str].pack('m').gsub(/\s+/, '')
end
IMASK = 0x36
OMASK = 0x5c
# CRAM-MD5: [RFC2195]
def cram_md5_response(secret, challenge)
tmp = Digest::MD5.digest(cram_secret(secret, IMASK) + challenge)
Digest::MD5.hexdigest(cram_secret(secret, OMASK) + tmp)
end
CRAM_BUFSIZE = 64
def cram_secret(secret, mask)
secret = Digest::MD5.digest(secret) if secret.size > CRAM_BUFSIZE
buf = secret.ljust(CRAM_BUFSIZE, "\0")
0.upto(buf.size - 1) do |i|
buf[i] = (buf[i].ord ^ mask).chr
end
buf
end
#
# SMTP command dispatcher
#
public
def starttls
getok('STARTTLS')
end
def helo(domain)
getok("HELO #{domain}")
end
def ehlo(domain)
getok("EHLO #{domain}")
end
def mailfrom(from_addr)
if $SAFE > 0
raise SecurityError, 'tainted from_addr' if from_addr.tainted?
end
getok("MAIL FROM:<#{from_addr}>")
end
def rcptto_list(to_addrs)
raise ArgumentError, 'mail destination not given' if to_addrs.empty?
to_addrs.flatten.each do |addr|
rcptto addr
end
end
def rcptto(to_addr)
if $SAFE > 0
raise SecurityError, 'tainted to_addr' if to_addr.tainted?
end
getok("RCPT TO:<#{to_addr}>")
end
# This method sends a message.
# If +msgstr+ is given, sends it as a message.
# If block is given, yield a message writer stream.
# You must write message before the block is closed.
#
# # Example 1 (by string)
# smtp.data(<<EndMessage)
# From: john@example.com
# To: betty@example.com
# Subject: I found a bug
#
# Check vm.c:58879.
# EndMessage
#
# # Example 2 (by block)
# smtp.data {|f|
# f.puts "From: john@example.com"
# f.puts "To: betty@example.com"
# f.puts "Subject: I found a bug"
# f.puts ""
# f.puts "Check vm.c:58879."
# }
#
def data(msgstr = nil, &block) #:yield: stream
if msgstr and block
raise ArgumentError, "message and block are exclusive"
end
unless msgstr or block
raise ArgumentError, "message or block is required"
end
res = critical {
check_continue get_response('DATA')
if msgstr
@socket.write_message msgstr
else
@socket.write_message_by_block(&block)
end
recv_response()
}
check_response res
res
end
def quit
getok('QUIT')
end
private
def getok(reqline)
res = critical {
@socket.writeline reqline
recv_response()
}
check_response res
res
end
def get_response(reqline)
@socket.writeline reqline
recv_response()
end
def recv_response
buf = ''
while true
line = @socket.readline
buf << line << "\n"
break unless line[3,1] == '-' # "210-PIPELINING"
end
Response.parse(buf)
end
def critical(&block)
return '200 dummy reply code' if @error_occured
begin
return yield()
rescue Exception
@error_occured = true
raise
end
end
def check_response(res)
unless res.success?
raise res.exception_class, res.message
end
end
def check_continue(res)
unless res.continue?
raise SMTPUnknownError, "could not get 3xx (#{res.status})"
end
end
def check_auth_response(res)
unless res.success?
raise SMTPAuthenticationError, res.message
end
end
def check_auth_continue(res)
unless res.continue?
raise res.exception_class, res.message
end
end
class Response
def Response.parse(str)
new(str[0,3], str)
end
def initialize(status, string)
@status = status
@string = string
end
attr_reader :status
attr_reader :string
def status_type_char
@status[0, 1]
end
def success?
status_type_char() == '2'
end
def continue?
status_type_char() == '3'
end
def message
@string.lines.first
end
def cram_md5_challenge
@string.split(/ /)[1].unpack('m')[0]
end
def capabilities
return {} unless @string[3, 1] == '-'
h = {}
@string.lines.drop(1).each do |line|
k, *v = line[4..-1].chomp.split(nil)
h[k] = v
end
h
end
def exception_class
case @status
when /\A4/ then SMTPServerBusy
when /\A50/ then SMTPSyntaxError
when /\A53/ then SMTPAuthenticationError
when /\A5/ then SMTPFatalError
else SMTPUnknownError
end
end
end
def logging(msg)
@debug_output << msg + "\n" if @debug_output
end
end # class SMTP
SMTPSession = SMTP
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/net/protocol.rb | tools/jruby-1.5.1/lib/ruby/1.8/net/protocol.rb | #
# = net/protocol.rb
#
#--
# Copyright (c) 1999-2005 Yukihiro Matsumoto
# Copyright (c) 1999-2005 Minero Aoki
#
# written and maintained by Minero Aoki <aamine@loveruby.net>
#
# This program is free software. You can re-distribute and/or
# modify this program under the same terms as Ruby itself,
# Ruby Distribute License or GNU General Public License.
#
# $Id: protocol.rb 12092 2007-03-19 02:39:22Z aamine $
#++
#
# WARNING: This file is going to remove.
# Do not rely on the implementation written in this file.
#
require 'socket'
require 'timeout'
module Net # :nodoc:
class Protocol #:nodoc: internal use only
private
def Protocol.protocol_param(name, val)
module_eval(<<-End, __FILE__, __LINE__ + 1)
def #{name}
#{val}
end
End
end
end
class ProtocolError < StandardError; end
class ProtoSyntaxError < ProtocolError; end
class ProtoFatalError < ProtocolError; end
class ProtoUnknownError < ProtocolError; end
class ProtoServerError < ProtocolError; end
class ProtoAuthError < ProtocolError; end
class ProtoCommandError < ProtocolError; end
class ProtoRetriableError < ProtocolError; end
ProtocRetryError = ProtoRetriableError
class BufferedIO #:nodoc: internal use only
def initialize(io)
@io = io
@read_timeout = 60
@debug_output = nil
@rbuf = ''
end
attr_reader :io
attr_accessor :read_timeout
attr_accessor :debug_output
def inspect
"#<#{self.class} io=#{@io}>"
end
def closed?
@io.closed?
end
def close
@io.close
end
#
# Read
#
public
def read(len, dest = '', ignore_eof = false)
LOG "reading #{len} bytes..."
read_bytes = 0
begin
while read_bytes + @rbuf.size < len
dest << (s = rbuf_consume(@rbuf.size))
read_bytes += s.size
rbuf_fill
end
dest << (s = rbuf_consume(len - read_bytes))
read_bytes += s.size
rescue EOFError
raise unless ignore_eof
end
LOG "read #{read_bytes} bytes"
dest
end
def read_all(dest = '')
LOG 'reading all...'
read_bytes = 0
begin
while true
dest << (s = rbuf_consume(@rbuf.size))
read_bytes += s.size
rbuf_fill
end
rescue EOFError
;
end
LOG "read #{read_bytes} bytes"
dest
end
def readuntil(terminator, ignore_eof = false)
begin
until idx = @rbuf.index(terminator)
rbuf_fill
end
return rbuf_consume(idx + terminator.size)
rescue EOFError
raise unless ignore_eof
return rbuf_consume(@rbuf.size)
end
end
def readline
readuntil("\n").chop
end
private
BUFSIZE = 1024 * 16
def rbuf_fill
timeout(@read_timeout) {
@rbuf << @io.sysread(BUFSIZE)
}
end
def rbuf_consume(len)
s = @rbuf.slice!(0, len)
@debug_output << %Q[-> #{s.dump}\n] if @debug_output
s
end
#
# Write
#
public
def write(str)
writing {
write0 str
}
end
def writeline(str)
writing {
write0 str + "\r\n"
}
end
private
def writing
@written_bytes = 0
@debug_output << '<- ' if @debug_output
yield
@debug_output << "\n" if @debug_output
bytes = @written_bytes
@written_bytes = nil
bytes
end
def write0(str)
@debug_output << str.dump if @debug_output
len = @io.write(str)
@written_bytes += len
len
end
#
# Logging
#
private
def LOG_off
@save_debug_out = @debug_output
@debug_output = nil
end
def LOG_on
@debug_output = @save_debug_out
end
def LOG(msg)
return unless @debug_output
@debug_output << msg + "\n"
end
end
class InternetMessageIO < BufferedIO #:nodoc: internal use only
def InternetMessageIO.old_open(addr, port,
open_timeout = nil, read_timeout = nil, debug_output = nil)
debug_output << "opening connection to #{addr}...\n" if debug_output
s = timeout(open_timeout) { TCPsocket.new(addr, port) }
io = new(s)
io.read_timeout = read_timeout
io.debug_output = debug_output
io
end
def initialize(io)
super
@wbuf = nil
end
#
# Read
#
def each_message_chunk
LOG 'reading message...'
LOG_off()
read_bytes = 0
while (line = readuntil("\r\n")) != ".\r\n"
read_bytes += line.size
yield line.sub(/\A\./, '')
end
LOG_on()
LOG "read message (#{read_bytes} bytes)"
end
# *library private* (cannot handle 'break')
def each_list_item
while (str = readuntil("\r\n")) != ".\r\n"
yield str.chop
end
end
def write_message_0(src)
prev = @written_bytes
each_crlf_line(src) do |line|
write0 line.sub(/\A\./, '..')
end
@written_bytes - prev
end
#
# Write
#
def write_message(src)
LOG "writing message from #{src.class}"
LOG_off()
len = writing {
using_each_crlf_line {
write_message_0 src
}
}
LOG_on()
LOG "wrote #{len} bytes"
len
end
def write_message_by_block(&block)
LOG 'writing message from block'
LOG_off()
len = writing {
using_each_crlf_line {
begin
block.call(WriteAdapter.new(self, :write_message_0))
rescue LocalJumpError
# allow `break' from writer block
end
}
}
LOG_on()
LOG "wrote #{len} bytes"
len
end
private
def using_each_crlf_line
@wbuf = ''
yield
if not @wbuf.empty? # unterminated last line
write0 @wbuf.chomp + "\r\n"
elsif @written_bytes == 0 # empty src
write0 "\r\n"
end
write0 ".\r\n"
@wbuf = nil
end
def each_crlf_line(src)
buffer_filling(@wbuf, src) do
while line = @wbuf.slice!(/\A.*(?:\n|\r\n|\r(?!\z))/n)
yield line.chomp("\n") + "\r\n"
end
end
end
def buffer_filling(buf, src)
case src
when String # for speeding up.
0.step(src.size - 1, 1024) do |i|
buf << src[i, 1024]
yield
end
when File # for speeding up.
while s = src.read(1024)
buf << s
yield
end
else # generic reader
src.each do |s|
buf << s
yield if buf.size > 1024
end
yield unless buf.empty?
end
end
end
#
# The writer adapter class
#
class WriteAdapter
def initialize(socket, method)
@socket = socket
@method_id = method
end
def inspect
"#<#{self.class} socket=#{@socket.inspect}>"
end
def write(str)
@socket.__send__(@method_id, str)
end
alias print write
def <<(str)
write str
self
end
def puts(str = '')
write str.chomp("\n") + "\n"
end
def printf(*args)
write sprintf(*args)
end
end
class ReadAdapter #:nodoc: internal use only
def initialize(block)
@block = block
end
def inspect
"#<#{self.class}>"
end
def <<(str)
call_block(str, &@block) if @block
end
private
# This method is needed because @block must be called by yield,
# not Proc#call. You can see difference when using `break' in
# the block.
def call_block(str)
yield str
end
end
module NetPrivate #:nodoc: obsolete
Socket = ::Net::InternetMessageIO
end
end # module Net
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/net/pop.rb | tools/jruby-1.5.1/lib/ruby/1.8/net/pop.rb | # = net/pop.rb
#
# Copyright (c) 1999-2007 Yukihiro Matsumoto.
#
# Copyright (c) 1999-2007 Minero Aoki.
#
# Written & maintained by Minero Aoki <aamine@loveruby.net>.
#
# Documented by William Webber and Minero Aoki.
#
# This program is free software. You can re-distribute and/or
# modify this program under the same terms as Ruby itself,
# Ruby Distribute License.
#
# NOTE: You can find Japanese version of this document at:
# http://www.ruby-lang.org/ja/man/html/net_pop.html
#
# $Id: pop.rb 22002 2009-02-03 05:35:56Z shyouhei $
#
# See Net::POP3 for documentation.
#
require 'net/protocol'
require 'digest/md5'
require 'timeout'
begin
require "openssl/ssl"
rescue LoadError
end
module Net
# Non-authentication POP3 protocol error
# (reply code "-ERR", except authentication).
class POPError < ProtocolError; end
# POP3 authentication error.
class POPAuthenticationError < ProtoAuthError; end
# Unexpected response from the server.
class POPBadResponse < POPError; end
#
# = Net::POP3
#
# == What is This Library?
#
# This library provides functionality for retrieving
# email via POP3, the Post Office Protocol version 3. For details
# of POP3, see [RFC1939] (http://www.ietf.org/rfc/rfc1939.txt).
#
# == Examples
#
# === Retrieving Messages
#
# This example retrieves messages from the server and deletes them
# on the server.
#
# Messages are written to files named 'inbox/1', 'inbox/2', ....
# Replace 'pop.example.com' with your POP3 server address, and
# 'YourAccount' and 'YourPassword' with the appropriate account
# details.
#
# require 'net/pop'
#
# pop = Net::POP3.new('pop.example.com')
# pop.start('YourAccount', 'YourPassword') # (1)
# if pop.mails.empty?
# puts 'No mail.'
# else
# i = 0
# pop.each_mail do |m| # or "pop.mails.each ..." # (2)
# File.open("inbox/#{i}", 'w') do |f|
# f.write m.pop
# end
# m.delete
# i += 1
# end
# puts "#{pop.mails.size} mails popped."
# end
# pop.finish # (3)
#
# 1. Call Net::POP3#start and start POP session.
# 2. Access messages by using POP3#each_mail and/or POP3#mails.
# 3. Close POP session by calling POP3#finish or use the block form of #start.
#
# === Shortened Code
#
# The example above is very verbose. You can shorten the code by using
# some utility methods. First, the block form of Net::POP3.start can
# be used instead of POP3.new, POP3#start and POP3#finish.
#
# require 'net/pop'
#
# Net::POP3.start('pop.example.com', 110,
# 'YourAccount', 'YourPassword') do |pop|
# if pop.mails.empty?
# puts 'No mail.'
# else
# i = 0
# pop.each_mail do |m| # or "pop.mails.each ..."
# File.open("inbox/#{i}", 'w') do |f|
# f.write m.pop
# end
# m.delete
# i += 1
# end
# puts "#{pop.mails.size} mails popped."
# end
# end
#
# POP3#delete_all is an alternative for #each_mail and #delete.
#
# require 'net/pop'
#
# Net::POP3.start('pop.example.com', 110,
# 'YourAccount', 'YourPassword') do |pop|
# if pop.mails.empty?
# puts 'No mail.'
# else
# i = 1
# pop.delete_all do |m|
# File.open("inbox/#{i}", 'w') do |f|
# f.write m.pop
# end
# i += 1
# end
# end
# end
#
# And here is an even shorter example.
#
# require 'net/pop'
#
# i = 0
# Net::POP3.delete_all('pop.example.com', 110,
# 'YourAccount', 'YourPassword') do |m|
# File.open("inbox/#{i}", 'w') do |f|
# f.write m.pop
# end
# i += 1
# end
#
# === Memory Space Issues
#
# All the examples above get each message as one big string.
# This example avoids this.
#
# require 'net/pop'
#
# i = 1
# Net::POP3.delete_all('pop.example.com', 110,
# 'YourAccount', 'YourPassword') do |m|
# File.open("inbox/#{i}", 'w') do |f|
# m.pop do |chunk| # get a message little by little.
# f.write chunk
# end
# i += 1
# end
# end
#
# === Using APOP
#
# The net/pop library supports APOP authentication.
# To use APOP, use the Net::APOP class instead of the Net::POP3 class.
# You can use the utility method, Net::POP3.APOP(). For example:
#
# require 'net/pop'
#
# # Use APOP authentication if $isapop == true
# pop = Net::POP3.APOP($is_apop).new('apop.example.com', 110)
# pop.start(YourAccount', 'YourPassword') do |pop|
# # Rest of the code is the same.
# end
#
# === Fetch Only Selected Mail Using 'UIDL' POP Command
#
# If your POP server provides UIDL functionality,
# you can grab only selected mails from the POP server.
# e.g.
#
# def need_pop?( id )
# # determine if we need pop this mail...
# end
#
# Net::POP3.start('pop.example.com', 110,
# 'Your account', 'Your password') do |pop|
# pop.mails.select { |m| need_pop?(m.unique_id) }.each do |m|
# do_something(m.pop)
# end
# end
#
# The POPMail#unique_id() method returns the unique-id of the message as a
# String. Normally the unique-id is a hash of the message.
#
class POP3 < Protocol
Revision = %q$Revision: 22002 $.split[1]
#
# Class Parameters
#
def POP3.default_port
default_pop3_port()
end
# The default port for POP3 connections, port 110
def POP3.default_pop3_port
110
end
# The default port for POP3S connections, port 995
def POP3.default_pop3s_port
995
end
def POP3.socket_type #:nodoc: obsolete
Net::InternetMessageIO
end
#
# Utilities
#
# Returns the APOP class if +isapop+ is true; otherwise, returns
# the POP class. For example:
#
# # Example 1
# pop = Net::POP3::APOP($is_apop).new(addr, port)
#
# # Example 2
# Net::POP3::APOP($is_apop).start(addr, port) do |pop|
# ....
# end
#
def POP3.APOP(isapop)
isapop ? APOP : POP3
end
# Starts a POP3 session and iterates over each POPMail object,
# yielding it to the +block+.
# This method is equivalent to:
#
# Net::POP3.start(address, port, account, password) do |pop|
# pop.each_mail do |m|
# yield m
# end
# end
#
# This method raises a POPAuthenticationError if authentication fails.
#
# === Example
#
# Net::POP3.foreach('pop.example.com', 110,
# 'YourAccount', 'YourPassword') do |m|
# file.write m.pop
# m.delete if $DELETE
# end
#
def POP3.foreach(address, port = nil,
account = nil, password = nil,
isapop = false, &block) # :yields: message
start(address, port, account, password, isapop) {|pop|
pop.each_mail(&block)
}
end
# Starts a POP3 session and deletes all messages on the server.
# If a block is given, each POPMail object is yielded to it before
# being deleted.
#
# This method raises a POPAuthenticationError if authentication fails.
#
# === Example
#
# Net::POP3.delete_all('pop.example.com', 110,
# 'YourAccount', 'YourPassword') do |m|
# file.write m.pop
# end
#
def POP3.delete_all(address, port = nil,
account = nil, password = nil,
isapop = false, &block)
start(address, port, account, password, isapop) {|pop|
pop.delete_all(&block)
}
end
# Opens a POP3 session, attempts authentication, and quits.
#
# This method raises POPAuthenticationError if authentication fails.
#
# === Example: normal POP3
#
# Net::POP3.auth_only('pop.example.com', 110,
# 'YourAccount', 'YourPassword')
#
# === Example: APOP
#
# Net::POP3.auth_only('pop.example.com', 110,
# 'YourAccount', 'YourPassword', true)
#
def POP3.auth_only(address, port = nil,
account = nil, password = nil,
isapop = false)
new(address, port, isapop).auth_only account, password
end
# Starts a pop3 session, attempts authentication, and quits.
# This method must not be called while POP3 session is opened.
# This method raises POPAuthenticationError if authentication fails.
def auth_only(account, password)
raise IOError, 'opening previously opened POP session' if started?
start(account, password) {
;
}
end
#
# SSL
#
@ssl_params = nil
# call-seq:
# Net::POP.enable_ssl(params = {})
#
# Enable SSL for all new instances.
# +params+ is passed to OpenSSL::SSLContext#set_params.
def POP3.enable_ssl(*args)
@ssl_params = create_ssl_params(*args)
end
def POP3.create_ssl_params(verify_or_params = {}, certs = nil)
begin
params = verify_or_params.to_hash
rescue NoMethodError
params = {}
params[:verify_mode] = verify_or_params
if certs
if File.file?(certs)
params[:ca_file] = certs
elsif File.directory?(certs)
params[:ca_path] = certs
end
end
end
return params
end
# Disable SSL for all new instances.
def POP3.disable_ssl
@ssl_params = nil
end
def POP3.ssl_params
return @ssl_params
end
def POP3.use_ssl?
return !@ssl_params.nil?
end
def POP3.verify
return @ssl_params[:verify_mode]
end
def POP3.certs
return @ssl_params[:ca_file] || @ssl_params[:ca_path]
end
#
# Session management
#
# Creates a new POP3 object and open the connection. Equivalent to
#
# Net::POP3.new(address, port, isapop).start(account, password)
#
# If +block+ is provided, yields the newly-opened POP3 object to it,
# and automatically closes it at the end of the session.
#
# === Example
#
# Net::POP3.start(addr, port, account, password) do |pop|
# pop.each_mail do |m|
# file.write m.pop
# m.delete
# end
# end
#
def POP3.start(address, port = nil,
account = nil, password = nil,
isapop = false, &block) # :yield: pop
new(address, port, isapop).start(account, password, &block)
end
# Creates a new POP3 object.
#
# +address+ is the hostname or ip address of your POP3 server.
#
# The optional +port+ is the port to connect to.
#
# The optional +isapop+ specifies whether this connection is going
# to use APOP authentication; it defaults to +false+.
#
# This method does *not* open the TCP connection.
def initialize(addr, port = nil, isapop = false)
@address = addr
@ssl_params = POP3.ssl_params
@port = port
@apop = isapop
@command = nil
@socket = nil
@started = false
@open_timeout = 30
@read_timeout = 60
@debug_output = nil
@mails = nil
@n_mails = nil
@n_bytes = nil
end
# Does this instance use APOP authentication?
def apop?
@apop
end
# does this instance use SSL?
def use_ssl?
return !@ssl_params.nil?
end
# call-seq:
# Net::POP#enable_ssl(params = {})
#
# Enables SSL for this instance. Must be called before the connection is
# established to have any effect.
# +params[:port]+ is port to establish the SSL connection on; Defaults to 995.
# +params+ (except :port) is passed to OpenSSL::SSLContext#set_params.
def enable_ssl(verify_or_params = {}, certs = nil, port = nil)
begin
@ssl_params = verify_or_params.to_hash.dup
@port = @ssl_params.delete(:port) || @port
rescue NoMethodError
@ssl_params = POP3.create_ssl_params(verify_or_params, certs)
@port = port || @port
end
end
def disable_ssl
@ssl_params = nil
end
# Provide human-readable stringification of class state.
def inspect
"#<#{self.class} #{@address}:#{@port} open=#{@started}>"
end
# *WARNING*: This method causes a serious security hole.
# Use this method only for debugging.
#
# Set an output stream for debugging.
#
# === Example
#
# pop = Net::POP.new(addr, port)
# pop.set_debug_output $stderr
# pop.start(account, passwd) do |pop|
# ....
# end
#
def set_debug_output(arg)
@debug_output = arg
end
# The address to connect to.
attr_reader :address
# The port number to connect to.
def port
return @port || (use_ssl? ? POP3.default_pop3s_port : POP3.default_pop3_port)
end
# Seconds to wait until a connection is opened.
# If the POP3 object cannot open a connection within this time,
# it raises a TimeoutError exception.
attr_accessor :open_timeout
# Seconds to wait until reading one block (by one read(1) call).
# If the POP3 object cannot complete a read() within this time,
# it raises a TimeoutError exception.
attr_reader :read_timeout
# Set the read timeout.
def read_timeout=(sec)
@command.socket.read_timeout = sec if @command
@read_timeout = sec
end
# +true+ if the POP3 session has started.
def started?
@started
end
alias active? started? #:nodoc: obsolete
# Starts a POP3 session.
#
# When called with block, gives a POP3 object to the block and
# closes the session after block call finishes.
#
# This method raises a POPAuthenticationError if authentication fails.
def start(account, password) # :yield: pop
raise IOError, 'POP session already started' if @started
if block_given?
begin
do_start account, password
return yield(self)
ensure
do_finish
end
else
do_start account, password
return self
end
end
def do_start(account, password)
s = timeout(@open_timeout) { TCPSocket.open(@address, port) }
if use_ssl?
raise 'openssl library not installed' unless defined?(OpenSSL)
context = OpenSSL::SSL::SSLContext.new
context.set_params(@ssl_params)
s = OpenSSL::SSL::SSLSocket.new(s, context)
s.sync_close = true
s.connect
if context.verify_mode != OpenSSL::SSL::VERIFY_NONE
s.post_connection_check(@address)
end
end
@socket = InternetMessageIO.new(s)
logging "POP session started: #{@address}:#{@port} (#{@apop ? 'APOP' : 'POP'})"
@socket.read_timeout = @read_timeout
@socket.debug_output = @debug_output
on_connect
@command = POP3Command.new(@socket)
if apop?
@command.apop account, password
else
@command.auth account, password
end
@started = true
ensure
# Authentication failed, clean up connection.
unless @started
s.close if s and not s.closed?
@socket = nil
@command = nil
end
end
private :do_start
def on_connect
end
private :on_connect
# Finishes a POP3 session and closes TCP connection.
def finish
raise IOError, 'POP session not yet started' unless started?
do_finish
end
def do_finish
@mails = nil
@n_mails = nil
@n_bytes = nil
@command.quit if @command
ensure
@started = false
@command = nil
@socket.close if @socket and not @socket.closed?
@socket = nil
end
private :do_finish
def command
raise IOError, 'POP session not opened yet' \
if not @socket or @socket.closed?
@command
end
private :command
#
# POP protocol wrapper
#
# Returns the number of messages on the POP server.
def n_mails
return @n_mails if @n_mails
@n_mails, @n_bytes = command().stat
@n_mails
end
# Returns the total size in bytes of all the messages on the POP server.
def n_bytes
return @n_bytes if @n_bytes
@n_mails, @n_bytes = command().stat
@n_bytes
end
# Returns an array of Net::POPMail objects, representing all the
# messages on the server. This array is renewed when the session
# restarts; otherwise, it is fetched from the server the first time
# this method is called (directly or indirectly) and cached.
#
# This method raises a POPError if an error occurs.
def mails
return @mails.dup if @mails
if n_mails() == 0
# some popd raises error for LIST on the empty mailbox.
@mails = []
return []
end
@mails = command().list.map {|num, size|
POPMail.new(num, size, self, command())
}
@mails.dup
end
# Yields each message to the passed-in block in turn.
# Equivalent to:
#
# pop3.mails.each do |popmail|
# ....
# end
#
# This method raises a POPError if an error occurs.
def each_mail(&block) # :yield: message
mails().each(&block)
end
alias each each_mail
# Deletes all messages on the server.
#
# If called with a block, yields each message in turn before deleting it.
#
# === Example
#
# n = 1
# pop.delete_all do |m|
# File.open("inbox/#{n}") do |f|
# f.write m.pop
# end
# n += 1
# end
#
# This method raises a POPError if an error occurs.
#
def delete_all # :yield: message
mails().each do |m|
yield m if block_given?
m.delete unless m.deleted?
end
end
# Resets the session. This clears all "deleted" marks from messages.
#
# This method raises a POPError if an error occurs.
def reset
command().rset
mails().each do |m|
m.instance_eval {
@deleted = false
}
end
end
def set_all_uids #:nodoc: internal use only (called from POPMail#uidl)
command().uidl.each do |num, uid|
@mails.find {|m| m.number == num }.uid = uid
end
end
def logging(msg)
@debug_output << msg + "\n" if @debug_output
end
end # class POP3
# class aliases
POP = POP3
POPSession = POP3
POP3Session = POP3
#
# This class is equivalent to POP3, except that it uses APOP authentication.
#
class APOP < POP3
# Always returns true.
def apop?
true
end
end
# class aliases
APOPSession = APOP
#
# This class represents a message which exists on the POP server.
# Instances of this class are created by the POP3 class; they should
# not be directly created by the user.
#
class POPMail
def initialize(num, len, pop, cmd) #:nodoc:
@number = num
@length = len
@pop = pop
@command = cmd
@deleted = false
@uid = nil
end
# The sequence number of the message on the server.
attr_reader :number
# The length of the message in octets.
attr_reader :length
alias size length
# Provide human-readable stringification of class state.
def inspect
"#<#{self.class} #{@number}#{@deleted ? ' deleted' : ''}>"
end
#
# This method fetches the message. If called with a block, the
# message is yielded to the block one chunk at a time. If called
# without a block, the message is returned as a String. The optional
# +dest+ argument will be prepended to the returned String; this
# argument is essentially obsolete.
#
# === Example without block
#
# POP3.start('pop.example.com', 110,
# 'YourAccount, 'YourPassword') do |pop|
# n = 1
# pop.mails.each do |popmail|
# File.open("inbox/#{n}", 'w') do |f|
# f.write popmail.pop
# end
# popmail.delete
# n += 1
# end
# end
#
# === Example with block
#
# POP3.start('pop.example.com', 110,
# 'YourAccount, 'YourPassword') do |pop|
# n = 1
# pop.mails.each do |popmail|
# File.open("inbox/#{n}", 'w') do |f|
# popmail.pop do |chunk| ####
# f.write chunk
# end
# end
# n += 1
# end
# end
#
# This method raises a POPError if an error occurs.
#
def pop( dest = '', &block ) # :yield: message_chunk
if block_given?
@command.retr(@number, &block)
nil
else
@command.retr(@number) do |chunk|
dest << chunk
end
dest
end
end
alias all pop #:nodoc: obsolete
alias mail pop #:nodoc: obsolete
# Fetches the message header and +lines+ lines of body.
#
# The optional +dest+ argument is obsolete.
#
# This method raises a POPError if an error occurs.
def top(lines, dest = '')
@command.top(@number, lines) do |chunk|
dest << chunk
end
dest
end
# Fetches the message header.
#
# The optional +dest+ argument is obsolete.
#
# This method raises a POPError if an error occurs.
def header(dest = '')
top(0, dest)
end
# Marks a message for deletion on the server. Deletion does not
# actually occur until the end of the session; deletion may be
# cancelled for _all_ marked messages by calling POP3#reset().
#
# This method raises a POPError if an error occurs.
#
# === Example
#
# POP3.start('pop.example.com', 110,
# 'YourAccount, 'YourPassword') do |pop|
# n = 1
# pop.mails.each do |popmail|
# File.open("inbox/#{n}", 'w') do |f|
# f.write popmail.pop
# end
# popmail.delete ####
# n += 1
# end
# end
#
def delete
@command.dele @number
@deleted = true
end
alias delete! delete #:nodoc: obsolete
# True if the mail has been deleted.
def deleted?
@deleted
end
# Returns the unique-id of the message.
# Normally the unique-id is a hash string of the message.
#
# This method raises a POPError if an error occurs.
def unique_id
return @uid if @uid
@pop.set_all_uids
@uid
end
alias uidl unique_id
def uid=(uid) #:nodoc: internal use only
@uid = uid
end
end # class POPMail
class POP3Command #:nodoc: internal use only
def initialize(sock)
@socket = sock
@error_occured = false
res = check_response(critical { recv_response() })
@apop_stamp = res.slice(/<[!-~]+@[!-~]+>/)
end
def inspect
"#<#{self.class} socket=#{@socket}>"
end
def auth(account, password)
check_response_auth(critical {
check_response_auth(get_response('USER %s', account))
get_response('PASS %s', password)
})
end
def apop(account, password)
raise POPAuthenticationError, 'not APOP server; cannot login' \
unless @apop_stamp
check_response_auth(critical {
get_response('APOP %s %s',
account,
Digest::MD5.hexdigest(@apop_stamp + password))
})
end
def list
critical {
getok 'LIST'
list = []
@socket.each_list_item do |line|
m = /\A(\d+)[ \t]+(\d+)/.match(line) or
raise POPBadResponse, "bad response: #{line}"
list.push [m[1].to_i, m[2].to_i]
end
return list
}
end
def stat
res = check_response(critical { get_response('STAT') })
m = /\A\+OK\s+(\d+)\s+(\d+)/.match(res) or
raise POPBadResponse, "wrong response format: #{res}"
[m[1].to_i, m[2].to_i]
end
def rset
check_response(critical { get_response('RSET') })
end
def top(num, lines = 0, &block)
critical {
getok('TOP %d %d', num, lines)
@socket.each_message_chunk(&block)
}
end
def retr(num, &block)
critical {
getok('RETR %d', num)
@socket.each_message_chunk(&block)
}
end
def dele(num)
check_response(critical { get_response('DELE %d', num) })
end
def uidl(num = nil)
if num
res = check_response(critical { get_response('UIDL %d', num) })
return res.split(/ /)[1]
else
critical {
getok('UIDL')
table = {}
@socket.each_list_item do |line|
num, uid = line.split
table[num.to_i] = uid
end
return table
}
end
end
def quit
check_response(critical { get_response('QUIT') })
end
private
def getok(fmt, *fargs)
@socket.writeline sprintf(fmt, *fargs)
check_response(recv_response())
end
def get_response(fmt, *fargs)
@socket.writeline sprintf(fmt, *fargs)
recv_response()
end
def recv_response
@socket.readline
end
def check_response(res)
raise POPError, res unless /\A\+OK/i =~ res
res
end
def check_response_auth(res)
raise POPAuthenticationError, res unless /\A\+OK/i =~ res
res
end
def critical
return '+OK dummy ok response' if @error_occured
begin
return yield()
rescue Exception
@error_occured = true
raise
end
end
end # class POP3Command
end # module Net
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/net/https.rb | tools/jruby-1.5.1/lib/ruby/1.8/net/https.rb | =begin
= $RCSfile$ -- SSL/TLS enhancement for Net::HTTP.
== Info
'OpenSSL for Ruby 2' project
Copyright (C) 2001 GOTOU Yuuzou <gotoyuzo@notwork.org>
All rights reserved.
== Licence
This program is licenced under the same licence as Ruby.
(See the file 'LICENCE'.)
== Requirements
This program requires Net 1.2.0 or higher version.
You can get it from RAA or Ruby's CVS repository.
== Version
$Id: https.rb 16857 2008-06-06 08:05:24Z knu $
2001-11-06: Contiributed to Ruby/OpenSSL project.
2004-03-06: Some code is merged in to net/http.
== Example
Here is a simple HTTP client:
require 'net/http'
require 'uri'
uri = URI.parse(ARGV[0] || 'http://localhost/')
http = Net::HTTP.new(uri.host, uri.port)
http.start {
http.request_get(uri.path) {|res|
print res.body
}
}
It can be replaced by the following code:
require 'net/https'
require 'uri'
uri = URI.parse(ARGV[0] || 'https://localhost/')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true if uri.scheme == "https" # enable SSL/TLS
http.start {
http.request_get(uri.path) {|res|
print res.body
}
}
== class Net::HTTP
=== Instance Methods
: use_ssl?
returns true if use SSL/TLS with HTTP.
: use_ssl=((|true_or_false|))
sets use_ssl.
: peer_cert
return the X.509 certificates the server presented.
: key, key=((|key|))
Sets an OpenSSL::PKey::RSA or OpenSSL::PKey::DSA object.
(This method is appeared in Michal Rokos's OpenSSL extension.)
: cert, cert=((|cert|))
Sets an OpenSSL::X509::Certificate object as client certificate
(This method is appeared in Michal Rokos's OpenSSL extension).
: ca_file, ca_file=((|path|))
Sets path of a CA certification file in PEM format.
The file can contrain several CA certificats.
: ca_path, ca_path=((|path|))
Sets path of a CA certification directory containing certifications
in PEM format.
: verify_mode, verify_mode=((|mode|))
Sets the flags for server the certification verification at
begining of SSL/TLS session.
OpenSSL::SSL::VERIFY_NONE or OpenSSL::SSL::VERIFY_PEER is acceptable.
: verify_callback, verify_callback=((|proc|))
Sets the verify callback for the server certification verification.
: verify_depth, verify_depth=((|num|))
Sets the maximum depth for the certificate chain verification.
: cert_store, cert_store=((|store|))
Sets the X509::Store to verify peer certificate.
: ssl_timeout, ssl_timeout=((|sec|))
Sets the SSL timeout seconds.
=end
require 'net/http'
require 'openssl'
module Net
class HTTP
remove_method :use_ssl?
def use_ssl?
@use_ssl
end
# For backward compatibility.
alias use_ssl use_ssl?
# Turn on/off SSL.
# This flag must be set before starting session.
# If you change use_ssl value after session started,
# a Net::HTTP object raises IOError.
def use_ssl=(flag)
flag = (flag ? true : false)
raise IOError, "use_ssl value changed, but session already started" \
if started? and @use_ssl != flag
if flag and not @ssl_context
@ssl_context = OpenSSL::SSL::SSLContext.new
end
@use_ssl = flag
end
def self.ssl_context_accessor(name)
module_eval(<<-End, __FILE__, __LINE__ + 1)
def #{name}
return nil unless @ssl_context
@ssl_context.#{name}
end
def #{name}=(val)
@ssl_context ||= OpenSSL::SSL::SSLContext.new
@ssl_context.#{name} = val
end
End
end
ssl_context_accessor :key
ssl_context_accessor :cert
ssl_context_accessor :ca_file
ssl_context_accessor :ca_path
ssl_context_accessor :verify_mode
ssl_context_accessor :verify_callback
ssl_context_accessor :verify_depth
ssl_context_accessor :cert_store
def ssl_timeout
return nil unless @ssl_context
@ssl_context.timeout
end
def ssl_timeout=(sec)
raise ArgumentError, 'Net::HTTP#ssl_timeout= called but use_ssl=false' \
unless use_ssl?
@ssl_context ||= OpenSSL::SSL::SSLContext.new
@ssl_context.timeout = sec
end
# For backward compatibility
alias timeout= ssl_timeout=
def peer_cert
return nil if not use_ssl? or not @socket
@socket.io.peer_cert
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/net/imap.rb | tools/jruby-1.5.1/lib/ruby/1.8/net/imap.rb | #
# = net/imap.rb
#
# Copyright (C) 2000 Shugo Maeda <shugo@ruby-lang.org>
#
# This library is distributed under the terms of the Ruby license.
# You can freely distribute/modify this library.
#
# Documentation: Shugo Maeda, with RDoc conversion and overview by William
# Webber.
#
# See Net::IMAP for documentation.
#
require "socket"
require "monitor"
require "digest/md5"
begin
require "openssl"
rescue LoadError
end
module Net
#
# Net::IMAP implements Internet Message Access Protocol (IMAP) client
# functionality. The protocol is described in [IMAP].
#
# == IMAP Overview
#
# An IMAP client connects to a server, and then authenticates
# itself using either #authenticate() or #login(). Having
# authenticated itself, there is a range of commands
# available to it. Most work with mailboxes, which may be
# arranged in an hierarchical namespace, and each of which
# contains zero or more messages. How this is implemented on
# the server is implementation-dependent; on a UNIX server, it
# will frequently be implemented as a files in mailbox format
# within a hierarchy of directories.
#
# To work on the messages within a mailbox, the client must
# first select that mailbox, using either #select() or (for
# read-only access) #examine(). Once the client has successfully
# selected a mailbox, they enter _selected_ state, and that
# mailbox becomes the _current_ mailbox, on which mail-item
# related commands implicitly operate.
#
# Messages have two sorts of identifiers: message sequence
# numbers, and UIDs.
#
# Message sequence numbers number messages within a mail box
# from 1 up to the number of items in the mail box. If new
# message arrives during a session, it receives a sequence
# number equal to the new size of the mail box. If messages
# are expunged from the mailbox, remaining messages have their
# sequence numbers "shuffled down" to fill the gaps.
#
# UIDs, on the other hand, are permanently guaranteed not to
# identify another message within the same mailbox, even if
# the existing message is deleted. UIDs are required to
# be assigned in ascending (but not necessarily sequential)
# order within a mailbox; this means that if a non-IMAP client
# rearranges the order of mailitems within a mailbox, the
# UIDs have to be reassigned. An IMAP client cannot thus
# rearrange message orders.
#
# == Examples of Usage
#
# === List sender and subject of all recent messages in the default mailbox
#
# imap = Net::IMAP.new('mail.example.com')
# imap.authenticate('LOGIN', 'joe_user', 'joes_password')
# imap.examine('INBOX')
# imap.search(["RECENT"]).each do |message_id|
# envelope = imap.fetch(message_id, "ENVELOPE")[0].attr["ENVELOPE"]
# puts "#{envelope.from[0].name}: \t#{envelope.subject}"
# end
#
# === Move all messages from April 2003 from "Mail/sent-mail" to "Mail/sent-apr03"
#
# imap = Net::IMAP.new('mail.example.com')
# imap.authenticate('LOGIN', 'joe_user', 'joes_password')
# imap.select('Mail/sent-mail')
# if not imap.list('Mail/', 'sent-apr03')
# imap.create('Mail/sent-apr03')
# end
# imap.search(["BEFORE", "30-Apr-2003", "SINCE", "1-Apr-2003"]).each do |message_id|
# imap.copy(message_id, "Mail/sent-apr03")
# imap.store(message_id, "+FLAGS", [:Deleted])
# end
# imap.expunge
#
# == Thread Safety
#
# Net::IMAP supports concurrent threads. For example,
#
# imap = Net::IMAP.new("imap.foo.net", "imap2")
# imap.authenticate("cram-md5", "bar", "password")
# imap.select("inbox")
# fetch_thread = Thread.start { imap.fetch(1..-1, "UID") }
# search_result = imap.search(["BODY", "hello"])
# fetch_result = fetch_thread.value
# imap.disconnect
#
# This script invokes the FETCH command and the SEARCH command concurrently.
#
# == Errors
#
# An IMAP server can send three different types of responses to indicate
# failure:
#
# NO:: the attempted command could not be successfully completed. For
# instance, the username/password used for logging in are incorrect;
# the selected mailbox does not exists; etc.
#
# BAD:: the request from the client does not follow the server's
# understanding of the IMAP protocol. This includes attempting
# commands from the wrong client state; for instance, attempting
# to perform a SEARCH command without having SELECTed a current
# mailbox. It can also signal an internal server
# failure (such as a disk crash) has occurred.
#
# BYE:: the server is saying goodbye. This can be part of a normal
# logout sequence, and can be used as part of a login sequence
# to indicate that the server is (for some reason) unwilling
# to accept our connection. As a response to any other command,
# it indicates either that the server is shutting down, or that
# the server is timing out the client connection due to inactivity.
#
# These three error response are represented by the errors
# Net::IMAP::NoResponseError, Net::IMAP::BadResponseError, and
# Net::IMAP::ByeResponseError, all of which are subclasses of
# Net::IMAP::ResponseError. Essentially, all methods that involve
# sending a request to the server can generate one of these errors.
# Only the most pertinent instances have been documented below.
#
# Because the IMAP class uses Sockets for communication, its methods
# are also susceptible to the various errors that can occur when
# working with sockets. These are generally represented as
# Errno errors. For instance, any method that involves sending a
# request to the server and/or receiving a response from it could
# raise an Errno::EPIPE error if the network connection unexpectedly
# goes down. See the socket(7), ip(7), tcp(7), socket(2), connect(2),
# and associated man pages.
#
# Finally, a Net::IMAP::DataFormatError is thrown if low-level data
# is found to be in an incorrect format (for instance, when converting
# between UTF-8 and UTF-16), and Net::IMAP::ResponseParseError is
# thrown if a server response is non-parseable.
#
#
# == References
#
# [[IMAP]]
# M. Crispin, "INTERNET MESSAGE ACCESS PROTOCOL - VERSION 4rev1",
# RFC 2060, December 1996. (Note: since obsoleted by RFC 3501)
#
# [[LANGUAGE-TAGS]]
# Alvestrand, H., "Tags for the Identification of
# Languages", RFC 1766, March 1995.
#
# [[MD5]]
# Myers, J., and M. Rose, "The Content-MD5 Header Field", RFC
# 1864, October 1995.
#
# [[MIME-IMB]]
# Freed, N., and N. Borenstein, "MIME (Multipurpose Internet
# Mail Extensions) Part One: Format of Internet Message Bodies", RFC
# 2045, November 1996.
#
# [[RFC-822]]
# Crocker, D., "Standard for the Format of ARPA Internet Text
# Messages", STD 11, RFC 822, University of Delaware, August 1982.
#
# [[RFC-2087]]
# Myers, J., "IMAP4 QUOTA extension", RFC 2087, January 1997.
#
# [[RFC-2086]]
# Myers, J., "IMAP4 ACL extension", RFC 2086, January 1997.
#
# [[RFC-2195]]
# Klensin, J., Catoe, R., and Krumviede, P., "IMAP/POP AUTHorize Extension
# for Simple Challenge/Response", RFC 2195, September 1997.
#
# [[SORT-THREAD-EXT]]
# Crispin, M., "INTERNET MESSAGE ACCESS PROTOCOL - SORT and THREAD
# Extensions", draft-ietf-imapext-sort, May 2003.
#
# [[OSSL]]
# http://www.openssl.org
#
# [[RSSL]]
# http://savannah.gnu.org/projects/rubypki
#
# [[UTF7]]
# Goldsmith, D. and Davis, M., "UTF-7: A Mail-Safe Transformation Format of
# Unicode", RFC 2152, May 1997.
#
class IMAP
include MonitorMixin
if defined?(OpenSSL)
include OpenSSL
include SSL
end
# Returns an initial greeting response from the server.
attr_reader :greeting
# Returns recorded untagged responses. For example:
#
# imap.select("inbox")
# p imap.responses["EXISTS"][-1]
# #=> 2
# p imap.responses["UIDVALIDITY"][-1]
# #=> 968263756
attr_reader :responses
# Returns all response handlers.
attr_reader :response_handlers
# The thread to receive exceptions.
attr_accessor :client_thread
# Flag indicating a message has been seen
SEEN = :Seen
# Flag indicating a message has been answered
ANSWERED = :Answered
# Flag indicating a message has been flagged for special or urgent
# attention
FLAGGED = :Flagged
# Flag indicating a message has been marked for deletion. This
# will occur when the mailbox is closed or expunged.
DELETED = :Deleted
# Flag indicating a message is only a draft or work-in-progress version.
DRAFT = :Draft
# Flag indicating that the message is "recent", meaning that this
# session is the first session in which the client has been notified
# of this message.
RECENT = :Recent
# Flag indicating that a mailbox context name cannot contain
# children.
NOINFERIORS = :Noinferiors
# Flag indicating that a mailbox is not selected.
NOSELECT = :Noselect
# Flag indicating that a mailbox has been marked "interesting" by
# the server; this commonly indicates that the mailbox contains
# new messages.
MARKED = :Marked
# Flag indicating that the mailbox does not contains new messages.
UNMARKED = :Unmarked
# Returns the debug mode.
def self.debug
return @@debug
end
# Sets the debug mode.
def self.debug=(val)
return @@debug = val
end
# Adds an authenticator for Net::IMAP#authenticate. +auth_type+
# is the type of authentication this authenticator supports
# (for instance, "LOGIN"). The +authenticator+ is an object
# which defines a process() method to handle authentication with
# the server. See Net::IMAP::LoginAuthenticator and
# Net::IMAP::CramMD5Authenticator for examples.
#
# If +auth_type+ refers to an existing authenticator, it will be
# replaced by the new one.
def self.add_authenticator(auth_type, authenticator)
@@authenticators[auth_type] = authenticator
end
# Disconnects from the server.
def disconnect
begin
# try to call SSL::SSLSocket#io.
@sock.io.shutdown
rescue NoMethodError
# @sock is not an SSL::SSLSocket.
@sock.shutdown
end
@receiver_thread.join
@sock.close
end
# Returns true if disconnected from the server.
def disconnected?
return @sock.closed?
end
# Sends a CAPABILITY command, and returns an array of
# capabilities that the server supports. Each capability
# is a string. See [IMAP] for a list of possible
# capabilities.
#
# Note that the Net::IMAP class does not modify its
# behaviour according to the capabilities of the server;
# it is up to the user of the class to ensure that
# a certain capability is supported by a server before
# using it.
def capability
synchronize do
send_command("CAPABILITY")
return @responses.delete("CAPABILITY")[-1]
end
end
# Sends a NOOP command to the server. It does nothing.
def noop
send_command("NOOP")
end
# Sends a LOGOUT command to inform the server that the client is
# done with the connection.
def logout
send_command("LOGOUT")
end
# Sends an AUTHENTICATE command to authenticate the client.
# The +auth_type+ parameter is a string that represents
# the authentication mechanism to be used. Currently Net::IMAP
# supports authentication mechanisms:
#
# LOGIN:: login using cleartext user and password.
# CRAM-MD5:: login with cleartext user and encrypted password
# (see [RFC-2195] for a full description). This
# mechanism requires that the server have the user's
# password stored in clear-text password.
#
# For both these mechanisms, there should be two +args+: username
# and (cleartext) password. A server may not support one or other
# of these mechanisms; check #capability() for a capability of
# the form "AUTH=LOGIN" or "AUTH=CRAM-MD5".
#
# Authentication is done using the appropriate authenticator object:
# see @@authenticators for more information on plugging in your own
# authenticator.
#
# For example:
#
# imap.authenticate('LOGIN', user, password)
#
# A Net::IMAP::NoResponseError is raised if authentication fails.
def authenticate(auth_type, *args)
auth_type = auth_type.upcase
unless @@authenticators.has_key?(auth_type)
raise ArgumentError,
format('unknown auth type - "%s"', auth_type)
end
authenticator = @@authenticators[auth_type].new(*args)
send_command("AUTHENTICATE", auth_type) do |resp|
if resp.instance_of?(ContinuationRequest)
data = authenticator.process(resp.data.text.unpack("m")[0])
s = [data].pack("m").gsub(/\n/, "")
send_string_data(s)
put_string(CRLF)
end
end
end
# Sends a LOGIN command to identify the client and carries
# the plaintext +password+ authenticating this +user+. Note
# that, unlike calling #authenticate() with an +auth_type+
# of "LOGIN", #login() does *not* use the login authenticator.
#
# A Net::IMAP::NoResponseError is raised if authentication fails.
def login(user, password)
send_command("LOGIN", user, password)
end
# Sends a SELECT command to select a +mailbox+ so that messages
# in the +mailbox+ can be accessed.
#
# After you have selected a mailbox, you may retrieve the
# number of items in that mailbox from @responses["EXISTS"][-1],
# and the number of recent messages from @responses["RECENT"][-1].
# Note that these values can change if new messages arrive
# during a session; see #add_response_handler() for a way of
# detecting this event.
#
# A Net::IMAP::NoResponseError is raised if the mailbox does not
# exist or is for some reason non-selectable.
def select(mailbox)
synchronize do
@responses.clear
send_command("SELECT", mailbox)
end
end
# Sends a EXAMINE command to select a +mailbox+ so that messages
# in the +mailbox+ can be accessed. Behaves the same as #select(),
# except that the selected +mailbox+ is identified as read-only.
#
# A Net::IMAP::NoResponseError is raised if the mailbox does not
# exist or is for some reason non-examinable.
def examine(mailbox)
synchronize do
@responses.clear
send_command("EXAMINE", mailbox)
end
end
# Sends a CREATE command to create a new +mailbox+.
#
# A Net::IMAP::NoResponseError is raised if a mailbox with that name
# cannot be created.
def create(mailbox)
send_command("CREATE", mailbox)
end
# Sends a DELETE command to remove the +mailbox+.
#
# A Net::IMAP::NoResponseError is raised if a mailbox with that name
# cannot be deleted, either because it does not exist or because the
# client does not have permission to delete it.
def delete(mailbox)
send_command("DELETE", mailbox)
end
# Sends a RENAME command to change the name of the +mailbox+ to
# +newname+.
#
# A Net::IMAP::NoResponseError is raised if a mailbox with the
# name +mailbox+ cannot be renamed to +newname+ for whatever
# reason; for instance, because +mailbox+ does not exist, or
# because there is already a mailbox with the name +newname+.
def rename(mailbox, newname)
send_command("RENAME", mailbox, newname)
end
# Sends a SUBSCRIBE command to add the specified +mailbox+ name to
# the server's set of "active" or "subscribed" mailboxes as returned
# by #lsub().
#
# A Net::IMAP::NoResponseError is raised if +mailbox+ cannot be
# subscribed to, for instance because it does not exist.
def subscribe(mailbox)
send_command("SUBSCRIBE", mailbox)
end
# Sends a UNSUBSCRIBE command to remove the specified +mailbox+ name
# from the server's set of "active" or "subscribed" mailboxes.
#
# A Net::IMAP::NoResponseError is raised if +mailbox+ cannot be
# unsubscribed from, for instance because the client is not currently
# subscribed to it.
def unsubscribe(mailbox)
send_command("UNSUBSCRIBE", mailbox)
end
# Sends a LIST command, and returns a subset of names from
# the complete set of all names available to the client.
# +refname+ provides a context (for instance, a base directory
# in a directory-based mailbox hierarchy). +mailbox+ specifies
# a mailbox or (via wildcards) mailboxes under that context.
# Two wildcards may be used in +mailbox+: '*', which matches
# all characters *including* the hierarchy delimiter (for instance,
# '/' on a UNIX-hosted directory-based mailbox hierarchy); and '%',
# which matches all characters *except* the hierarchy delimiter.
#
# If +refname+ is empty, +mailbox+ is used directly to determine
# which mailboxes to match. If +mailbox+ is empty, the root
# name of +refname+ and the hierarchy delimiter are returned.
#
# The return value is an array of +Net::IMAP::MailboxList+. For example:
#
# imap.create("foo/bar")
# imap.create("foo/baz")
# p imap.list("", "foo/%")
# #=> [#<Net::IMAP::MailboxList attr=[:Noselect], delim="/", name="foo/">, \\
# #<Net::IMAP::MailboxList attr=[:Noinferiors, :Marked], delim="/", name="foo/bar">, \\
# #<Net::IMAP::MailboxList attr=[:Noinferiors], delim="/", name="foo/baz">]
def list(refname, mailbox)
synchronize do
send_command("LIST", refname, mailbox)
return @responses.delete("LIST")
end
end
# Sends the GETQUOTAROOT command along with specified +mailbox+.
# This command is generally available to both admin and user.
# If mailbox exists, returns an array containing objects of
# Net::IMAP::MailboxQuotaRoot and Net::IMAP::MailboxQuota.
def getquotaroot(mailbox)
synchronize do
send_command("GETQUOTAROOT", mailbox)
result = []
result.concat(@responses.delete("QUOTAROOT"))
result.concat(@responses.delete("QUOTA"))
return result
end
end
# Sends the GETQUOTA command along with specified +mailbox+.
# If this mailbox exists, then an array containing a
# Net::IMAP::MailboxQuota object is returned. This
# command generally is only available to server admin.
def getquota(mailbox)
synchronize do
send_command("GETQUOTA", mailbox)
return @responses.delete("QUOTA")
end
end
# Sends a SETQUOTA command along with the specified +mailbox+ and
# +quota+. If +quota+ is nil, then quota will be unset for that
# mailbox. Typically one needs to be logged in as server admin
# for this to work. The IMAP quota commands are described in
# [RFC-2087].
def setquota(mailbox, quota)
if quota.nil?
data = '()'
else
data = '(STORAGE ' + quota.to_s + ')'
end
send_command("SETQUOTA", mailbox, RawData.new(data))
end
# Sends the SETACL command along with +mailbox+, +user+ and the
# +rights+ that user is to have on that mailbox. If +rights+ is nil,
# then that user will be stripped of any rights to that mailbox.
# The IMAP ACL commands are described in [RFC-2086].
def setacl(mailbox, user, rights)
if rights.nil?
send_command("SETACL", mailbox, user, "")
else
send_command("SETACL", mailbox, user, rights)
end
end
# Send the GETACL command along with specified +mailbox+.
# If this mailbox exists, an array containing objects of
# Net::IMAP::MailboxACLItem will be returned.
def getacl(mailbox)
synchronize do
send_command("GETACL", mailbox)
return @responses.delete("ACL")[-1]
end
end
# Sends a LSUB command, and returns a subset of names from the set
# of names that the user has declared as being "active" or
# "subscribed". +refname+ and +mailbox+ are interpreted as
# for #list().
# The return value is an array of +Net::IMAP::MailboxList+.
def lsub(refname, mailbox)
synchronize do
send_command("LSUB", refname, mailbox)
return @responses.delete("LSUB")
end
end
# Sends a STATUS command, and returns the status of the indicated
# +mailbox+. +attr+ is a list of one or more attributes that
# we are request the status of. Supported attributes include:
#
# MESSAGES:: the number of messages in the mailbox.
# RECENT:: the number of recent messages in the mailbox.
# UNSEEN:: the number of unseen messages in the mailbox.
#
# The return value is a hash of attributes. For example:
#
# p imap.status("inbox", ["MESSAGES", "RECENT"])
# #=> {"RECENT"=>0, "MESSAGES"=>44}
#
# A Net::IMAP::NoResponseError is raised if status values
# for +mailbox+ cannot be returned, for instance because it
# does not exist.
def status(mailbox, attr)
synchronize do
send_command("STATUS", mailbox, attr)
return @responses.delete("STATUS")[-1].attr
end
end
# Sends a APPEND command to append the +message+ to the end of
# the +mailbox+. The optional +flags+ argument is an array of
# flags to initially passing to the new message. The optional
# +date_time+ argument specifies the creation time to assign to the
# new message; it defaults to the current time.
# For example:
#
# imap.append("inbox", <<EOF.gsub(/\n/, "\r\n"), [:Seen], Time.now)
# Subject: hello
# From: shugo@ruby-lang.org
# To: shugo@ruby-lang.org
#
# hello world
# EOF
#
# A Net::IMAP::NoResponseError is raised if the mailbox does
# not exist (it is not created automatically), or if the flags,
# date_time, or message arguments contain errors.
def append(mailbox, message, flags = nil, date_time = nil)
args = []
if flags
args.push(flags)
end
args.push(date_time) if date_time
args.push(Literal.new(message))
send_command("APPEND", mailbox, *args)
end
# Sends a CHECK command to request a checkpoint of the currently
# selected mailbox. This performs implementation-specific
# housekeeping, for instance, reconciling the mailbox's
# in-memory and on-disk state.
def check
send_command("CHECK")
end
# Sends a CLOSE command to close the currently selected mailbox.
# The CLOSE command permanently removes from the mailbox all
# messages that have the \Deleted flag set.
def close
send_command("CLOSE")
end
# Sends a EXPUNGE command to permanently remove from the currently
# selected mailbox all messages that have the \Deleted flag set.
def expunge
synchronize do
send_command("EXPUNGE")
return @responses.delete("EXPUNGE")
end
end
# Sends a SEARCH command to search the mailbox for messages that
# match the given searching criteria, and returns message sequence
# numbers. +keys+ can either be a string holding the entire
# search string, or a single-dimension array of search keywords and
# arguments. The following are some common search criteria;
# see [IMAP] section 6.4.4 for a full list.
#
# <message set>:: a set of message sequence numbers. ',' indicates
# an interval, ':' indicates a range. For instance,
# '2,10:12,15' means "2,10,11,12,15".
#
# BEFORE <date>:: messages with an internal date strictly before
# <date>. The date argument has a format similar
# to 8-Aug-2002.
#
# BODY <string>:: messages that contain <string> within their body.
#
# CC <string>:: messages containing <string> in their CC field.
#
# FROM <string>:: messages that contain <string> in their FROM field.
#
# NEW:: messages with the \Recent, but not the \Seen, flag set.
#
# NOT <search-key>:: negate the following search key.
#
# OR <search-key> <search-key>:: "or" two search keys together.
#
# ON <date>:: messages with an internal date exactly equal to <date>,
# which has a format similar to 8-Aug-2002.
#
# SINCE <date>:: messages with an internal date on or after <date>.
#
# SUBJECT <string>:: messages with <string> in their subject.
#
# TO <string>:: messages with <string> in their TO field.
#
# For example:
#
# p imap.search(["SUBJECT", "hello", "NOT", "NEW"])
# #=> [1, 6, 7, 8]
def search(keys, charset = nil)
return search_internal("SEARCH", keys, charset)
end
# As for #search(), but returns unique identifiers.
def uid_search(keys, charset = nil)
return search_internal("UID SEARCH", keys, charset)
end
# Sends a FETCH command to retrieve data associated with a message
# in the mailbox. The +set+ parameter is a number or an array of
# numbers or a Range object. The number is a message sequence
# number. +attr+ is a list of attributes to fetch; see the
# documentation for Net::IMAP::FetchData for a list of valid
# attributes.
# The return value is an array of Net::IMAP::FetchData. For example:
#
# p imap.fetch(6..8, "UID")
# #=> [#<Net::IMAP::FetchData seqno=6, attr={"UID"=>98}>, \\
# #<Net::IMAP::FetchData seqno=7, attr={"UID"=>99}>, \\
# #<Net::IMAP::FetchData seqno=8, attr={"UID"=>100}>]
# p imap.fetch(6, "BODY[HEADER.FIELDS (SUBJECT)]")
# #=> [#<Net::IMAP::FetchData seqno=6, attr={"BODY[HEADER.FIELDS (SUBJECT)]"=>"Subject: test\r\n\r\n"}>]
# data = imap.uid_fetch(98, ["RFC822.SIZE", "INTERNALDATE"])[0]
# p data.seqno
# #=> 6
# p data.attr["RFC822.SIZE"]
# #=> 611
# p data.attr["INTERNALDATE"]
# #=> "12-Oct-2000 22:40:59 +0900"
# p data.attr["UID"]
# #=> 98
def fetch(set, attr)
return fetch_internal("FETCH", set, attr)
end
# As for #fetch(), but +set+ contains unique identifiers.
def uid_fetch(set, attr)
return fetch_internal("UID FETCH", set, attr)
end
# Sends a STORE command to alter data associated with messages
# in the mailbox, in particular their flags. The +set+ parameter
# is a number or an array of numbers or a Range object. Each number
# is a message sequence number. +attr+ is the name of a data item
# to store: 'FLAGS' means to replace the message's flag list
# with the provided one; '+FLAGS' means to add the provided flags;
# and '-FLAGS' means to remove them. +flags+ is a list of flags.
#
# The return value is an array of Net::IMAP::FetchData. For example:
#
# p imap.store(6..8, "+FLAGS", [:Deleted])
# #=> [#<Net::IMAP::FetchData seqno=6, attr={"FLAGS"=>[:Seen, :Deleted]}>, \\
# #<Net::IMAP::FetchData seqno=7, attr={"FLAGS"=>[:Seen, :Deleted]}>, \\
# #<Net::IMAP::FetchData seqno=8, attr={"FLAGS"=>[:Seen, :Deleted]}>]
def store(set, attr, flags)
return store_internal("STORE", set, attr, flags)
end
# As for #store(), but +set+ contains unique identifiers.
def uid_store(set, attr, flags)
return store_internal("UID STORE", set, attr, flags)
end
# Sends a COPY command to copy the specified message(s) to the end
# of the specified destination +mailbox+. The +set+ parameter is
# a number or an array of numbers or a Range object. The number is
# a message sequence number.
def copy(set, mailbox)
copy_internal("COPY", set, mailbox)
end
# As for #copy(), but +set+ contains unique identifiers.
def uid_copy(set, mailbox)
copy_internal("UID COPY", set, mailbox)
end
# Sends a SORT command to sort messages in the mailbox.
# Returns an array of message sequence numbers. For example:
#
# p imap.sort(["FROM"], ["ALL"], "US-ASCII")
# #=> [1, 2, 3, 5, 6, 7, 8, 4, 9]
# p imap.sort(["DATE"], ["SUBJECT", "hello"], "US-ASCII")
# #=> [6, 7, 8, 1]
#
# See [SORT-THREAD-EXT] for more details.
def sort(sort_keys, search_keys, charset)
return sort_internal("SORT", sort_keys, search_keys, charset)
end
# As for #sort(), but returns an array of unique identifiers.
def uid_sort(sort_keys, search_keys, charset)
return sort_internal("UID SORT", sort_keys, search_keys, charset)
end
# Adds a response handler. For example, to detect when
# the server sends us a new EXISTS response (which normally
# indicates new messages being added to the mail box),
# you could add the following handler after selecting the
# mailbox.
#
# imap.add_response_handler { |resp|
# if resp.kind_of?(Net::IMAP::UntaggedResponse) and resp.name == "EXISTS"
# puts "Mailbox now has #{resp.data} messages"
# end
# }
#
def add_response_handler(handler = Proc.new)
@response_handlers.push(handler)
end
# Removes the response handler.
def remove_response_handler(handler)
@response_handlers.delete(handler)
end
# As for #search(), but returns message sequence numbers in threaded
# format, as a Net::IMAP::ThreadMember tree. The supported algorithms
# are:
#
# ORDEREDSUBJECT:: split into single-level threads according to subject,
# ordered by date.
# REFERENCES:: split into threads by parent/child relationships determined
# by which message is a reply to which.
#
# Unlike #search(), +charset+ is a required argument. US-ASCII
# and UTF-8 are sample values.
#
# See [SORT-THREAD-EXT] for more details.
def thread(algorithm, search_keys, charset)
return thread_internal("THREAD", algorithm, search_keys, charset)
end
# As for #thread(), but returns unique identifiers instead of
# message sequence numbers.
def uid_thread(algorithm, search_keys, charset)
return thread_internal("UID THREAD", algorithm, search_keys, charset)
end
# Decode a string from modified UTF-7 format to UTF-8.
#
# UTF-7 is a 7-bit encoding of Unicode [UTF7]. IMAP uses a
# slightly modified version of this to encode mailbox names
# containing non-ASCII characters; see [IMAP] section 5.1.3.
#
# Net::IMAP does _not_ automatically encode and decode
# mailbox names to and from utf7.
def self.decode_utf7(s)
return s.gsub(/&(.*?)-/n) {
if $1.empty?
"&"
else
base64 = $1.tr(",", "/")
x = base64.length % 4
if x > 0
base64.concat("=" * (4 - x))
end
u16tou8(base64.unpack("m")[0])
end
}
end
# Encode a string from UTF-8 format to modified UTF-7.
def self.encode_utf7(s)
return s.gsub(/(&)|([^\x20-\x25\x27-\x7e]+)/n) { |x|
if $1
"&-"
else
base64 = [u8tou16(x)].pack("m")
"&" + base64.delete("=\n").tr("/", ",") + "-"
end
}
end
private
CRLF = "\r\n" # :nodoc:
PORT = 143 # :nodoc:
@@debug = false
@@authenticators = {}
# Creates a new Net::IMAP object and connects it to the specified
# +port+ (143 by default) on the named +host+. If +usessl+ is true,
# then an attempt will
# be made to use SSL (now TLS) to connect to the server. For this
# to work OpenSSL [OSSL] and the Ruby OpenSSL [RSSL]
# extensions need to be installed. The +certs+ parameter indicates
# the path or file containing the CA cert of the server, and the
# +verify+ parameter is for the OpenSSL verification callback.
#
# The most common errors are:
#
# Errno::ECONNREFUSED:: connection refused by +host+ or an intervening
# firewall.
# Errno::ETIMEDOUT:: connection timed out (possibly due to packets
# being dropped by an intervening firewall).
# Errno::ENETUNREACH:: there is no route to that network.
# SocketError:: hostname not known or other socket error.
# Net::IMAP::ByeResponseError:: we connected to the host, but they
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | true |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/bigdecimal/newton.rb | tools/jruby-1.5.1/lib/ruby/1.8/bigdecimal/newton.rb | #
# newton.rb
#
# Solves the nonlinear algebraic equation system f = 0 by Newton's method.
# This program is not dependent on BigDecimal.
#
# To call:
# n = nlsolve(f,x)
# where n is the number of iterations required,
# x is the initial value vector
# f is an Object which is used to compute the values of the equations to be solved.
# It must provide the following methods:
#
# f.values(x):: returns the values of all functions at x
#
# f.zero:: returns 0.0
# f.one:: returns 1.0
# f.two:: returns 1.0
# f.ten:: returns 10.0
#
# f.eps:: returns the convergence criterion (epsilon value) used to determine whether two values are considered equal. If |a-b| < epsilon, the two values are considered equal.
#
# On exit, x is the solution vector.
#
require "bigdecimal/ludcmp"
require "bigdecimal/jacobian"
module Newton
include LUSolve
include Jacobian
def norm(fv,zero=0.0)
s = zero
n = fv.size
for i in 0...n do
s += fv[i]*fv[i]
end
s
end
def nlsolve(f,x)
nRetry = 0
n = x.size
f0 = f.values(x)
zero = f.zero
one = f.one
two = f.two
p5 = one/two
d = norm(f0,zero)
minfact = f.ten*f.ten*f.ten
minfact = one/minfact
e = f.eps
while d >= e do
nRetry += 1
# Not yet converged. => Compute Jacobian matrix
dfdx = jacobian(f,f0,x)
# Solve dfdx*dx = -f0 to estimate dx
dx = lusolve(dfdx,f0,ludecomp(dfdx,n,zero,one),zero)
fact = two
xs = x.dup
begin
fact *= p5
if fact < minfact then
raise "Failed to reduce function values."
end
for i in 0...n do
x[i] = xs[i] - dx[i]*fact
end
f0 = f.values(x)
dn = norm(f0,zero)
end while(dn>=d)
d = dn
end
nRetry
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/bigdecimal/math.rb | tools/jruby-1.5.1/lib/ruby/1.8/bigdecimal/math.rb | #
#--
# Contents:
# sqrt(x, prec)
# sin (x, prec)
# cos (x, prec)
# atan(x, prec) Note: |x|<1, x=0.9999 may not converge.
# exp (x, prec)
# log (x, prec)
# PI (prec)
# E (prec) == exp(1.0,prec)
#
# where:
# x ... BigDecimal number to be computed.
# |x| must be small enough to get convergence.
# prec ... Number of digits to be obtained.
#++
#
# Provides mathematical functions.
#
# Example:
#
# require "bigdecimal"
# require "bigdecimal/math"
#
# include BigMath
#
# a = BigDecimal((PI(100)/2).to_s)
# puts sin(a,100) # -> 0.10000000000000000000......E1
#
module BigMath
# Computes the square root of x to the specified number of digits of
# precision.
#
# BigDecimal.new('2').sqrt(16).to_s
# -> "0.14142135623730950488016887242096975E1"
#
def sqrt(x,prec)
x.sqrt(prec)
end
# Computes the sine of x to the specified number of digits of precision.
#
# If x is infinite or NaN, returns NaN.
def sin(x, prec)
raise ArgumentError, "Zero or negative precision for sin" if prec <= 0
return BigDecimal("NaN") if x.infinite? || x.nan?
n = prec + BigDecimal.double_fig
one = BigDecimal("1")
two = BigDecimal("2")
x1 = x
x2 = x.mult(x,n)
sign = 1
y = x
d = y
i = one
z = one
while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
m = BigDecimal.double_fig if m < BigDecimal.double_fig
sign = -sign
x1 = x2.mult(x1,n)
i += two
z *= (i-one) * i
d = sign * x1.div(z,m)
y += d
end
y
end
# Computes the cosine of x to the specified number of digits of precision.
#
# If x is infinite or NaN, returns NaN.
def cos(x, prec)
raise ArgumentError, "Zero or negative precision for cos" if prec <= 0
return BigDecimal("NaN") if x.infinite? || x.nan?
n = prec + BigDecimal.double_fig
one = BigDecimal("1")
two = BigDecimal("2")
x1 = one
x2 = x.mult(x,n)
sign = 1
y = one
d = y
i = BigDecimal("0")
z = one
while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
m = BigDecimal.double_fig if m < BigDecimal.double_fig
sign = -sign
x1 = x2.mult(x1,n)
i += two
z *= (i-one) * i
d = sign * x1.div(z,m)
y += d
end
y
end
# Computes the arctangent of x to the specified number of digits of precision.
#
# If x is infinite or NaN, returns NaN.
# Raises an argument error if x > 1.
def atan(x, prec)
raise ArgumentError, "Zero or negative precision for atan" if prec <= 0
return BigDecimal("NaN") if x.infinite? || x.nan?
raise ArgumentError, "x.abs must be less than 1.0" if x.abs>=1
n = prec + BigDecimal.double_fig
y = x
d = y
t = x
r = BigDecimal("3")
x2 = x.mult(x,n)
while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
m = BigDecimal.double_fig if m < BigDecimal.double_fig
t = -t.mult(x2,n)
d = t.div(r,m)
y += d
r += 2
end
y
end
# Computes the value of e (the base of natural logarithms) raised to the
# power of x, to the specified number of digits of precision.
#
# If x is infinite or NaN, returns NaN.
#
# BigMath::exp(BigDecimal.new('1'), 10).to_s
# -> "0.271828182845904523536028752390026306410273E1"
def exp(x, prec)
raise ArgumentError, "Zero or negative precision for exp" if prec <= 0
return BigDecimal("NaN") if x.infinite? || x.nan?
n = prec + BigDecimal.double_fig
one = BigDecimal("1")
x1 = one
y = one
d = y
z = one
i = 0
while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
m = BigDecimal.double_fig if m < BigDecimal.double_fig
x1 = x1.mult(x,n)
i += 1
z *= i
d = x1.div(z,m)
y += d
end
y
end
# Computes the natural logarithm of x to the specified number of digits
# of precision.
#
# Returns x if x is infinite or NaN.
#
def log(x, prec)
raise ArgumentError, "Zero or negative argument for log" if x <= 0 || prec <= 0
return x if x.infinite? || x.nan?
one = BigDecimal("1")
two = BigDecimal("2")
n = prec + BigDecimal.double_fig
x = (x - one).div(x + one,n)
x2 = x.mult(x,n)
y = x
d = y
i = one
while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
m = BigDecimal.double_fig if m < BigDecimal.double_fig
x = x2.mult(x,n)
i += two
d = x.div(i,m)
y += d
end
y*two
end
# Computes the value of pi to the specified number of digits of precision.
def PI(prec)
raise ArgumentError, "Zero or negative argument for PI" if prec <= 0
n = prec + BigDecimal.double_fig
zero = BigDecimal("0")
one = BigDecimal("1")
two = BigDecimal("2")
m25 = BigDecimal("-0.04")
m57121 = BigDecimal("-57121")
pi = zero
d = one
k = one
w = one
t = BigDecimal("-80")
while d.nonzero? && ((m = n - (pi.exponent - d.exponent).abs) > 0)
m = BigDecimal.double_fig if m < BigDecimal.double_fig
t = t*m25
d = t.div(k,m)
k = k+two
pi = pi + d
end
d = one
k = one
w = one
t = BigDecimal("956")
while d.nonzero? && ((m = n - (pi.exponent - d.exponent).abs) > 0)
m = BigDecimal.double_fig if m < BigDecimal.double_fig
t = t.div(m57121,n)
d = t.div(k,m)
pi = pi + d
k = k+two
end
pi
end
# Computes e (the base of natural logarithms) to the specified number of
# digits of precision.
def E(prec)
raise ArgumentError, "Zero or negative precision for E" if prec <= 0
n = prec + BigDecimal.double_fig
one = BigDecimal("1")
y = one
d = y
z = one
i = 0
while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
m = BigDecimal.double_fig if m < BigDecimal.double_fig
i += 1
z *= i
d = one.div(z,m)
y += d
end
y
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/bigdecimal/jacobian.rb | tools/jruby-1.5.1/lib/ruby/1.8/bigdecimal/jacobian.rb | #
# require 'bigdecimal/jacobian'
#
# Provides methods to compute the Jacobian matrix of a set of equations at a
# point x. In the methods below:
#
# f is an Object which is used to compute the Jacobian matrix of the equations.
# It must provide the following methods:
#
# f.values(x):: returns the values of all functions at x
#
# f.zero:: returns 0.0
# f.one:: returns 1.0
# f.two:: returns 1.0
# f.ten:: returns 10.0
#
# f.eps:: returns the convergence criterion (epsilon value) used to determine whether two values are considered equal. If |a-b| < epsilon, the two values are considered equal.
#
# x is the point at which to compute the Jacobian.
#
# fx is f.values(x).
#
module Jacobian
#--
def isEqual(a,b,zero=0.0,e=1.0e-8)
aa = a.abs
bb = b.abs
if aa == zero && bb == zero then
true
else
if ((a-b)/(aa+bb)).abs < e then
true
else
false
end
end
end
#++
# Computes the derivative of f[i] at x[i].
# fx is the value of f at x.
def dfdxi(f,fx,x,i)
nRetry = 0
n = x.size
xSave = x[i]
ok = 0
ratio = f.ten*f.ten*f.ten
dx = x[i].abs/ratio
dx = fx[i].abs/ratio if isEqual(dx,f.zero,f.zero,f.eps)
dx = f.one/f.ten if isEqual(dx,f.zero,f.zero,f.eps)
until ok>0 do
s = f.zero
deriv = []
if(nRetry>100) then
raize "Singular Jacobian matrix. No change at x[" + i.to_s + "]"
end
dx = dx*f.two
x[i] += dx
fxNew = f.values(x)
for j in 0...n do
if !isEqual(fxNew[j],fx[j],f.zero,f.eps) then
ok += 1
deriv <<= (fxNew[j]-fx[j])/dx
else
deriv <<= f.zero
end
end
x[i] = xSave
end
deriv
end
# Computes the Jacobian of f at x. fx is the value of f at x.
def jacobian(f,fx,x)
n = x.size
dfdx = Array::new(n*n)
for i in 0...n do
df = dfdxi(f,fx,x,i)
for j in 0...n do
dfdx[j*n+i] = df[j]
end
end
dfdx
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/bigdecimal/ludcmp.rb | tools/jruby-1.5.1/lib/ruby/1.8/bigdecimal/ludcmp.rb | #
# Solves a*x = b for x, using LU decomposition.
#
module LUSolve
# Performs LU decomposition of the n by n matrix a.
def ludecomp(a,n,zero=0,one=1)
prec = BigDecimal.limit(nil)
ps = []
scales = []
for i in 0...n do # pick up largest(abs. val.) element in each row.
ps <<= i
nrmrow = zero
ixn = i*n
for j in 0...n do
biggst = a[ixn+j].abs
nrmrow = biggst if biggst>nrmrow
end
if nrmrow>zero then
scales <<= one.div(nrmrow,prec)
else
raise "Singular matrix"
end
end
n1 = n - 1
for k in 0...n1 do # Gaussian elimination with partial pivoting.
biggst = zero;
for i in k...n do
size = a[ps[i]*n+k].abs*scales[ps[i]]
if size>biggst then
biggst = size
pividx = i
end
end
raise "Singular matrix" if biggst<=zero
if pividx!=k then
j = ps[k]
ps[k] = ps[pividx]
ps[pividx] = j
end
pivot = a[ps[k]*n+k]
for i in (k+1)...n do
psin = ps[i]*n
a[psin+k] = mult = a[psin+k].div(pivot,prec)
if mult!=zero then
pskn = ps[k]*n
for j in (k+1)...n do
a[psin+j] -= mult.mult(a[pskn+j],prec)
end
end
end
end
raise "Singular matrix" if a[ps[n1]*n+n1] == zero
ps
end
# Solves a*x = b for x, using LU decomposition.
#
# a is a matrix, b is a constant vector, x is the solution vector.
#
# ps is the pivot, a vector which indicates the permutation of rows performed
# during LU decomposition.
def lusolve(a,b,ps,zero=0.0)
prec = BigDecimal.limit(nil)
n = ps.size
x = []
for i in 0...n do
dot = zero
psin = ps[i]*n
for j in 0...i do
dot = a[psin+j].mult(x[j],prec) + dot
end
x <<= b[ps[i]] - dot
end
(n-1).downto(0) do |i|
dot = zero
psin = ps[i]*n
for j in (i+1)...n do
dot = a[psin+j].mult(x[j],prec) + dot
end
x[i] = (x[i]-dot).div(a[psin+i],prec)
end
x
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/bigdecimal/util.rb | tools/jruby-1.5.1/lib/ruby/1.8/bigdecimal/util.rb | #
# BigDecimal utility library.
#
# To use these functions, require 'bigdecimal/util'
#
# The following methods are provided to convert other types to BigDecimals:
#
# String#to_d -> BigDecimal
# Float#to_d -> BigDecimal
# Rational#to_d -> BigDecimal
#
# The following method is provided to convert BigDecimals to other types:
#
# BigDecimal#to_r -> Rational
#
# ----------------------------------------------------------------------
#
class Float < Numeric
def to_d
BigDecimal(self.to_s)
end
end
class String
def to_d
BigDecimal(self)
end
end
class BigDecimal < Numeric
# Converts a BigDecimal to a String of the form "nnnnnn.mmm".
# This method is deprecated; use BigDecimal#to_s("F") instead.
def to_digits
if self.nan? || self.infinite? || self.zero?
self.to_s
else
i = self.to_i.to_s
s,f,y,z = self.frac.split
i + "." + ("0"*(-z)) + f
end
end
# Converts a BigDecimal to a Rational.
def to_r
sign,digits,base,power = self.split
numerator = sign*digits.to_i
denomi_power = power - digits.size # base is always 10
if denomi_power < 0
Rational(numerator,base ** (-denomi_power))
else
Rational(numerator * (base ** denomi_power),1)
end
end
end
class Rational < Numeric
# Converts a Rational to a BigDecimal
def to_d(nFig=0)
num = self.numerator.to_s
if nFig<=0
nFig = BigDecimal.double_fig*2+1
end
BigDecimal.new(num).div(self.denominator,nFig)
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xmlrpc/utils.rb | tools/jruby-1.5.1/lib/ruby/1.8/xmlrpc/utils.rb | #
# Defines ParserWriterChooseMixin, which makes it possible to choose a
# different XML writer and/or XML parser then the default one.
# The Mixin is used in client.rb (class Client) and server.rb (class
# BasicServer)
#
# Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de)
#
# $Id: utils.rb 13771 2007-10-24 23:04:42Z jeg2 $
#
module XMLRPC
#
# This module enables a user-class to be marshalled
# by XML-RPC for Ruby into a Hash, with one additional
# key/value pair "___class___" => ClassName
#
module Marshallable
end
module ParserWriterChooseMixin
def set_writer(writer)
@create = Create.new(writer)
self
end
def set_parser(parser)
@parser = parser
self
end
private
def create
# if set_writer was not already called then call it now
if @create.nil? then
set_writer(Config::DEFAULT_WRITER.new)
end
@create
end
def parser
# if set_parser was not already called then call it now
if @parser.nil? then
set_parser(Config::DEFAULT_PARSER.new)
end
@parser
end
end # module ParserWriterChooseMixin
module Service
#
# base class for Service Interface definitions, used
# by BasicServer#add_handler
#
class BasicInterface
attr_reader :prefix, :methods
def initialize(prefix)
@prefix = prefix
@methods = []
end
def add_method(sig, help=nil, meth_name=nil)
mname = nil
sig = [sig] if sig.kind_of? String
sig = sig.collect do |s|
name, si = parse_sig(s)
raise "Wrong signatures!" if mname != nil and name != mname
mname = name
si
end
@methods << [mname, meth_name || mname, sig, help]
end
private # ---------------------------------
def parse_sig(sig)
# sig is a String
if sig =~ /^\s*(\w+)\s+([^(]+)(\(([^)]*)\))?\s*$/
params = [$1]
name = $2.strip
$4.split(",").each {|i| params << i.strip} if $4 != nil
return name, params
else
raise "Syntax error in signature"
end
end
end # class BasicInterface
#
# class which wraps a Service Interface definition, used
# by BasicServer#add_handler
#
class Interface < BasicInterface
def initialize(prefix, &p)
raise "No interface specified" if p.nil?
super(prefix)
instance_eval(&p)
end
def get_methods(obj, delim=".")
prefix = @prefix + delim
@methods.collect { |name, meth, sig, help|
[prefix + name, obj.method(meth).to_proc, sig, help]
}
end
private # ---------------------------------
def meth(*a)
add_method(*a)
end
end # class Interface
class PublicInstanceMethodsInterface < BasicInterface
def initialize(prefix)
super(prefix)
end
def get_methods(obj, delim=".")
prefix = @prefix + delim
obj.class.public_instance_methods(false).collect { |name|
[prefix + name, obj.method(name).to_proc, nil, nil]
}
end
end
end # module Service
#
# short-form to create a Service::Interface
#
def self.interface(prefix, &p)
Service::Interface.new(prefix, &p)
end
# short-cut for creating a PublicInstanceMethodsInterface
def self.iPIMethods(prefix)
Service::PublicInstanceMethodsInterface.new(prefix)
end
module ParseContentType
def parse_content_type(str)
a, *b = str.split(";")
return a.strip.downcase, *b
end
end
end # module XMLRPC
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xmlrpc/parser.rb | tools/jruby-1.5.1/lib/ruby/1.8/xmlrpc/parser.rb | #
# Parser for XML-RPC call and response
#
# Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de)
#
# $Id: parser.rb 13771 2007-10-24 23:04:42Z jeg2 $
#
require "date"
require "xmlrpc/base64"
require "xmlrpc/datetime"
# add some methods to NQXML::Node
module NQXML
class Node
def removeChild(node)
@children.delete(node)
end
def childNodes
@children
end
def hasChildNodes
not @children.empty?
end
def [] (index)
@children[index]
end
def nodeType
if @entity.instance_of? NQXML::Text then :TEXT
elsif @entity.instance_of? NQXML::Comment then :COMMENT
#elsif @entity.instance_of? NQXML::Element then :ELEMENT
elsif @entity.instance_of? NQXML::Tag then :ELEMENT
else :ELSE
end
end
def nodeValue
#TODO: error when wrong Entity-type
@entity.text
end
def nodeName
#TODO: error when wrong Entity-type
@entity.name
end
end # class Node
end # module NQXML
module XMLRPC
class FaultException < StandardError
attr_reader :faultCode, :faultString
alias message faultString
def initialize(faultCode, faultString)
@faultCode = faultCode
@faultString = faultString
end
# returns a hash
def to_h
{"faultCode" => @faultCode, "faultString" => @faultString}
end
end
module Convert
def self.int(str)
str.to_i
end
def self.boolean(str)
case str
when "0" then false
when "1" then true
else
raise "RPC-value of type boolean is wrong"
end
end
def self.double(str)
str.to_f
end
def self.dateTime(str)
case str
when /^(-?\d\d\d\d)-?(\d\d)-?(\d\d)T(\d\d):(\d\d):(\d\d)(?:Z|([+-])(\d\d):?(\d\d))?$/
a = [$1, $2, $3, $4, $5, $6].collect{|i| i.to_i}
if $7
ofs = $8.to_i*3600 + $9.to_i*60
ofs = -ofs if $7=='+'
utc = Time.utc(*a) + ofs
a = [ utc.year, utc.month, utc.day, utc.hour, utc.min, utc.sec ]
end
XMLRPC::DateTime.new(*a)
when /^(-?\d\d)-?(\d\d)-?(\d\d)T(\d\d):(\d\d):(\d\d)(Z|([+-]\d\d):(\d\d))?$/
a = [$1, $2, $3, $4, $5, $6].collect{|i| i.to_i}
if a[0] < 70
a[0] += 2000
else
a[0] += 1900
end
if $7
ofs = $8.to_i*3600 + $9.to_i*60
ofs = -ofs if $7=='+'
utc = Time.utc(*a) + ofs
a = [ utc.year, utc.month, utc.day, utc.hour, utc.min, utc.sec ]
end
XMLRPC::DateTime.new(*a)
else
raise "wrong dateTime.iso8601 format " + str
end
end
def self.base64(str)
XMLRPC::Base64.decode(str)
end
def self.struct(hash)
# convert to marhalled object
klass = hash["___class___"]
if klass.nil? or Config::ENABLE_MARSHALLING == false
hash
else
begin
mod = Module
klass.split("::").each {|const| mod = mod.const_get(const.strip)}
obj = mod.allocate
hash.delete "___class___"
hash.each {|key, value|
obj.instance_variable_set("@#{ key }", value) if key =~ /^([\w_][\w_0-9]*)$/
}
obj
rescue
hash
end
end
end
def self.fault(hash)
if hash.kind_of? Hash and hash.size == 2 and
hash.has_key? "faultCode" and hash.has_key? "faultString" and
hash["faultCode"].kind_of? Integer and hash["faultString"].kind_of? String
XMLRPC::FaultException.new(hash["faultCode"], hash["faultString"])
else
raise "wrong fault-structure: #{hash.inspect}"
end
end
end # module Convert
module XMLParser
class AbstractTreeParser
def parseMethodResponse(str)
methodResponse_document(createCleanedTree(str))
end
def parseMethodCall(str)
methodCall_document(createCleanedTree(str))
end
private
#
# remove all whitespaces but in the tags i4, int, boolean....
# and all comments
#
def removeWhitespacesAndComments(node)
remove = []
childs = node.childNodes.to_a
childs.each do |nd|
case _nodeType(nd)
when :TEXT
# TODO: add nil?
unless %w(i4 int boolean string double dateTime.iso8601 base64).include? node.nodeName
if node.nodeName == "value"
if not node.childNodes.to_a.detect {|n| _nodeType(n) == :ELEMENT}.nil?
remove << nd if nd.nodeValue.strip == ""
end
else
remove << nd if nd.nodeValue.strip == ""
end
end
when :COMMENT
remove << nd
else
removeWhitespacesAndComments(nd)
end
end
remove.each { |i| node.removeChild(i) }
end
def nodeMustBe(node, name)
cmp = case name
when Array
name.include?(node.nodeName)
when String
name == node.nodeName
else
raise "error"
end
if not cmp then
raise "wrong xml-rpc (name)"
end
node
end
#
# returns, when successfully the only child-node
#
def hasOnlyOneChild(node, name=nil)
if node.childNodes.to_a.size != 1
raise "wrong xml-rpc (size)"
end
if name != nil then
nodeMustBe(node.firstChild, name)
end
end
def assert(b)
if not b then
raise "assert-fail"
end
end
# the node `node` has empty string or string
def text_zero_one(node)
nodes = node.childNodes.to_a.size
if nodes == 1
text(node.firstChild)
elsif nodes == 0
""
else
raise "wrong xml-rpc (size)"
end
end
def integer(node)
#TODO: check string for float because to_i returnsa
# 0 when wrong string
nodeMustBe(node, %w(i4 int))
hasOnlyOneChild(node)
Convert.int(text(node.firstChild))
end
def boolean(node)
nodeMustBe(node, "boolean")
hasOnlyOneChild(node)
Convert.boolean(text(node.firstChild))
end
def v_nil(node)
nodeMustBe(node, "nil")
assert( node.childNodes.to_a.size == 0 )
nil
end
def string(node)
nodeMustBe(node, "string")
text_zero_one(node)
end
def double(node)
#TODO: check string for float because to_f returnsa
# 0.0 when wrong string
nodeMustBe(node, "double")
hasOnlyOneChild(node)
Convert.double(text(node.firstChild))
end
def dateTime(node)
nodeMustBe(node, "dateTime.iso8601")
hasOnlyOneChild(node)
Convert.dateTime( text(node.firstChild) )
end
def base64(node)
nodeMustBe(node, "base64")
#hasOnlyOneChild(node)
Convert.base64(text_zero_one(node))
end
def member(node)
nodeMustBe(node, "member")
assert( node.childNodes.to_a.size == 2 )
[ name(node[0]), value(node[1]) ]
end
def name(node)
nodeMustBe(node, "name")
#hasOnlyOneChild(node)
text_zero_one(node)
end
def array(node)
nodeMustBe(node, "array")
hasOnlyOneChild(node, "data")
data(node.firstChild)
end
def data(node)
nodeMustBe(node, "data")
node.childNodes.to_a.collect do |val|
value(val)
end
end
def param(node)
nodeMustBe(node, "param")
hasOnlyOneChild(node, "value")
value(node.firstChild)
end
def methodResponse(node)
nodeMustBe(node, "methodResponse")
hasOnlyOneChild(node, %w(params fault))
child = node.firstChild
case child.nodeName
when "params"
[ true, params(child,false) ]
when "fault"
[ false, fault(child) ]
else
raise "unexpected error"
end
end
def methodName(node)
nodeMustBe(node, "methodName")
hasOnlyOneChild(node)
text(node.firstChild)
end
def params(node, call=true)
nodeMustBe(node, "params")
if call
node.childNodes.to_a.collect do |n|
param(n)
end
else # response (only one param)
hasOnlyOneChild(node)
param(node.firstChild)
end
end
def fault(node)
nodeMustBe(node, "fault")
hasOnlyOneChild(node, "value")
f = value(node.firstChild)
Convert.fault(f)
end
# _nodeType is defined in the subclass
def text(node)
assert( _nodeType(node) == :TEXT )
assert( node.hasChildNodes == false )
assert( node.nodeValue != nil )
node.nodeValue.to_s
end
def struct(node)
nodeMustBe(node, "struct")
hash = {}
node.childNodes.to_a.each do |me|
n, v = member(me)
hash[n] = v
end
Convert.struct(hash)
end
def value(node)
nodeMustBe(node, "value")
nodes = node.childNodes.to_a.size
if nodes == 0
return ""
elsif nodes > 1
raise "wrong xml-rpc (size)"
end
child = node.firstChild
case _nodeType(child)
when :TEXT
text_zero_one(node)
when :ELEMENT
case child.nodeName
when "i4", "int" then integer(child)
when "boolean" then boolean(child)
when "string" then string(child)
when "double" then double(child)
when "dateTime.iso8601" then dateTime(child)
when "base64" then base64(child)
when "struct" then struct(child)
when "array" then array(child)
when "nil"
if Config::ENABLE_NIL_PARSER
v_nil(child)
else
raise "wrong/unknown XML-RPC type 'nil'"
end
else
raise "wrong/unknown XML-RPC type"
end
else
raise "wrong type of node"
end
end
def methodCall(node)
nodeMustBe(node, "methodCall")
assert( (1..2).include?( node.childNodes.to_a.size ) )
name = methodName(node[0])
if node.childNodes.to_a.size == 2 then
pa = params(node[1])
else # no parameters given
pa = []
end
[name, pa]
end
end # module TreeParserMixin
class AbstractStreamParser
def parseMethodResponse(str)
parser = @parser_class.new
parser.parse(str)
raise "No valid method response!" if parser.method_name != nil
if parser.fault != nil
# is a fault structure
[false, parser.fault]
else
# is a normal return value
raise "Missing return value!" if parser.params.size == 0
raise "Too many return values. Only one allowed!" if parser.params.size > 1
[true, parser.params[0]]
end
end
def parseMethodCall(str)
parser = @parser_class.new
parser.parse(str)
raise "No valid method call - missing method name!" if parser.method_name.nil?
[parser.method_name, parser.params]
end
end
module StreamParserMixin
attr_reader :params
attr_reader :method_name
attr_reader :fault
def initialize(*a)
super(*a)
@params = []
@values = []
@val_stack = []
@names = []
@name = []
@structs = []
@struct = {}
@method_name = nil
@fault = nil
@data = nil
end
def startElement(name, attrs=[])
@data = nil
case name
when "value"
@value = nil
when "nil"
raise "wrong/unknown XML-RPC type 'nil'" unless Config::ENABLE_NIL_PARSER
@value = :nil
when "array"
@val_stack << @values
@values = []
when "struct"
@names << @name
@name = []
@structs << @struct
@struct = {}
end
end
def endElement(name)
@data ||= ""
case name
when "string"
@value = @data
when "i4", "int"
@value = Convert.int(@data)
when "boolean"
@value = Convert.boolean(@data)
when "double"
@value = Convert.double(@data)
when "dateTime.iso8601"
@value = Convert.dateTime(@data)
when "base64"
@value = Convert.base64(@data)
when "value"
@value = @data if @value.nil?
@values << (@value == :nil ? nil : @value)
when "array"
@value = @values
@values = @val_stack.pop
when "struct"
@value = Convert.struct(@struct)
@name = @names.pop
@struct = @structs.pop
when "name"
@name[0] = @data
when "member"
@struct[@name[0]] = @values.pop
when "param"
@params << @values[0]
@values = []
when "fault"
@fault = Convert.fault(@values[0])
when "methodName"
@method_name = @data
end
@data = nil
end
def character(data)
if @data
@data << data
else
@data = data
end
end
end # module StreamParserMixin
# ---------------------------------------------------------------------------
class XMLStreamParser < AbstractStreamParser
def initialize
require "xmlparser"
@parser_class = Class.new(::XMLParser) {
include StreamParserMixin
}
end
end # class XMLStreamParser
# ---------------------------------------------------------------------------
class NQXMLStreamParser < AbstractStreamParser
def initialize
require "nqxml/streamingparser"
@parser_class = XMLRPCParser
end
class XMLRPCParser
include StreamParserMixin
def parse(str)
parser = NQXML::StreamingParser.new(str)
parser.each do |ele|
case ele
when NQXML::Text
@data = ele.text
#character(ele.text)
when NQXML::Tag
if ele.isTagEnd
endElement(ele.name)
else
startElement(ele.name, ele.attrs)
end
end
end # do
end # method parse
end # class XMLRPCParser
end # class NQXMLStreamParser
# ---------------------------------------------------------------------------
class XMLTreeParser < AbstractTreeParser
def initialize
require "xmltreebuilder"
# The new XMLParser library (0.6.2+) uses a slightly different DOM implementation.
# The following code removes the differences between both versions.
if defined? XML::DOM::Builder
return if defined? XML::DOM::Node::DOCUMENT # code below has been already executed
klass = XML::DOM::Node
klass.const_set("DOCUMENT", klass::DOCUMENT_NODE)
klass.const_set("TEXT", klass::TEXT_NODE)
klass.const_set("COMMENT", klass::COMMENT_NODE)
klass.const_set("ELEMENT", klass::ELEMENT_NODE)
end
end
private
def _nodeType(node)
tp = node.nodeType
if tp == XML::SimpleTree::Node::TEXT then :TEXT
elsif tp == XML::SimpleTree::Node::COMMENT then :COMMENT
elsif tp == XML::SimpleTree::Node::ELEMENT then :ELEMENT
else :ELSE
end
end
def methodResponse_document(node)
assert( node.nodeType == XML::SimpleTree::Node::DOCUMENT )
hasOnlyOneChild(node, "methodResponse")
methodResponse(node.firstChild)
end
def methodCall_document(node)
assert( node.nodeType == XML::SimpleTree::Node::DOCUMENT )
hasOnlyOneChild(node, "methodCall")
methodCall(node.firstChild)
end
def createCleanedTree(str)
doc = XML::SimpleTreeBuilder.new.parse(str)
doc.documentElement.normalize
removeWhitespacesAndComments(doc)
doc
end
end # class XMLParser
# ---------------------------------------------------------------------------
class NQXMLTreeParser < AbstractTreeParser
def initialize
require "nqxml/treeparser"
end
private
def _nodeType(node)
node.nodeType
end
def methodResponse_document(node)
methodResponse(node)
end
def methodCall_document(node)
methodCall(node)
end
def createCleanedTree(str)
doc = ::NQXML::TreeParser.new(str).document.rootNode
removeWhitespacesAndComments(doc)
doc
end
end # class NQXMLTreeParser
# ---------------------------------------------------------------------------
class REXMLStreamParser < AbstractStreamParser
def initialize
require "rexml/document"
@parser_class = StreamListener
end
class StreamListener
include StreamParserMixin
alias :tag_start :startElement
alias :tag_end :endElement
alias :text :character
alias :cdata :character
def method_missing(*a)
# ignore
end
def parse(str)
parser = REXML::Document.parse_stream(str, self)
end
end
end
# ---------------------------------------------------------------------------
class XMLScanStreamParser < AbstractStreamParser
def initialize
require "xmlscan/parser"
@parser_class = XMLScanParser
end
class XMLScanParser
include StreamParserMixin
Entities = {
"lt" => "<",
"gt" => ">",
"amp" => "&",
"quot" => '"',
"apos" => "'"
}
def parse(str)
parser = XMLScan::XMLParser.new(self)
parser.parse(str)
end
alias :on_stag :startElement
alias :on_etag :endElement
def on_stag_end(name); end
def on_stag_end_empty(name)
startElement(name)
endElement(name)
end
def on_chardata(str)
character(str)
end
def on_cdata(str)
character(str)
end
def on_entityref(ent)
str = Entities[ent]
if str
character(str)
else
raise "unknown entity"
end
end
def on_charref(code)
character(code.chr)
end
def on_charref_hex(code)
character(code.chr)
end
def method_missing(*a)
end
# TODO: call/implement?
# valid_name?
# valid_chardata?
# valid_char?
# parse_error
end
end
# ---------------------------------------------------------------------------
XMLParser = XMLTreeParser
NQXMLParser = NQXMLTreeParser
Classes = [XMLStreamParser, XMLTreeParser,
NQXMLStreamParser, NQXMLTreeParser,
REXMLStreamParser, XMLScanStreamParser]
# yields an instance of each installed parser
def self.each_installed_parser
XMLRPC::XMLParser::Classes.each do |klass|
begin
yield klass.new
rescue LoadError
end
end
end
end # module XMLParser
end # module XMLRPC
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xmlrpc/base64.rb | tools/jruby-1.5.1/lib/ruby/1.8/xmlrpc/base64.rb | =begin
= xmlrpc/base64.rb
Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de)
Released under the same term of license as Ruby.
= Classes
* ((<XMLRPC::Base64>))
= XMLRPC::Base64
== Description
This class is necessary for (('xmlrpc4r')) to determine that a string should
be transmitted base64-encoded and not as a raw-string.
You can use (({XMLRPC::Base64})) on the client and server-side as a
parameter and/or return-value.
== Class Methods
--- XMLRPC::Base64.new( str, state = :dec )
Creates a new (({XMLRPC::Base64})) instance with string ((|str|)) as the
internal string. When ((|state|)) is (({:dec})) it assumes that the
string ((|str|)) is not in base64 format (perhaps already decoded),
otherwise if ((|state|)) is (({:enc})) it decodes ((|str|))
and stores it as the internal string.
--- XMLRPC::Base64.decode( str )
Decodes string ((|str|)) with base64 and returns that value.
--- XMLRPC::Base64.encode( str )
Encodes string ((|str|)) with base64 and returns that value.
== Instance Methods
--- XMLRPC::Base64#decoded
Returns the internal string decoded.
--- XMLRPC::Base64#encoded
Returns the internal string encoded with base64.
=end
module XMLRPC
class Base64
def initialize(str, state = :dec)
case state
when :enc
@str = Base64.decode(str)
when :dec
@str = str
else
raise ArgumentError, "wrong argument; either :enc or :dec"
end
end
def decoded
@str
end
def encoded
Base64.encode(@str)
end
def Base64.decode(str)
str.gsub(/\s+/, "").unpack("m")[0]
end
def Base64.encode(str)
[str].pack("m")
end
end
end # module XMLRPC
=begin
= History
$Id: base64.rb 11708 2007-02-12 23:01:19Z shyouhei $
=end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xmlrpc/create.rb | tools/jruby-1.5.1/lib/ruby/1.8/xmlrpc/create.rb | #
# Creates XML-RPC call/response documents
#
# Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de)
#
# $Id: create.rb 11818 2007-02-23 03:45:55Z knu $
#
require "date"
require "xmlrpc/base64"
module XMLRPC
module XMLWriter
class Abstract
def ele(name, *children)
element(name, nil, *children)
end
def tag(name, txt)
element(name, nil, text(txt))
end
end
class Simple < Abstract
def document_to_str(doc)
doc
end
def document(*params)
params.join("")
end
def pi(name, *params)
"<?#{name} " + params.join(" ") + " ?>"
end
def element(name, attrs, *children)
raise "attributes not yet implemented" unless attrs.nil?
if children.empty?
"<#{name}/>"
else
"<#{name}>" + children.join("") + "</#{name}>"
end
end
def text(txt)
cleaned = txt.dup
cleaned.gsub!(/&/, '&')
cleaned.gsub!(/</, '<')
cleaned.gsub!(/>/, '>')
cleaned
end
end # class Simple
class XMLParser < Abstract
def initialize
require "xmltreebuilder"
end
def document_to_str(doc)
doc.to_s
end
def document(*params)
XML::SimpleTree::Document.new(*params)
end
def pi(name, *params)
XML::SimpleTree::ProcessingInstruction.new(name, *params)
end
def element(name, attrs, *children)
XML::SimpleTree::Element.new(name, attrs, *children)
end
def text(txt)
XML::SimpleTree::Text.new(txt)
end
end # class XMLParser
Classes = [Simple, XMLParser]
# yields an instance of each installed XML writer
def self.each_installed_writer
XMLRPC::XMLWriter::Classes.each do |klass|
begin
yield klass.new
rescue LoadError
end
end
end
end # module XMLWriter
class Create
def initialize(xml_writer = nil)
@writer = xml_writer || Config::DEFAULT_WRITER.new
end
def methodCall(name, *params)
name = name.to_s
if name !~ /[a-zA-Z0-9_.:\/]+/
raise ArgumentError, "Wrong XML-RPC method-name"
end
parameter = params.collect do |param|
@writer.ele("param", conv2value(param))
end
tree = @writer.document(
@writer.pi("xml", 'version="1.0"'),
@writer.ele("methodCall",
@writer.tag("methodName", name),
@writer.ele("params", *parameter)
)
)
@writer.document_to_str(tree) + "\n"
end
#
# generates a XML-RPC methodResponse document
#
# if is_ret == false then the params array must
# contain only one element, which is a structure
# of a fault return-value.
#
# if is_ret == true then a normal
# return-value of all the given params is created.
#
def methodResponse(is_ret, *params)
if is_ret
resp = params.collect do |param|
@writer.ele("param", conv2value(param))
end
resp = [@writer.ele("params", *resp)]
else
if params.size != 1 or params[0] === XMLRPC::FaultException
raise ArgumentError, "no valid fault-structure given"
end
resp = @writer.ele("fault", conv2value(params[0].to_h))
end
tree = @writer.document(
@writer.pi("xml", 'version="1.0"'),
@writer.ele("methodResponse", resp)
)
@writer.document_to_str(tree) + "\n"
end
#####################################
private
#####################################
#
# converts a Ruby object into
# a XML-RPC <value> tag
#
def conv2value(param)
val = case param
when Fixnum
@writer.tag("i4", param.to_s)
when Bignum
if Config::ENABLE_BIGINT
@writer.tag("i4", param.to_s)
else
if param >= -(2**31) and param <= (2**31-1)
@writer.tag("i4", param.to_s)
else
raise "Bignum is too big! Must be signed 32-bit integer!"
end
end
when TrueClass, FalseClass
@writer.tag("boolean", param ? "1" : "0")
when String
@writer.tag("string", param)
when Symbol
@writer.tag("string", param.to_s)
when NilClass
if Config::ENABLE_NIL_CREATE
@writer.ele("nil")
else
raise "Wrong type NilClass. Not allowed!"
end
when Float
@writer.tag("double", param.to_s)
when Struct
h = param.members.collect do |key|
value = param[key]
@writer.ele("member",
@writer.tag("name", key.to_s),
conv2value(value)
)
end
@writer.ele("struct", *h)
when Hash
# TODO: can a Hash be empty?
h = param.collect do |key, value|
@writer.ele("member",
@writer.tag("name", key.to_s),
conv2value(value)
)
end
@writer.ele("struct", *h)
when Array
# TODO: can an Array be empty?
a = param.collect {|v| conv2value(v) }
@writer.ele("array",
@writer.ele("data", *a)
)
when Time, Date, ::DateTime
@writer.tag("dateTime.iso8601", param.strftime("%Y%m%dT%H:%M:%S"))
when XMLRPC::DateTime
@writer.tag("dateTime.iso8601",
format("%.4d%02d%02dT%02d:%02d:%02d", *param.to_a))
when XMLRPC::Base64
@writer.tag("base64", param.encoded)
else
if Config::ENABLE_MARSHALLING and param.class.included_modules.include? XMLRPC::Marshallable
# convert Ruby object into Hash
ret = {"___class___" => param.class.name}
param.instance_variables.each {|v|
name = v[1..-1]
val = param.instance_variable_get(v)
if val.nil?
ret[name] = val if Config::ENABLE_NIL_CREATE
else
ret[name] = val
end
}
return conv2value(ret)
else
ok, pa = wrong_type(param)
if ok
return conv2value(pa)
else
raise "Wrong type!"
end
end
end
@writer.ele("value", val)
end
def wrong_type(value)
false
end
end # class Create
end # module XMLRPC
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xmlrpc/client.rb | tools/jruby-1.5.1/lib/ruby/1.8/xmlrpc/client.rb | =begin
= xmlrpc/client.rb
Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de)
Released under the same term of license as Ruby.
= Classes
* ((<XMLRPC::Client>))
* ((<XMLRPC::Client::Proxy>))
= XMLRPC::Client
== Synopsis
require "xmlrpc/client"
server = XMLRPC::Client.new("www.ruby-lang.org", "/RPC2", 80)
begin
param = server.call("michael.add", 4, 5)
puts "4 + 5 = #{param}"
rescue XMLRPC::FaultException => e
puts "Error:"
puts e.faultCode
puts e.faultString
end
or
require "xmlrpc/client"
server = XMLRPC::Client.new("www.ruby-lang.org", "/RPC2", 80)
ok, param = server.call2("michael.add", 4, 5)
if ok then
puts "4 + 5 = #{param}"
else
puts "Error:"
puts param.faultCode
puts param.faultString
end
== Description
Class (({XMLRPC::Client})) provides remote procedure calls to a XML-RPC server.
After setting the connection-parameters with ((<XMLRPC::Client.new>)) which
creates a new (({XMLRPC::Client})) instance, you can execute a remote procedure
by sending the ((<call|XMLRPC::Client#call>)) or ((<call2|XMLRPC::Client#call2>))
message to this new instance. The given parameters indicate which method to
call on the remote-side and of course the parameters for the remote procedure.
== Class Methods
--- XMLRPC::Client.new( host=nil, path=nil, port=nil, proxy_host=nil, proxy_port=nil, user=nil, password=nil, use_ssl=false, timeout =nil)
Creates an object which represents the remote XML-RPC server on the
given host ((|host|)). If the server is CGI-based, ((|path|)) is the
path to the CGI-script, which will be called, otherwise (in the
case of a standalone server) ((|path|)) should be (({"/RPC2"})).
((|port|)) is the port on which the XML-RPC server listens.
If ((|proxy_host|)) is given, then a proxy server listening at
((|proxy_host|)) is used. ((|proxy_port|)) is the port of the
proxy server.
Default values for ((|host|)), ((|path|)) and ((|port|)) are 'localhost', '/RPC2' and
'80' respectively using SSL '443'.
If ((|user|)) and ((|password|)) are given, each time a request is send,
a Authorization header is send. Currently only Basic Authentification is
implemented no Digest.
If ((|use_ssl|)) is set to (({true})), comunication over SSL is enabled.
Note, that you need the SSL package from RAA installed.
Parameter ((|timeout|)) is the time to wait for a XML-RPC response, defaults to 30.
--- XMLRPC::Client.new2( uri, proxy=nil, timeout=nil)
--- XMLRPC::Client.new_from_uri( uri, proxy=nil, timeout=nil)
: uri
URI specifying protocol (http or https), host, port, path, user and password.
Example: https://user:password@host:port/path
: proxy
Is of the form "host:port".
: timeout
Defaults to 30.
--- XMLRPC::Client.new3( hash={} )
--- XMLRPC::Client.new_from_hash( hash={} )
Parameter ((|hash|)) has following case-insensitive keys:
* host
* path
* port
* proxy_host
* proxy_port
* user
* password
* use_ssl
* timeout
Calls ((<XMLRPC::Client.new>)) with the corresponding values.
== Instance Methods
--- XMLRPC::Client#call( method, *args )
Invokes the method named ((|method|)) with the parameters given by
((|args|)) on the XML-RPC server.
The parameter ((|method|)) is converted into a (({String})) and should
be a valid XML-RPC method-name.
Each parameter of ((|args|)) must be of one of the following types,
where (({Hash})), (({Struct})) and (({Array})) can contain any of these listed ((:types:)):
* (({Fixnum})), (({Bignum}))
* (({TrueClass})), (({FalseClass})) ((({true})), (({false})))
* (({String})), (({Symbol}))
* (({Float}))
* (({Hash})), (({Struct}))
* (({Array}))
* (({Date})), (({Time})), (({XMLRPC::DateTime}))
* (({XMLRPC::Base64}))
* A Ruby object which class includes XMLRPC::Marshallable (only if Config::ENABLE_MARSHALLABLE is (({true}))).
That object is converted into a hash, with one additional key/value pair "___class___" which contains the class name
for restoring later that object.
The method returns the return-value from the RPC
((-stands for Remote Procedure Call-)).
The type of the return-value is one of the above shown,
only that a (({Bignum})) is only allowed when it fits in 32-bit and
that a XML-RPC (('dateTime.iso8601')) type is always returned as
a ((<(({XMLRPC::DateTime}))|URL:datetime.html>)) object and
a (({Struct})) is never returned, only a (({Hash})), the same for a (({Symbol})), where
always a (({String})) is returned.
A (({XMLRPC::Base64})) is returned as a (({String})) from xmlrpc4r version 1.6.1 on.
If the remote procedure returned a fault-structure, then a
(({XMLRPC::FaultException})) exception is raised, which has two accessor-methods
(({faultCode})) and (({faultString})) of type (({Integer})) and (({String})).
--- XMLRPC::Client#call2( method, *args )
The difference between this method and ((<call|XMLRPC::Client#call>)) is, that
this method do ((*not*)) raise a (({XMLRPC::FaultException})) exception.
The method returns an array of two values. The first value indicates if
the second value is a return-value ((({true}))) or an object of type
(({XMLRPC::FaultException})).
Both are explained in ((<call|XMLRPC::Client#call>)).
Simple to remember: The "2" in "call2" denotes the number of values it returns.
--- XMLRPC::Client#multicall( *methods )
You can use this method to execute several methods on a XMLRPC server which supports
the multi-call extension.
Example:
s.multicall(
['michael.add', 3, 4],
['michael.sub', 4, 5]
)
# => [7, -1]
--- XMLRPC::Client#multicall2( *methods )
Same as ((<XMLRPC::Client#multicall>)), but returns like ((<XMLRPC::Client#call2>)) two parameters
instead of raising an (({XMLRPC::FaultException})).
--- XMLRPC::Client#proxy( prefix, *args )
Returns an object of class (({XMLRPC::Client::Proxy})), initialized with
((|prefix|)) and ((|args|)). A proxy object returned by this method behaves
like ((<XMLRPC::Client#call>)), i.e. a call on that object will raise a
(({XMLRPC::FaultException})) when a fault-structure is returned by that call.
--- XMLRPC::Client#proxy2( prefix, *args )
Almost the same like ((<XMLRPC::Client#proxy>)) only that a call on the returned
(({XMLRPC::Client::Proxy})) object behaves like ((<XMLRPC::Client#call2>)), i.e.
a call on that object will return two parameters.
--- XMLRPC::Client#call_async(...)
--- XMLRPC::Client#call2_async(...)
--- XMLRPC::Client#multicall_async(...)
--- XMLRPC::Client#multicall2_async(...)
--- XMLRPC::Client#proxy_async(...)
--- XMLRPC::Client#proxy2_async(...)
In contrast to corresponding methods without "_async", these can be
called concurrently and use for each request a new connection, where the
non-asynchronous counterparts use connection-alive (one connection for all requests)
if possible.
Note, that you have to use Threads to call these methods concurrently.
The following example calls two methods concurrently:
Thread.new {
p client.call_async("michael.add", 4, 5)
}
Thread.new {
p client.call_async("michael.div", 7, 9)
}
--- XMLRPC::Client#timeout
--- XMLRPC::Client#user
--- XMLRPC::Client#password
Return the corresponding attributes.
--- XMLRPC::Client#timeout= (new_timeout)
--- XMLRPC::Client#user= (new_user)
--- XMLRPC::Client#password= (new_password)
Set the corresponding attributes.
--- XMLRPC::Client#set_writer( writer )
Sets the XML writer to use for generating XML output.
Should be an instance of a class from module (({XMLRPC::XMLWriter})).
If this method is not called, then (({XMLRPC::Config::DEFAULT_WRITER})) is used.
--- XMLRPC::Client#set_parser( parser )
Sets the XML parser to use for parsing XML documents.
Should be an instance of a class from module (({XMLRPC::XMLParser})).
If this method is not called, then (({XMLRPC::Config::DEFAULT_PARSER})) is used.
--- XMLRPC::Client#cookie
--- XMLRPC::Client#cookie= (cookieString)
Get and set the HTTP Cookie header.
--- XMLRPC::Client#http_header_extra= (additionalHeaders)
Set extra HTTP headers that are included in the request.
--- XMLRPC::Client#http_header_extra
Access the via ((<XMLRPC::Client#http_header_extra=>)) assigned header.
--- XMLRPC::Client#http_last_response
Returns the (({Net::HTTPResponse})) object of the last RPC.
= XMLRPC::Client::Proxy
== Synopsis
require "xmlrpc/client"
server = XMLRPC::Client.new("www.ruby-lang.org", "/RPC2", 80)
michael = server.proxy("michael")
michael2 = server.proxy("michael", 4)
# both calls should return the same value '9'.
p michael.add(4,5)
p michael2.add(5)
== Description
Class (({XMLRPC::Client::Proxy})) makes XML-RPC calls look nicer!
You can call any method onto objects of that class - the object handles
(({method_missing})) and will forward the method call to a XML-RPC server.
Don't use this class directly, but use instead method ((<XMLRPC::Client#proxy>)) or
((<XMLRPC::Client#proxy2>)).
== Class Methods
--- XMLRPC::Client::Proxy.new( server, prefix, args=[], meth=:call, delim="." )
Creates an object which provides (({method_missing})).
((|server|)) must be of type (({XMLRPC::Client})), which is the XML-RPC server to be used
for a XML-RPC call. ((|prefix|)) and ((|delim|)) will be prepended to the methodname
called onto this object.
Parameter ((|meth|)) is the method (call, call2, call_async, call2_async) to use for
a RPC.
((|args|)) are arguments which are automatically given
to every XML-RPC call before the arguments provides through (({method_missing})).
== Instance Methods
Every method call is forwarded to the XML-RPC server defined in ((<new|XMLRPC::Client::Proxy#new>)).
Note: Inherited methods from class (({Object})) cannot be used as XML-RPC names, because they get around
(({method_missing})).
= History
$Id: client.rb 18091 2008-07-16 17:07:44Z shyouhei $
=end
require "xmlrpc/parser"
require "xmlrpc/create"
require "xmlrpc/config"
require "xmlrpc/utils" # ParserWriterChooseMixin
require "net/http"
module XMLRPC
class Client
USER_AGENT = "XMLRPC::Client (Ruby #{RUBY_VERSION})"
include ParserWriterChooseMixin
include ParseContentType
# Constructors -------------------------------------------------------------------
def initialize(host=nil, path=nil, port=nil, proxy_host=nil, proxy_port=nil,
user=nil, password=nil, use_ssl=nil, timeout=nil)
@http_header_extra = nil
@http_last_response = nil
@cookie = nil
@host = host || "localhost"
@path = path || "/RPC2"
@proxy_host = proxy_host
@proxy_port = proxy_port
@proxy_host ||= 'localhost' if @proxy_port != nil
@proxy_port ||= 8080 if @proxy_host != nil
@use_ssl = use_ssl || false
@timeout = timeout || 30
if use_ssl
require "net/https"
@port = port || 443
else
@port = port || 80
end
@user, @password = user, password
set_auth
# convert ports to integers
@port = @port.to_i if @port != nil
@proxy_port = @proxy_port.to_i if @proxy_port != nil
# HTTP object for synchronous calls
Net::HTTP.version_1_2
@http = Net::HTTP.new(@host, @port, @proxy_host, @proxy_port)
@http.use_ssl = @use_ssl if @use_ssl
@http.read_timeout = @timeout
@http.open_timeout = @timeout
@parser = nil
@create = nil
end
class << self
def new2(uri, proxy=nil, timeout=nil)
if match = /^([^:]+):\/\/(([^@]+)@)?([^\/]+)(\/.*)?$/.match(uri)
proto = match[1]
user, passwd = (match[3] || "").split(":")
host, port = match[4].split(":")
path = match[5]
if proto != "http" and proto != "https"
raise "Wrong protocol specified. Only http or https allowed!"
end
else
raise "Wrong URI as parameter!"
end
proxy_host, proxy_port = (proxy || "").split(":")
self.new(host, path, port, proxy_host, proxy_port, user, passwd, (proto == "https"), timeout)
end
alias new_from_uri new2
def new3(hash={})
# convert all keys into lowercase strings
h = {}
hash.each { |k,v| h[k.to_s.downcase] = v }
self.new(h['host'], h['path'], h['port'], h['proxy_host'], h['proxy_port'], h['user'], h['password'],
h['use_ssl'], h['timeout'])
end
alias new_from_hash new3
end
# Attribute Accessors -------------------------------------------------------------------
# add additional HTTP headers to the request
attr_accessor :http_header_extra
# makes last HTTP response accessible
attr_reader :http_last_response
# Cookie support
attr_accessor :cookie
attr_reader :timeout, :user, :password
def timeout=(new_timeout)
@timeout = new_timeout
@http.read_timeout = @timeout
@http.open_timeout = @timeout
end
def user=(new_user)
@user = new_user
set_auth
end
def password=(new_password)
@password = new_password
set_auth
end
# Call methods --------------------------------------------------------------
def call(method, *args)
ok, param = call2(method, *args)
if ok
param
else
raise param
end
end
def call2(method, *args)
request = create().methodCall(method, *args)
data = do_rpc(request, false)
parser().parseMethodResponse(data)
end
def call_async(method, *args)
ok, param = call2_async(method, *args)
if ok
param
else
raise param
end
end
def call2_async(method, *args)
request = create().methodCall(method, *args)
data = do_rpc(request, true)
parser().parseMethodResponse(data)
end
# Multicall methods --------------------------------------------------------------
def multicall(*methods)
ok, params = multicall2(*methods)
if ok
params
else
raise params
end
end
def multicall2(*methods)
gen_multicall(methods, false)
end
def multicall_async(*methods)
ok, params = multicall2_async(*methods)
if ok
params
else
raise params
end
end
def multicall2_async(*methods)
gen_multicall(methods, true)
end
# Proxy generating methods ------------------------------------------
def proxy(prefix=nil, *args)
Proxy.new(self, prefix, args, :call)
end
def proxy2(prefix=nil, *args)
Proxy.new(self, prefix, args, :call2)
end
def proxy_async(prefix=nil, *args)
Proxy.new(self, prefix, args, :call_async)
end
def proxy2_async(prefix=nil, *args)
Proxy.new(self, prefix, args, :call2_async)
end
private # ----------------------------------------------------------
def set_auth
if @user.nil?
@auth = nil
else
a = "#@user"
a << ":#@password" if @password != nil
@auth = ("Basic " + [a].pack("m")).chomp
end
end
def do_rpc(request, async=false)
header = {
"User-Agent" => USER_AGENT,
"Content-Type" => "text/xml; charset=utf-8",
"Content-Length" => request.size.to_s,
"Connection" => (async ? "close" : "keep-alive")
}
header["Cookie"] = @cookie if @cookie
header.update(@http_header_extra) if @http_header_extra
if @auth != nil
# add authorization header
header["Authorization"] = @auth
end
resp = nil
@http_last_response = nil
if async
# use a new HTTP object for each call
Net::HTTP.version_1_2
http = Net::HTTP.new(@host, @port, @proxy_host, @proxy_port)
http.use_ssl = @use_ssl if @use_ssl
http.read_timeout = @timeout
http.open_timeout = @timeout
# post request
http.start {
resp = http.post2(@path, request, header)
}
else
# reuse the HTTP object for each call => connection alive is possible
# we must start connection explicitely first time so that http.request
# does not assume that we don't want keepalive
@http.start if not @http.started?
# post request
resp = @http.post2(@path, request, header)
end
@http_last_response = resp
data = resp.body
if resp.code == "401"
# Authorization Required
raise "Authorization failed.\nHTTP-Error: #{resp.code} #{resp.message}"
elsif resp.code[0,1] != "2"
raise "HTTP-Error: #{resp.code} #{resp.message}"
end
ct = parse_content_type(resp["Content-Type"]).first
if ct != "text/xml"
if ct == "text/html"
raise "Wrong content-type (received '#{ct}' but expected 'text/xml'): \n#{data}"
else
raise "Wrong content-type (received '#{ct}' but expected 'text/xml')"
end
end
expected = resp["Content-Length"] || "<unknown>"
if data.nil? or data.size == 0
raise "Wrong size. Was #{data.size}, should be #{expected}"
elsif expected != "<unknown>" and expected.to_i != data.size and resp["Transfer-Encoding"].nil?
raise "Wrong size. Was #{data.size}, should be #{expected}"
end
set_cookies = resp.get_fields("Set-Cookie")
if set_cookies and !set_cookies.empty?
require 'webrick/cookie'
@cookie = set_cookies.collect do |set_cookie|
cookie = WEBrick::Cookie.parse_set_cookie(set_cookie)
WEBrick::Cookie.new(cookie.name, cookie.value).to_s
end.join("; ")
end
return data
end
def gen_multicall(methods=[], async=false)
meth = :call2
meth = :call2_async if async
ok, params = self.send(meth, "system.multicall",
methods.collect {|m| {'methodName' => m[0], 'params' => m[1..-1]} }
)
if ok
params = params.collect do |param|
if param.is_a? Array
param[0]
elsif param.is_a? Hash
XMLRPC::FaultException.new(param["faultCode"], param["faultString"])
else
raise "Wrong multicall return value"
end
end
end
return ok, params
end
class Proxy
def initialize(server, prefix, args=[], meth=:call, delim=".")
@server = server
@prefix = prefix ? prefix + delim : ""
@args = args
@meth = meth
end
def method_missing(mid, *args)
pre = @prefix + mid.to_s
arg = @args + args
@server.send(@meth, pre, *arg)
end
end # class Proxy
end # class Client
end # module XMLRPC
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xmlrpc/config.rb | tools/jruby-1.5.1/lib/ruby/1.8/xmlrpc/config.rb | #
# $Id: config.rb 11708 2007-02-12 23:01:19Z shyouhei $
# Configuration file for XML-RPC for Ruby
#
module XMLRPC
module Config
DEFAULT_WRITER = XMLWriter::Simple # or XMLWriter::XMLParser
# available parser:
# * XMLParser::NQXMLTreeParser
# * XMLParser::NQXMLStreamParser
# * XMLParser::XMLTreeParser
# * XMLParser::XMLStreamParser (fastest)
# * XMLParser::REXMLStreamParser
# * XMLParser::XMLScanStreamParser
DEFAULT_PARSER = XMLParser::REXMLStreamParser
# enable <nil/> tag
ENABLE_NIL_CREATE = false
ENABLE_NIL_PARSER = false
# allows integers greater than 32-bit if true
ENABLE_BIGINT = false
# enable marshalling ruby objects which include XMLRPC::Marshallable
ENABLE_MARSHALLING = true
# enable multiCall extension by default
ENABLE_MULTICALL = false
# enable Introspection extension by default
ENABLE_INTROSPECTION = false
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xmlrpc/server.rb | tools/jruby-1.5.1/lib/ruby/1.8/xmlrpc/server.rb | =begin
= xmlrpc/server.rb
Copyright (C) 2001, 2002, 2003, 2005 by Michael Neumann (mneumann@ntecs.de)
Released under the same term of license as Ruby.
= Classes
* ((<XMLRPC::BasicServer>))
* ((<XMLRPC::CGIServer>))
* ((<XMLRPC::ModRubyServer>))
* ((<XMLRPC::Server>))
* ((<XMLRPC::WEBrickServlet>))
= XMLRPC::BasicServer
== Description
Is the base class for all XML-RPC server-types (CGI, standalone).
You can add handler and set a default handler.
Do not use this server, as this is/should be an abstract class.
=== How the method to call is found
The arity (number of accepted arguments) of a handler (method or (({Proc})) object) is
compared to the given arguments submitted by the client for a RPC ((-Remote Procedure Call-)).
A handler is only called if it accepts the number of arguments, otherwise the search
for another handler will go on. When at the end no handler was found,
the ((<default_handler|XMLRPC::BasicServer#set_default_handler>)) will be called.
With this technique it is possible to do overloading by number of parameters, but
only for (({Proc})) handler, because you cannot define two methods of the same name in
the same class.
== Class Methods
--- XMLRPC::BasicServer.new( class_delim="." )
Creates a new (({XMLRPC::BasicServer})) instance, which should not be
done, because (({XMLRPC::BasicServer})) is an abstract class. This
method should be called from a subclass indirectly by a (({super})) call
in the method (({initialize})). The paramter ((|class_delim|)) is used
in ((<add_handler|XMLRPC::BasicServer#add_handler>)) when an object is
added as handler, to delimit the object-prefix and the method-name.
== Instance Methods
--- XMLRPC::BasicServer#add_handler( name, signature=nil, help=nil ) { aBlock }
Adds ((|aBlock|)) to the list of handlers, with ((|name|)) as the name of the method.
Parameters ((|signature|)) and ((|help|)) are used by the Introspection method if specified,
where ((|signature|)) is either an Array containing strings each representing a type of it's
signature (the first is the return value) or an Array of Arrays if the method has multiple
signatures. Value type-names are "int, boolean, double, string, dateTime.iso8601, base64, array, struct".
Parameter ((|help|)) is a String with informations about how to call this method etc.
A handler method or code-block can return the types listed at
((<XMLRPC::Client#call|URL:client.html#index:0>)).
When a method fails, it can tell it the client by throwing an
(({XMLRPC::FaultException})) like in this example:
s.add_handler("michael.div") do |a,b|
if b == 0
raise XMLRPC::FaultException.new(1, "division by zero")
else
a / b
end
end
The client gets in the case of (({b==0})) an object back of type
(({XMLRPC::FaultException})) that has a ((|faultCode|)) and ((|faultString|))
field.
--- XMLRPC::BasicServer#add_handler( prefix, obj )
This is the second form of ((<add_handler|XMLRPC::BasicServer#add_handler>)).
To add an object write:
server.add_handler("michael", MyHandlerClass.new)
All public methods of (({MyHandlerClass})) are accessible to
the XML-RPC clients by (('michael."name of method"')). This is
where the ((|class_delim|)) in ((<new|XMLRPC::BasicServer.new>))
has it's role, a XML-RPC method-name is defined by
((|prefix|)) + ((|class_delim|)) + (('"name of method"')).
--- XMLRPC::BasicServer#add_handler( interface, obj )
This is the third form of ((<add_handler|XMLRPC::BasicServer#add_handler>)).
Use (({XMLRPC::interface})) to generate an ServiceInterface object, which
represents an interface (with signature and help text) for a handler class.
Parameter ((|interface|)) must be of type (({XMLRPC::ServiceInterface})).
Adds all methods of ((|obj|)) which are defined in ((|interface|)) to the
server.
This is the recommended way of adding services to a server!
--- XMLRPC::BasicServer#get_default_handler
Returns the default-handler, which is called when no handler for
a method-name is found.
It is a (({Proc})) object or (({nil})).
--- XMLRPC::BasicServer#set_default_handler ( &handler )
Sets ((|handler|)) as the default-handler, which is called when
no handler for a method-name is found. ((|handler|)) is a code-block.
The default-handler is called with the (XML-RPC) method-name as first argument, and
the other arguments are the parameters given by the client-call.
If no block is specified the default of (({XMLRPC::BasicServer})) is used, which raises a
XMLRPC::FaultException saying "method missing".
--- XMLRPC::BasicServer#set_writer( writer )
Sets the XML writer to use for generating XML output.
Should be an instance of a class from module (({XMLRPC::XMLWriter})).
If this method is not called, then (({XMLRPC::Config::DEFAULT_WRITER})) is used.
--- XMLRPC::BasicServer#set_parser( parser )
Sets the XML parser to use for parsing XML documents.
Should be an instance of a class from module (({XMLRPC::XMLParser})).
If this method is not called, then (({XMLRPC::Config::DEFAULT_PARSER})) is used.
--- XMLRPC::BasicServer#add_introspection
Adds the introspection handlers "system.listMethods", "system.methodSignature" and "system.methodHelp",
where only the first one works.
--- XMLRPC::BasicServer#add_multicall
Adds the multi-call handler "system.multicall".
--- XMLRPC::BasicServer#get_service_hook
Returns the service-hook, which is called on each service request (RPC) unless it's (({nil})).
--- XMLRPC::BasicServer#set_service_hook ( &handler )
A service-hook is called for each service request (RPC).
You can use a service-hook for example to wrap existing methods and catch exceptions of them or
convert values to values recognized by XMLRPC. You can disable it by passing (({nil})) as parameter
((|handler|)) .
The service-hook is called with a (({Proc})) object and with the parameters for this (({Proc})).
An example:
server.set_service_hook {|obj, *args|
begin
ret = obj.call(*args) # call the original service-method
# could convert the return value
resuce
# rescue exceptions
end
}
=end
require "xmlrpc/parser"
require "xmlrpc/create"
require "xmlrpc/config"
require "xmlrpc/utils" # ParserWriterChooseMixin
module XMLRPC
class BasicServer
include ParserWriterChooseMixin
include ParseContentType
ERR_METHOD_MISSING = 1
ERR_UNCAUGHT_EXCEPTION = 2
ERR_MC_WRONG_PARAM = 3
ERR_MC_MISSING_PARAMS = 4
ERR_MC_MISSING_METHNAME = 5
ERR_MC_RECURSIVE_CALL = 6
ERR_MC_WRONG_PARAM_PARAMS = 7
ERR_MC_EXPECTED_STRUCT = 8
def initialize(class_delim=".")
@handler = []
@default_handler = nil
@service_hook = nil
@class_delim = class_delim
@create = nil
@parser = nil
add_multicall if Config::ENABLE_MULTICALL
add_introspection if Config::ENABLE_INTROSPECTION
end
def add_handler(prefix, obj_or_signature=nil, help=nil, &block)
if block_given?
# proc-handler
@handler << [prefix, block, obj_or_signature, help]
else
if prefix.kind_of? String
# class-handler
raise ArgumentError, "Expected non-nil value" if obj_or_signature.nil?
@handler << [prefix + @class_delim, obj_or_signature]
elsif prefix.kind_of? XMLRPC::Service::BasicInterface
# class-handler with interface
# add all methods
@handler += prefix.get_methods(obj_or_signature, @class_delim)
else
raise ArgumentError, "Wrong type for parameter 'prefix'"
end
end
self
end
def get_service_hook
@service_hook
end
def set_service_hook(&handler)
@service_hook = handler
self
end
def get_default_handler
@default_handler
end
def set_default_handler (&handler)
@default_handler = handler
self
end
def add_multicall
add_handler("system.multicall", %w(array array), "Multicall Extension") do |arrStructs|
unless arrStructs.is_a? Array
raise XMLRPC::FaultException.new(ERR_MC_WRONG_PARAM, "system.multicall expects an array")
end
arrStructs.collect {|call|
if call.is_a? Hash
methodName = call["methodName"]
params = call["params"]
if params.nil?
multicall_fault(ERR_MC_MISSING_PARAMS, "Missing params")
elsif methodName.nil?
multicall_fault(ERR_MC_MISSING_METHNAME, "Missing methodName")
else
if methodName == "system.multicall"
multicall_fault(ERR_MC_RECURSIVE_CALL, "Recursive system.multicall forbidden")
else
unless params.is_a? Array
multicall_fault(ERR_MC_WRONG_PARAM_PARAMS, "Parameter params have to be an Array")
else
ok, val = call_method(methodName, *params)
if ok
# correct return value
[val]
else
# exception
multicall_fault(val.faultCode, val.faultString)
end
end
end
end
else
multicall_fault(ERR_MC_EXPECTED_STRUCT, "system.multicall expected struct")
end
}
end # end add_handler
self
end
def add_introspection
add_handler("system.listMethods",%w(array), "List methods available on this XML-RPC server") do
methods = []
@handler.each do |name, obj|
if obj.kind_of? Proc
methods << name
else
obj.class.public_instance_methods(false).each do |meth|
methods << "#{name}#{meth}"
end
end
end
methods
end
add_handler("system.methodSignature", %w(array string), "Returns method signature") do |meth|
sigs = []
@handler.each do |name, obj, sig|
if obj.kind_of? Proc and sig != nil and name == meth
if sig[0].kind_of? Array
# sig contains multiple signatures, e.g. [["array"], ["array", "string"]]
sig.each {|s| sigs << s}
else
# sig is a single signature, e.g. ["array"]
sigs << sig
end
end
end
sigs.uniq! || sigs # remove eventually duplicated signatures
end
add_handler("system.methodHelp", %w(string string), "Returns help on using this method") do |meth|
help = nil
@handler.each do |name, obj, sig, hlp|
if obj.kind_of? Proc and name == meth
help = hlp
break
end
end
help || ""
end
self
end
def process(data)
method, params = parser().parseMethodCall(data)
handle(method, *params)
end
private # --------------------------------------------------------------
def multicall_fault(nr, str)
{"faultCode" => nr, "faultString" => str}
end
#
# method dispatch
#
def dispatch(methodname, *args)
for name, obj in @handler
if obj.kind_of? Proc
next unless methodname == name
else
next unless methodname =~ /^#{name}(.+)$/
next unless obj.respond_to? $1
obj = obj.method($1)
end
if check_arity(obj, args.size)
if @service_hook.nil?
return obj.call(*args)
else
return @service_hook.call(obj, *args)
end
end
end
if @default_handler.nil?
raise XMLRPC::FaultException.new(ERR_METHOD_MISSING, "Method #{methodname} missing or wrong number of parameters!")
else
@default_handler.call(methodname, *args)
end
end
#
# returns true, if the arity of "obj" matches
#
def check_arity(obj, n_args)
ary = obj.arity
if ary >= 0
n_args == ary
else
n_args >= (ary+1).abs
end
end
def call_method(methodname, *args)
begin
[true, dispatch(methodname, *args)]
rescue XMLRPC::FaultException => e
[false, e]
rescue Exception => e
[false, XMLRPC::FaultException.new(ERR_UNCAUGHT_EXCEPTION, "Uncaught exception #{e.message} in method #{methodname}")]
end
end
#
#
#
def handle(methodname, *args)
create().methodResponse(*call_method(methodname, *args))
end
end
=begin
= XMLRPC::CGIServer
== Synopsis
require "xmlrpc/server"
s = XMLRPC::CGIServer.new
s.add_handler("michael.add") do |a,b|
a + b
end
s.add_handler("michael.div") do |a,b|
if b == 0
raise XMLRPC::FaultException.new(1, "division by zero")
else
a / b
end
end
s.set_default_handler do |name, *args|
raise XMLRPC::FaultException.new(-99, "Method #{name} missing" +
" or wrong number of parameters!")
end
s.serve
== Description
Implements a CGI-based XML-RPC server.
== Superclass
((<XMLRPC::BasicServer>))
== Class Methods
--- XMLRPC::CGIServer.new( *a )
Creates a new (({XMLRPC::CGIServer})) instance. All parameters given
are by-passed to ((<XMLRPC::BasicServer.new>)). You can only create
((*one*)) (({XMLRPC::CGIServer})) instance, because more than one makes
no sense.
== Instance Methods
--- XMLRPC::CGIServer#serve
Call this after you have added all you handlers to the server.
This method processes a XML-RPC methodCall and sends the answer
back to the client.
Make sure that you don't write to standard-output in a handler, or in
any other part of your program, this would case a CGI-based server to fail!
=end
class CGIServer < BasicServer
@@obj = nil
def CGIServer.new(*a)
@@obj = super(*a) if @@obj.nil?
@@obj
end
def initialize(*a)
super(*a)
end
def serve
catch(:exit_serve) {
length = ENV['CONTENT_LENGTH'].to_i
http_error(405, "Method Not Allowed") unless ENV['REQUEST_METHOD'] == "POST"
http_error(400, "Bad Request") unless parse_content_type(ENV['CONTENT_TYPE']).first == "text/xml"
http_error(411, "Length Required") unless length > 0
# TODO: do we need a call to binmode?
$stdin.binmode if $stdin.respond_to? :binmode
data = $stdin.read(length)
http_error(400, "Bad Request") if data.nil? or data.size != length
http_write(process(data), "Content-type" => "text/xml; charset=utf-8")
}
end
private
def http_error(status, message)
err = "#{status} #{message}"
msg = <<-"MSGEND"
<html>
<head>
<title>#{err}</title>
</head>
<body>
<h1>#{err}</h1>
<p>Unexpected error occured while processing XML-RPC request!</p>
</body>
</html>
MSGEND
http_write(msg, "Status" => err, "Content-type" => "text/html")
throw :exit_serve # exit from the #serve method
end
def http_write(body, header)
h = {}
header.each {|key, value| h[key.to_s.capitalize] = value}
h['Status'] ||= "200 OK"
h['Content-length'] ||= body.size.to_s
str = ""
h.each {|key, value| str << "#{key}: #{value}\r\n"}
str << "\r\n#{body}"
print str
end
end
=begin
= XMLRPC::ModRubyServer
== Description
Implements a XML-RPC server, which works with Apache mod_ruby.
Use it in the same way as CGIServer!
== Superclass
((<XMLRPC::BasicServer>))
=end
class ModRubyServer < BasicServer
def initialize(*a)
@ap = Apache::request
super(*a)
end
def serve
catch(:exit_serve) {
header = {}
@ap.headers_in.each {|key, value| header[key.capitalize] = value}
length = header['Content-length'].to_i
http_error(405, "Method Not Allowed") unless @ap.request_method == "POST"
http_error(400, "Bad Request") unless parse_content_type(header['Content-type']).first == "text/xml"
http_error(411, "Length Required") unless length > 0
# TODO: do we need a call to binmode?
@ap.binmode
data = @ap.read(length)
http_error(400, "Bad Request") if data.nil? or data.size != length
http_write(process(data), 200, "Content-type" => "text/xml; charset=utf-8")
}
end
private
def http_error(status, message)
err = "#{status} #{message}"
msg = <<-"MSGEND"
<html>
<head>
<title>#{err}</title>
</head>
<body>
<h1>#{err}</h1>
<p>Unexpected error occured while processing XML-RPC request!</p>
</body>
</html>
MSGEND
http_write(msg, status, "Status" => err, "Content-type" => "text/html")
throw :exit_serve # exit from the #serve method
end
def http_write(body, status, header)
h = {}
header.each {|key, value| h[key.to_s.capitalize] = value}
h['Status'] ||= "200 OK"
h['Content-length'] ||= body.size.to_s
h.each {|key, value| @ap.headers_out[key] = value }
@ap.content_type = h["Content-type"]
@ap.status = status.to_i
@ap.send_http_header
@ap.print body
end
end
=begin
= XMLRPC::Server
== Synopsis
require "xmlrpc/server"
s = XMLRPC::Server.new(8080)
s.add_handler("michael.add") do |a,b|
a + b
end
s.add_handler("michael.div") do |a,b|
if b == 0
raise XMLRPC::FaultException.new(1, "division by zero")
else
a / b
end
end
s.set_default_handler do |name, *args|
raise XMLRPC::FaultException.new(-99, "Method #{name} missing" +
" or wrong number of parameters!")
end
s.serve
== Description
Implements a standalone XML-RPC server. The method (({serve}))) is left if a SIGHUP is sent to the
program.
== Superclass
((<XMLRPC::WEBrickServlet>))
== Class Methods
--- XMLRPC::Server.new( port=8080, host="127.0.0.1", maxConnections=4, stdlog=$stdout, audit=true, debug=true, *a )
Creates a new (({XMLRPC::Server})) instance, which is a XML-RPC server listening on
port ((|port|)) and accepts requests for the host ((|host|)), which is by default only the localhost.
The server is not started, to start it you have to call ((<serve|XMLRPC::Server#serve>)).
Parameters ((|audit|)) and ((|debug|)) are obsolete!
All additionally given parameters in ((|*a|)) are by-passed to ((<XMLRPC::BasicServer.new>)).
== Instance Methods
--- XMLRPC::Server#serve
Call this after you have added all you handlers to the server.
This method starts the server to listen for XML-RPC requests and answer them.
--- XMLRPC::Server#shutdown
Stops and shuts the server down.
=end
class WEBrickServlet < BasicServer; end # forward declaration
class Server < WEBrickServlet
def initialize(port=8080, host="127.0.0.1", maxConnections=4, stdlog=$stdout, audit=true, debug=true, *a)
super(*a)
require 'webrick'
@server = WEBrick::HTTPServer.new(:Port => port, :BindAddress => host, :MaxClients => maxConnections,
:Logger => WEBrick::Log.new(stdlog))
@server.mount("/", self)
end
def serve
if RUBY_PLATFORM =~ /mingw|mswin32/
signals = [1]
else
signals = %w[INT TERM HUP]
end
signals.each { |signal| trap(signal) { @server.shutdown } }
@server.start
end
def shutdown
@server.shutdown
end
end
=begin
= XMLRPC::WEBrickServlet
== Synopsis
require "webrick"
require "xmlrpc/server"
s = XMLRPC::WEBrickServlet.new
s.add_handler("michael.add") do |a,b|
a + b
end
s.add_handler("michael.div") do |a,b|
if b == 0
raise XMLRPC::FaultException.new(1, "division by zero")
else
a / b
end
end
s.set_default_handler do |name, *args|
raise XMLRPC::FaultException.new(-99, "Method #{name} missing" +
" or wrong number of parameters!")
end
httpserver = WEBrick::HTTPServer.new(:Port => 8080)
httpserver.mount("/RPC2", s)
trap("HUP") { httpserver.shutdown } # use 1 instead of "HUP" on Windows
httpserver.start
== Instance Methods
--- XMLRPC::WEBrickServlet#set_valid_ip( *ip_addr )
Specifies the valid IP addresses that are allowed to connect to the server.
Each IP is either a (({String})) or a (({Regexp})).
--- XMLRPC::WEBrickServlet#get_valid_ip
Return the via method ((<set_valid_ip|XMLRPC::Server#set_valid_ip>)) specified
valid IP addresses.
== Description
Implements a servlet for use with WEBrick, a pure Ruby (HTTP-) server framework.
== Superclass
((<XMLRPC::BasicServer>))
=end
class WEBrickServlet < BasicServer
def initialize(*a)
super
require "webrick/httpstatus"
@valid_ip = nil
end
# deprecated from WEBrick/1.2.2.
# but does not break anything.
def require_path_info?
false
end
def get_instance(config, *options)
# TODO: set config & options
self
end
def set_valid_ip(*ip_addr)
if ip_addr.size == 1 and ip_addr[0].nil?
@valid_ip = nil
else
@valid_ip = ip_addr
end
end
def get_valid_ip
@valid_ip
end
def service(request, response)
if @valid_ip
raise WEBrick::HTTPStatus::Forbidden unless @valid_ip.any? { |ip| request.peeraddr[3] =~ ip }
end
if request.request_method != "POST"
raise WEBrick::HTTPStatus::MethodNotAllowed,
"unsupported method `#{request.request_method}'."
end
if parse_content_type(request['Content-type']).first != "text/xml"
raise WEBrick::HTTPStatus::BadRequest
end
length = (request['Content-length'] || 0).to_i
raise WEBrick::HTTPStatus::LengthRequired unless length > 0
data = request.body
if data.nil? or data.size != length
raise WEBrick::HTTPStatus::BadRequest
end
resp = process(data)
if resp.nil? or resp.size <= 0
raise WEBrick::HTTPStatus::InternalServerError
end
response.status = 200
response['Content-Length'] = resp.size
response['Content-Type'] = "text/xml; charset=utf-8"
response.body = resp
end
end
end # module XMLRPC
=begin
= History
$Id: server.rb 22461 2009-02-20 09:06:53Z shyouhei $
=end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xmlrpc/datetime.rb | tools/jruby-1.5.1/lib/ruby/1.8/xmlrpc/datetime.rb | =begin
= xmlrpc/datetime.rb
Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de)
Released under the same term of license as Ruby.
= Classes
* ((<XMLRPC::DateTime>))
= XMLRPC::DateTime
== Description
This class is important to handle XMLRPC (('dateTime.iso8601')) values,
correcly, because normal UNIX-dates (class (({Date}))) only handle dates
from year 1970 on, and class (({Time})) handles dates without the time
component. (({XMLRPC::DateTime})) is able to store a XMLRPC
(('dateTime.iso8601')) value correctly.
== Class Methods
--- XMLRPC::DateTime.new( year, month, day, hour, min, sec )
Creates a new (({XMLRPC::DateTime})) instance with the
parameters ((|year|)), ((|month|)), ((|day|)) as date and
((|hour|)), ((|min|)), ((|sec|)) as time.
Raises (({ArgumentError})) if a parameter is out of range, or ((|year|)) is not
of type (({Integer})).
== Instance Methods
--- XMLRPC::DateTime#year
--- XMLRPC::DateTime#month
--- XMLRPC::DateTime#day
--- XMLRPC::DateTime#hour
--- XMLRPC::DateTime#min
--- XMLRPC::DateTime#sec
Return the value of the specified date/time component.
--- XMLRPC::DateTime#mon
Alias for ((<XMLRPC::DateTime#month>)).
--- XMLRPC::DateTime#year=( value )
--- XMLRPC::DateTime#month=( value )
--- XMLRPC::DateTime#day=( value )
--- XMLRPC::DateTime#hour=( value )
--- XMLRPC::DateTime#min=( value )
--- XMLRPC::DateTime#sec=( value )
Set ((|value|)) as the new date/time component.
Raises (({ArgumentError})) if ((|value|)) is out of range, or in the case
of (({XMLRPC::DateTime#year=})) if ((|value|)) is not of type (({Integer})).
--- XMLRPC::DateTime#mon=( value )
Alias for ((<XMLRPC::DateTime#month=>)).
--- XMLRPC::DateTime#to_time
Return a (({Time})) object of the date/time which (({self})) represents.
If the (('year')) is below 1970, this method returns (({nil})),
because (({Time})) cannot handle years below 1970.
The used timezone is GMT.
--- XMLRPC::DateTime#to_date
Return a (({Date})) object of the date which (({self})) represents.
The (({Date})) object do ((*not*)) contain the time component (only date).
--- XMLRPC::DateTime#to_a
Returns all date/time components in an array.
Returns (({[year, month, day, hour, min, sec]})).
=end
require "date"
module XMLRPC
class DateTime
attr_reader :year, :month, :day, :hour, :min, :sec
def year= (value)
raise ArgumentError, "date/time out of range" unless value.is_a? Integer
@year = value
end
def month= (value)
raise ArgumentError, "date/time out of range" unless (1..12).include? value
@month = value
end
def day= (value)
raise ArgumentError, "date/time out of range" unless (1..31).include? value
@day = value
end
def hour= (value)
raise ArgumentError, "date/time out of range" unless (0..24).include? value
@hour = value
end
def min= (value)
raise ArgumentError, "date/time out of range" unless (0..59).include? value
@min = value
end
def sec= (value)
raise ArgumentError, "date/time out of range" unless (0..59).include? value
@sec = value
end
alias mon month
alias mon= month=
def initialize(year, month, day, hour, min, sec)
self.year, self.month, self.day = year, month, day
self.hour, self.min, self.sec = hour, min, sec
end
def to_time
if @year >= 1970
Time.gm(*to_a)
else
nil
end
end
def to_date
Date.new(*to_a[0,3])
end
def to_a
[@year, @month, @day, @hour, @min, @sec]
end
def ==(o)
Array(self) == Array(o)
end
end
end # module XMLRPC
=begin
= History
$Id: datetime.rb 11708 2007-02-12 23:01:19Z shyouhei $
=end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xmlrpc/httpserver.rb | tools/jruby-1.5.1/lib/ruby/1.8/xmlrpc/httpserver.rb | #
# Implements a simple HTTP-server by using John W. Small's (jsmall@laser.net)
# ruby-generic-server.
#
# Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de)
#
# $Id: httpserver.rb 11708 2007-02-12 23:01:19Z shyouhei $
#
require "gserver"
class HttpServer < GServer
##
# handle_obj specifies the object, that receives calls to request_handler
# and ip_auth_handler
def initialize(handle_obj, port = 8080, host = DEFAULT_HOST, maxConnections = 4,
stdlog = $stdout, audit = true, debug = true)
@handler = handle_obj
super(port, host, maxConnections, stdlog, audit, debug)
end
private
# Constants -----------------------------------------------
CRLF = "\r\n"
HTTP_PROTO = "HTTP/1.0"
SERVER_NAME = "HttpServer (Ruby #{RUBY_VERSION})"
DEFAULT_HEADER = {
"Server" => SERVER_NAME
}
##
# Mapping of status code and error message
#
StatusCodeMapping = {
200 => "OK",
400 => "Bad Request",
403 => "Forbidden",
405 => "Method Not Allowed",
411 => "Length Required",
500 => "Internal Server Error"
}
# Classes -------------------------------------------------
class Request
attr_reader :data, :header, :method, :path, :proto
def initialize(data, method=nil, path=nil, proto=nil)
@header, @data = Table.new, data
@method, @path, @proto = method, path, proto
end
def content_length
len = @header['Content-Length']
return nil if len.nil?
return len.to_i
end
end
class Response
attr_reader :header
attr_accessor :body, :status, :status_message
def initialize(status=200)
@status = status
@status_message = nil
@header = Table.new
end
end
##
# a case-insensitive Hash class for HTTP header
#
class Table
include Enumerable
def initialize(hash={})
@hash = hash
update(hash)
end
def [](key)
@hash[key.to_s.capitalize]
end
def []=(key, value)
@hash[key.to_s.capitalize] = value
end
def update(hash)
hash.each {|k,v| self[k] = v}
self
end
def each
@hash.each {|k,v| yield k.capitalize, v }
end
def writeTo(port)
each { |k,v| port << "#{k}: #{v}" << CRLF }
end
end # class Table
# Helper Methods ------------------------------------------
def http_header(header=nil)
new_header = Table.new(DEFAULT_HEADER)
new_header.update(header) unless header.nil?
new_header["Connection"] = "close"
new_header["Date"] = http_date(Time.now)
new_header
end
def http_date( aTime )
aTime.gmtime.strftime( "%a, %d %b %Y %H:%M:%S GMT" )
end
def http_resp(status_code, status_message=nil, header=nil, body=nil)
status_message ||= StatusCodeMapping[status_code]
str = ""
str << "#{HTTP_PROTO} #{status_code} #{status_message}" << CRLF
http_header(header).writeTo(str)
str << CRLF
str << body unless body.nil?
str
end
# Main Serve Loop -----------------------------------------
def serve(io)
# perform IP authentification
unless @handler.ip_auth_handler(io)
io << http_resp(403, "Forbidden")
return
end
# parse first line
if io.gets =~ /^(\S+)\s+(\S+)\s+(\S+)/
request = Request.new(io, $1, $2, $3)
else
io << http_resp(400, "Bad Request")
return
end
# parse HTTP headers
while (line=io.gets) !~ /^(\n|\r)/
if line =~ /^([\w-]+):\s*(.*)$/
request.header[$1] = $2.strip
end
end
io.binmode
response = Response.new
# execute request handler
@handler.request_handler(request, response)
# write response back to the client
io << http_resp(response.status, response.status_message,
response.header, response.body)
rescue Exception => e
io << http_resp(500, "Internal Server Error")
end
end # class HttpServer
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/xmlrpc/marshal.rb | tools/jruby-1.5.1/lib/ruby/1.8/xmlrpc/marshal.rb | #
# Marshalling of XML-RPC methodCall and methodResponse
#
# Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de)
#
# $Id: marshal.rb 11708 2007-02-12 23:01:19Z shyouhei $
#
require "xmlrpc/parser"
require "xmlrpc/create"
require "xmlrpc/config"
require "xmlrpc/utils"
module XMLRPC
class Marshal
include ParserWriterChooseMixin
# class methods -------------------------------
class << self
def dump_call( methodName, *params )
new.dump_call( methodName, *params )
end
def dump_response( param )
new.dump_response( param )
end
def load_call( stringOrReadable )
new.load_call( stringOrReadable )
end
def load_response( stringOrReadable )
new.load_response( stringOrReadable )
end
alias dump dump_response
alias load load_response
end # class self
# instance methods ----------------------------
def initialize( parser = nil, writer = nil )
set_parser( parser )
set_writer( writer )
end
def dump_call( methodName, *params )
create.methodCall( methodName, *params )
end
def dump_response( param )
create.methodResponse( ! param.kind_of?( XMLRPC::FaultException ) , param )
end
##
# returns [ methodname, params ]
#
def load_call( stringOrReadable )
parser.parseMethodCall( stringOrReadable )
end
##
# returns paramOrFault
#
def load_response( stringOrReadable )
parser.parseMethodResponse( stringOrReadable )[1]
end
end # class Marshal
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/runit/assert.rb | tools/jruby-1.5.1/lib/ruby/1.8/runit/assert.rb | # Author:: Nathaniel Talbott.
# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
# License:: Ruby license.
require 'test/unit/assertions'
require 'runit/error'
module RUNIT
module Assert
include Test::Unit::Assertions
def setup_assert
end
def assert_no_exception(*args, &block)
assert_nothing_raised(*args, &block)
end
# To deal with the fact that RubyUnit does not check that the
# regular expression is, indeed, a regular expression, if it is
# not, we do our own assertion using the same semantics as
# RubyUnit
def assert_match(actual_string, expected_re, message="")
_wrap_assertion {
full_message = build_message(message, "Expected <?> to match <?>", actual_string, expected_re)
assert_block(full_message) {
expected_re =~ actual_string
}
Regexp.last_match
}
end
def assert_not_nil(actual, message="")
assert(!actual.nil?, message)
end
def assert_not_match(actual_string, expected_re, message="")
assert_no_match(expected_re, actual_string, message)
end
def assert_matches(*args)
assert_match(*args)
end
def assert_fail(message="")
flunk(message)
end
def assert_equal_float(expected, actual, delta, message="")
assert_in_delta(expected, actual, delta, message)
end
def assert_send(object, method, *args)
super([object, method, *args])
end
def assert_exception(exception, message="", &block)
assert_raises(exception, message, &block)
end
def assert_respond_to(method, object, message="")
if (called_internally?)
super
else
super(object, method, message)
end
end
def called_internally?
/assertions\.rb/.match(caller[1])
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/runit/testsuite.rb | tools/jruby-1.5.1/lib/ruby/1.8/runit/testsuite.rb | # Author:: Nathaniel Talbott.
# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
# License:: Ruby license.
require 'test/unit/testsuite'
module RUNIT
class TestSuite < Test::Unit::TestSuite
def add_test(*args)
add(*args)
end
def add(*args)
self.<<(*args)
end
def count_test_cases
return size
end
def run(result, &progress_block)
progress_block = proc {} unless (block_given?)
super(result, &progress_block)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/runit/topublic.rb | tools/jruby-1.5.1/lib/ruby/1.8/runit/topublic.rb | # Author:: Nathaniel Talbott.
# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
# License:: Ruby license.
module RUNIT
module ToPublic
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/runit/testresult.rb | tools/jruby-1.5.1/lib/ruby/1.8/runit/testresult.rb | # Author:: Nathaniel Talbott.
# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
# License:: Ruby license.
require 'test/unit/testresult'
module RUNIT
class TestResult < Test::Unit::TestResult
attr_reader(:errors, :failures)
def succeed?
return passed?
end
def failure_size
return failure_count
end
def run_asserts
return assertion_count
end
def error_size
return error_count
end
def run_tests
return run_count
end
def add_failure(failure)
def failure.at
return location
end
def failure.err
return message
end
super(failure)
end
def add_error(error)
def error.at
return location
end
def error.err
return exception
end
super(error)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/runit/error.rb | tools/jruby-1.5.1/lib/ruby/1.8/runit/error.rb | # Author:: Nathaniel Talbott.
# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
# License:: Ruby license.
require 'test/unit/assertionfailederror.rb'
module RUNIT
AssertionFailedError = Test::Unit::AssertionFailedError
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/runit/testcase.rb | tools/jruby-1.5.1/lib/ruby/1.8/runit/testcase.rb | # Author:: Nathaniel Talbott.
# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
# License:: Ruby license.
require 'runit/testresult'
require 'runit/testsuite'
require 'runit/assert'
require 'runit/error'
require 'test/unit/testcase'
module RUNIT
class TestCase < Test::Unit::TestCase
include RUNIT::Assert
def self.suite
method_names = instance_methods(true)
tests = method_names.delete_if { |method_name| method_name !~ /^test/ }
suite = TestSuite.new(name)
tests.each {
|test|
catch(:invalid_test) {
suite << new(test, name)
}
}
return suite
end
def initialize(test_name, suite_name=self.class.name)
super(test_name)
end
def assert_equals(*args)
assert_equal(*args)
end
def name
super.sub(/^(.*?)\((.*)\)$/, '\2#\1')
end
def run(result, &progress_block)
progress_block = proc {} unless (block_given?)
super(result, &progress_block)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/runit/cui/testrunner.rb | tools/jruby-1.5.1/lib/ruby/1.8/runit/cui/testrunner.rb | # Author:: Nathaniel Talbott.
# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
# License:: Ruby license.
require 'test/unit/ui/console/testrunner'
require 'runit/testresult'
module RUNIT
module CUI
class TestRunner < Test::Unit::UI::Console::TestRunner
@@quiet_mode = false
def self.run(suite)
self.new().run(suite)
end
def initialize
super nil
end
def run(suite, quiet_mode=@@quiet_mode)
@suite = suite
def @suite.suite
self
end
@output_level = (quiet_mode ? Test::Unit::UI::PROGRESS_ONLY : Test::Unit::UI::VERBOSE)
start
end
def create_mediator(suite)
mediator = Test::Unit::UI::TestRunnerMediator.new(suite)
class << mediator
attr_writer :result_delegate
def create_result
return @result_delegate.create_result
end
end
mediator.result_delegate = self
return mediator
end
def create_result
return RUNIT::TestResult.new
end
def self.quiet_mode=(boolean)
@@quiet_mode = boolean
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/diagram.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/diagram.rb | # A wonderful hack by to draw package diagrams using the dot package.
# Originally written by Jah, team Enticla.
#
# You must have the V1.7 or later in your path
# http://www.research.att.com/sw/tools/graphviz/
require "rdoc/dot/dot"
require 'rdoc/options'
module RDoc
# Draw a set of diagrams representing the modules and classes in the
# system. We draw one diagram for each file, and one for each toplevel
# class or module. This means there will be overlap. However, it also
# means that you'll get better context for objects.
#
# To use, simply
#
# d = Diagram.new(info) # pass in collection of top level infos
# d.draw
#
# The results will be written to the +dot+ subdirectory. The process
# also sets the +diagram+ attribute in each object it graphs to
# the name of the file containing the image. This can be used
# by output generators to insert images.
class Diagram
FONT = "Arial"
DOT_PATH = "dot"
# Pass in the set of top level objects. The method also creates
# the subdirectory to hold the images
def initialize(info, options)
@info = info
@options = options
@counter = 0
File.makedirs(DOT_PATH)
@diagram_cache = {}
end
# Draw the diagrams. We traverse the files, drawing a diagram for
# each. We also traverse each top-level class and module in that
# file drawing a diagram for these too.
def draw
unless @options.quiet
$stderr.print "Diagrams: "
$stderr.flush
end
@info.each_with_index do |i, file_count|
@done_modules = {}
@local_names = find_names(i)
@global_names = []
@global_graph = graph = DOT::DOTDigraph.new('name' => 'TopLevel',
'fontname' => FONT,
'fontsize' => '8',
'bgcolor' => 'lightcyan1',
'compound' => 'true')
# it's a little hack %) i'm too lazy to create a separate class
# for default node
graph << DOT::DOTNode.new('name' => 'node',
'fontname' => FONT,
'color' => 'black',
'fontsize' => 8)
i.modules.each do |mod|
draw_module(mod, graph, true, i.file_relative_name)
end
add_classes(i, graph, i.file_relative_name)
i.diagram = convert_to_png("f_#{file_count}", graph)
# now go through and document each top level class and
# module independently
i.modules.each_with_index do |mod, count|
@done_modules = {}
@local_names = find_names(mod)
@global_names = []
@global_graph = graph = DOT::DOTDigraph.new('name' => 'TopLevel',
'fontname' => FONT,
'fontsize' => '8',
'bgcolor' => 'lightcyan1',
'compound' => 'true')
graph << DOT::DOTNode.new('name' => 'node',
'fontname' => FONT,
'color' => 'black',
'fontsize' => 8)
draw_module(mod, graph, true)
mod.diagram = convert_to_png("m_#{file_count}_#{count}",
graph)
end
end
$stderr.puts unless @options.quiet
end
#######
private
#######
def find_names(mod)
return [mod.full_name] + mod.classes.collect{|cl| cl.full_name} +
mod.modules.collect{|m| find_names(m)}.flatten
end
def find_full_name(name, mod)
full_name = name.dup
return full_name if @local_names.include?(full_name)
mod_path = mod.full_name.split('::')[0..-2]
unless mod_path.nil?
until mod_path.empty?
full_name = mod_path.pop + '::' + full_name
return full_name if @local_names.include?(full_name)
end
end
return name
end
def draw_module(mod, graph, toplevel = false, file = nil)
return if @done_modules[mod.full_name] and not toplevel
@counter += 1
url = mod.http_url("classes")
m = DOT::DOTSubgraph.new('name' => "cluster_#{mod.full_name.gsub( /:/,'_' )}",
'label' => mod.name,
'fontname' => FONT,
'color' => 'blue',
'style' => 'filled',
'URL' => %{"#{url}"},
'fillcolor' => toplevel ? 'palegreen1' : 'palegreen3')
@done_modules[mod.full_name] = m
add_classes(mod, m, file)
graph << m
unless mod.includes.empty?
mod.includes.each do |m|
m_full_name = find_full_name(m.name, mod)
if @local_names.include?(m_full_name)
@global_graph << DOT::DOTEdge.new('from' => "#{m_full_name.gsub( /:/,'_' )}",
'to' => "#{mod.full_name.gsub( /:/,'_' )}",
'ltail' => "cluster_#{m_full_name.gsub( /:/,'_' )}",
'lhead' => "cluster_#{mod.full_name.gsub( /:/,'_' )}")
else
unless @global_names.include?(m_full_name)
path = m_full_name.split("::")
url = File.join('classes', *path) + ".html"
@global_graph << DOT::DOTNode.new('name' => "#{m_full_name.gsub( /:/,'_' )}",
'shape' => 'box',
'label' => "#{m_full_name}",
'URL' => %{"#{url}"})
@global_names << m_full_name
end
@global_graph << DOT::DOTEdge.new('from' => "#{m_full_name.gsub( /:/,'_' )}",
'to' => "#{mod.full_name.gsub( /:/,'_' )}",
'lhead' => "cluster_#{mod.full_name.gsub( /:/,'_' )}")
end
end
end
end
def add_classes(container, graph, file = nil )
use_fileboxes = Options.instance.fileboxes
files = {}
# create dummy node (needed if empty and for module includes)
if container.full_name
graph << DOT::DOTNode.new('name' => "#{container.full_name.gsub( /:/,'_' )}",
'label' => "",
'width' => (container.classes.empty? and
container.modules.empty?) ?
'0.75' : '0.01',
'height' => '0.01',
'shape' => 'plaintext')
end
container.classes.each_with_index do |cl, cl_index|
last_file = cl.in_files[-1].file_relative_name
if use_fileboxes && !files.include?(last_file)
@counter += 1
files[last_file] =
DOT::DOTSubgraph.new('name' => "cluster_#{@counter}",
'label' => "#{last_file}",
'fontname' => FONT,
'color'=>
last_file == file ? 'red' : 'black')
end
next if cl.name == 'Object' || cl.name[0,2] == "<<"
url = cl.http_url("classes")
label = cl.name.dup
if use_fileboxes && cl.in_files.length > 1
label << '\n[' +
cl.in_files.collect {|i|
i.file_relative_name
}.sort.join( '\n' ) +
']'
end
attrs = {
'name' => "#{cl.full_name.gsub( /:/, '_' )}",
'fontcolor' => 'black',
'style'=>'filled',
'color'=>'palegoldenrod',
'label' => label,
'shape' => 'ellipse',
'URL' => %{"#{url}"}
}
c = DOT::DOTNode.new(attrs)
if use_fileboxes
files[last_file].push c
else
graph << c
end
end
if use_fileboxes
files.each_value do |val|
graph << val
end
end
unless container.classes.empty?
container.classes.each_with_index do |cl, cl_index|
cl.includes.each do |m|
m_full_name = find_full_name(m.name, cl)
if @local_names.include?(m_full_name)
@global_graph << DOT::DOTEdge.new('from' => "#{m_full_name.gsub( /:/,'_' )}",
'to' => "#{cl.full_name.gsub( /:/,'_' )}",
'ltail' => "cluster_#{m_full_name.gsub( /:/,'_' )}")
else
unless @global_names.include?(m_full_name)
path = m_full_name.split("::")
url = File.join('classes', *path) + ".html"
@global_graph << DOT::DOTNode.new('name' => "#{m_full_name.gsub( /:/,'_' )}",
'shape' => 'box',
'label' => "#{m_full_name}",
'URL' => %{"#{url}"})
@global_names << m_full_name
end
@global_graph << DOT::DOTEdge.new('from' => "#{m_full_name.gsub( /:/,'_' )}",
'to' => "#{cl.full_name.gsub( /:/, '_')}")
end
end
sclass = cl.superclass
next if sclass.nil? || sclass == 'Object'
sclass_full_name = find_full_name(sclass,cl)
unless @local_names.include?(sclass_full_name) or @global_names.include?(sclass_full_name)
path = sclass_full_name.split("::")
url = File.join('classes', *path) + ".html"
@global_graph << DOT::DOTNode.new(
'name' => "#{sclass_full_name.gsub( /:/, '_' )}",
'label' => sclass_full_name,
'URL' => %{"#{url}"})
@global_names << sclass_full_name
end
@global_graph << DOT::DOTEdge.new('from' => "#{sclass_full_name.gsub( /:/,'_' )}",
'to' => "#{cl.full_name.gsub( /:/, '_')}")
end
end
container.modules.each do |submod|
draw_module(submod, graph)
end
end
def convert_to_png(file_base, graph)
str = graph.to_s
return @diagram_cache[str] if @diagram_cache[str]
op_type = Options.instance.image_format
dotfile = File.join(DOT_PATH, file_base)
src = dotfile + ".dot"
dot = dotfile + "." + op_type
unless @options.quiet
$stderr.print "."
$stderr.flush
end
File.open(src, 'w+' ) do |f|
f << str << "\n"
end
system "dot", "-T#{op_type}", src, "-o", dot
# Now construct the imagemap wrapper around
# that png
ret = wrap_in_image_map(src, dot)
@diagram_cache[str] = ret
return ret
end
# Extract the client-side image map from dot, and use it
# to generate the imagemap proper. Return the whole
# <map>..<img> combination, suitable for inclusion on
# the page
def wrap_in_image_map(src, dot)
res = %{<map id="map" name="map">\n}
dot_map = `dot -Tismap #{src}`
dot_map.each do |area|
unless area =~ /^rectangle \((\d+),(\d+)\) \((\d+),(\d+)\) ([\/\w.]+)\s*(.*)/
$stderr.puts "Unexpected output from dot:\n#{area}"
return nil
end
xs, ys = [$1.to_i, $3.to_i], [$2.to_i, $4.to_i]
url, area_name = $5, $6
res << %{ <area shape="rect" coords="#{xs.min},#{ys.min},#{xs.max},#{ys.max}" }
res << %{ href="#{url}" alt="#{area_name}" />\n}
end
res << "</map>\n"
# map_file = src.sub(/.dot/, '.map')
# system("dot -Timap #{src} -o #{map_file}")
res << %{<img src="#{dot}" usemap="#map" border="0" alt="#{dot}">}
return res
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/usage.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/usage.rb | # = Synopsis
#
# This library allows command-line tools to encapsulate their usage
# as a comment at the top of the main file. Calling <tt>RDoc::usage</tt>
# then displays some or all of that comment, and optionally exits
# the program with an exit status. We always look for the comment
# in the main program file, so it is safe to call this method
# from anywhere in the executing program.
#
# = Usage
#
# RDoc::usage( [ exit_status ], [ section, ...])
# RDoc::usage_no_exit( [ section, ...])
#
# where:
#
# exit_status::
# the integer exit code (default zero). RDoc::usage will exit
# the calling program with this status.
#
# section::
# an optional list of section names. If specified, only the
# sections with the given names as headings will be output.
# For example, this section is named 'Usage', and the next
# section is named 'Examples'. The section names are case
# insensitive.
#
# = Examples
#
# # Comment block describing usage
# # with (optional) section headings
# # . . .
#
# require 'rdoc/usage'
#
# # Display all usage and exit with a status of 0
#
# RDoc::usage
#
# # Display all usage and exit with a status of 99
#
# RDoc::usage(99)
#
# # Display usage in the 'Summary' section only, then
# # exit with a status of 99
#
# RDoc::usage(99, 'Summary')
#
# # Display information in the Author and Copyright
# # sections, then exit 0.
#
# RDoc::usage('Author', 'Copyright')
#
# # Display information in the Author and Copyright
# # sections, but don't exit
#
# RDoc::usage_no_exit('Author', 'Copyright')
#
# = Author
#
# Dave Thomas, The Pragmatic Programmers, LLC
#
# = Copyright
#
# Copyright (c) 2004 Dave Thomas.
# Licensed under the same terms as Ruby
#
require 'rdoc/markup/simple_markup'
require 'rdoc/markup/simple_markup/to_flow'
require 'rdoc/ri/ri_formatter'
require 'rdoc/ri/ri_options'
module RDoc
# Display usage information from the comment at the top of
# the file. String arguments identify specific sections of the
# comment to display. An optional integer first argument
# specifies the exit status (defaults to 0)
def RDoc.usage(*args)
exit_code = 0
if args.size > 0
status = args[0]
if status.respond_to?(:to_int)
exit_code = status.to_int
args.shift
end
end
# display the usage and exit with the given code
usage_no_exit(*args)
exit(exit_code)
end
# Display usage
def RDoc.usage_no_exit(*args)
main_program_file = caller[-1].sub(/:\d+$/, '')
comment = File.open(main_program_file) 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
######################################################################
private
# Find the first comment in the file (that isn't a shebang line)
# If the file doesn't start with a comment, report the fact
# and return empty string
def RDoc.gets(file)
if (line = file.gets) && (line =~ /^#!/) # shebang
throw :exit, find_comment(file)
else
line
end
end
def RDoc.find_comment(file)
catch(:exit) do
# skip leading blank lines
0 while (line = gets(file)) && (line =~ /^\s*$/)
comment = []
while line && line =~ /^\s*#/
comment << line
line = gets(file)
end
0 while line && (line = gets(file))
return no_comment if comment.empty?
return comment.join
end
end
#####
# Given an array of flow items and an array of section names, extract those
# sections from the flow which have headings corresponding to
# a section name in the list. Return them in the order
# of names in the +sections+ array.
def RDoc.extract_sections(flow, sections)
result = []
sections.each do |name|
name = name.downcase
copy_upto_level = nil
flow.each do |item|
case item
when SM::Flow::H
if copy_upto_level && item.level >= copy_upto_level
copy_upto_level = nil
else
if item.text.downcase == name
result << item
copy_upto_level = item.level
end
end
else
if copy_upto_level
result << item
end
end
end
end
if result.empty?
puts "Note to developer: requested section(s) [#{sections.join(', ')}] " +
"not found"
result = flow
end
result
end
#####
# Report the fact that no doc comment count be found
def RDoc.no_comment
$stderr.puts "No usage information available for this program"
""
end
end
if $0 == __FILE__
RDoc::usage(*ARGV)
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/options.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/options.rb | # We handle the parsing of options, and subsequently as a singleton
# object to be queried for option values
require "rdoc/ri/ri_paths"
class Options
require 'singleton'
require 'getoptlong'
include Singleton
# files matching this pattern will be excluded
attr_accessor :exclude
# the name of the output directory
attr_accessor :op_dir
# the name to use for the output
attr_reader :op_name
# include private and protected methods in the
# output
attr_accessor :show_all
# name of the file, class or module to display in
# the initial index page (if not specified
# the first file we encounter is used)
attr_accessor :main_page
# merge into classes of the name name when generating ri
attr_reader :merge
# Don't display progress as we process the files
attr_reader :quiet
# description of the output generator (set with the <tt>-fmt</tt>
# option
attr_accessor :generator
# and the list of files to be processed
attr_reader :files
# array of directories to search for files to satisfy an :include:
attr_reader :rdoc_include
# title to be used out the output
#attr_writer :title
# template to be used when generating output
attr_reader :template
# should diagrams be drawn
attr_reader :diagram
# should we draw fileboxes in diagrams
attr_reader :fileboxes
# include the '#' at the front of hyperlinked instance method names
attr_reader :show_hash
# image format for diagrams
attr_reader :image_format
# character-set
attr_reader :charset
# should source code be included inline, or displayed in a popup
attr_reader :inline_source
# should the output be placed into a single file
attr_reader :all_one_file
# the number of columns in a tab
attr_reader :tab_width
# include line numbers in the source listings
attr_reader :include_line_numbers
# pattern for additional attr_... style methods
attr_reader :extra_accessors
attr_reader :extra_accessor_flags
# URL of stylesheet
attr_reader :css
# URL of web cvs frontend
attr_reader :webcvs
# Are we promiscuous about showing module contents across
# multiple files
attr_reader :promiscuous
# scan newer sources than the flag file if true.
attr_reader :force_update
module OptionList
OPTION_LIST = [
[ "--accessor", "-A", "accessorname[,..]",
"comma separated list of additional class methods\n" +
"that should be treated like 'attr_reader' and\n" +
"friends. Option may be repeated. Each accessorname\n" +
"may have '=text' appended, in which case that text\n" +
"appears where the r/w/rw appears for normal accessors."],
[ "--all", "-a", nil,
"include all methods (not just public)\nin the output" ],
[ "--charset", "-c", "charset",
"specifies HTML character-set" ],
[ "--debug", "-D", nil,
"displays lots on internal stuff" ],
[ "--diagram", "-d", nil,
"Generate diagrams showing modules and classes.\n" +
"You need dot V1.8.6 or later to use the --diagram\n" +
"option correctly. Dot is available from\n"+
"http://www.research.att.com/sw/tools/graphviz/" ],
[ "--exclude", "-x", "pattern",
"do not process files or directories matching\n" +
"pattern. Files given explicitly on the command\n" +
"line will never be excluded." ],
[ "--extension", "-E", "new=old",
"Treat files ending with .new as if they ended with\n" +
".old. Using '-E cgi=rb' will cause xxx.cgi to be\n" +
"parsed as a Ruby file"],
[ "--fileboxes", "-F", nil,
"classes are put in boxes which represents\n" +
"files, where these classes reside. Classes\n" +
"shared between more than one file are\n" +
"shown with list of files that sharing them.\n" +
"Silently discarded if --diagram is not given\n" +
"Experimental." ],
[ "--force-update", "-U", nil,
"forces to scan all sources even if newer than\n" +
"the flag file." ],
[ "--fmt", "-f", "format name",
"set the output formatter (see below)" ],
[ "--help", "-h", nil,
"you're looking at it" ],
[ "--help-output", "-O", nil,
"explain the various output options" ],
[ "--image-format", "-I", "gif/png/jpg/jpeg",
"Sets output image format for diagrams. Can\n" +
"be png, gif, jpeg, jpg. If this option is\n" +
"omitted, png is used. Requires --diagram." ],
[ "--include", "-i", "dir[,dir...]",
"set (or add to) the list of directories\n" +
"to be searched when satisfying :include:\n" +
"requests. Can be used more than once." ],
[ "--inline-source", "-S", nil,
"Show method source code inline, rather\n" +
"than via a popup link" ],
[ "--line-numbers", "-N", nil,
"Include line numbers in the source code" ],
[ "--main", "-m", "name",
"'name' will be the initial page displayed" ],
[ "--merge", "-M", nil,
"when creating ri output, merge processed classes\n" +
"into previously documented classes of the name name"],
[ "--one-file", "-1", nil,
"put all the output into a single file" ],
[ "--op", "-o", "dir",
"set the output directory" ],
[ "--opname", "-n", "name",
"Set the 'name' of the output. Has no\n" +
"effect for HTML." ],
[ "--promiscuous", "-p", nil,
"When documenting a file that contains a module\n" +
"or class also defined in other files, show\n" +
"all stuff for that module/class in each files\n" +
"page. By default, only show stuff defined in\n" +
"that particular file." ],
[ "--quiet", "-q", nil,
"don't show progress as we parse" ],
[ "--ri", "-r", nil,
"generate output for use by 'ri.' The files are\n" +
"stored in the '.rdoc' directory under your home\n"+
"directory unless overridden by a subsequent\n" +
"--op parameter, so no special privileges are needed." ],
[ "--ri-site", "-R", nil,
"generate output for use by 'ri.' The files are\n" +
"stored in a site-wide directory, making them accessible\n"+
"to others, so special privileges are needed." ],
[ "--ri-system", "-Y", nil,
"generate output for use by 'ri.' The files are\n" +
"stored in a system-level directory, making them accessible\n"+
"to others, so special privileges are needed. This option\n"+
"is intended to be used during Ruby installations" ],
[ "--show-hash", "-H", nil,
"A name of the form #name in a comment\n" +
"is a possible hyperlink to an instance\n" +
"method name. When displayed, the '#' is\n" +
"removed unless this option is specified" ],
[ "--style", "-s", "stylesheet url",
"specifies the URL of a separate stylesheet." ],
[ "--tab-width", "-w", "n",
"Set the width of tab characters (default 8)"],
[ "--template", "-T", "template name",
"Set the template used when generating output" ],
[ "--title", "-t", "text",
"Set 'txt' as the title for the output" ],
[ "--version", "-v", nil,
"display RDoc's version" ],
[ "--webcvs", "-W", "url",
"Specify a URL for linking to a web frontend\n" +
"to CVS. If the URL contains a '\%s', the\n" +
"name of the current file will be substituted;\n" +
"if the URL doesn't contain a '\%s', the\n" +
"filename will be appended to it." ],
]
def OptionList.options
OPTION_LIST.map do |long, short, arg,|
[ long,
short,
arg ? GetoptLong::REQUIRED_ARGUMENT : GetoptLong::NO_ARGUMENT
]
end
end
def OptionList.strip_output(text)
text =~ /^\s+/
leading_spaces = $&
text.gsub!(/^#{leading_spaces}/, '')
$stdout.puts text
end
# Show an error and exit
def OptionList.error(msg)
$stderr.puts
$stderr.puts msg
$stderr.puts "\nFor help on options, try 'rdoc --help'\n\n"
exit 1
end
# Show usage and exit
def OptionList.usage(generator_names)
puts
puts(VERSION_STRING)
puts
name = File.basename($0)
OptionList.strip_output(<<-EOT)
Usage:
#{name} [options] [names...]
Files are parsed, and the information they contain
collected, before any output is produced. This allows cross
references between all files to be resolved. If a name is a
directory, it is traversed. If no names are specified, all
Ruby files in the current directory (and subdirectories) are
processed.
Options:
EOT
OPTION_LIST.each do |long, short, arg, desc|
opt = sprintf("%20s", "#{long}, #{short}")
oparg = sprintf("%-7s", arg)
print "#{opt} #{oparg}"
desc = desc.split("\n")
if arg.nil? || arg.length < 7
puts desc.shift
else
puts
end
desc.each do |line|
puts(" "*28 + line)
end
puts
end
puts "\nAvailable output formatters: " +
generator_names.sort.join(', ') + "\n\n"
puts "For information on where the output goes, use\n\n"
puts " rdoc --help-output\n\n"
exit 0
end
def OptionList.help_output
OptionList.strip_output(<<-EOT)
How RDoc generates output depends on the output formatter being
used, and on the options you give.
- HTML output is normally produced into a number of separate files
(one per class, module, and file, along with various indices).
These files will appear in the directory given by the --op
option (doc/ by default).
- XML output by default is written to standard output. If a
--opname option is given, the output will instead be written
to a file with that name in the output directory.
- .chm files (Windows help files) are written in the --op directory.
If an --opname parameter is present, that name is used, otherwise
the file will be called rdoc.chm.
For information on other RDoc options, use "rdoc --help".
EOT
exit 0
end
end
# Parse command line options. We're passed a hash containing
# output generators, keyed by the generator name
def parse(argv, generators)
old_argv = ARGV.dup
begin
ARGV.replace(argv)
@op_dir = "doc"
@op_name = nil
@show_all = false
@main_page = nil
@marge = false
@exclude = []
@quiet = false
@generator_name = 'html'
@generator = generators[@generator_name]
@rdoc_include = []
@title = nil
@template = nil
@diagram = false
@fileboxes = false
@show_hash = false
@image_format = 'png'
@inline_source = false
@all_one_file = false
@tab_width = 8
@include_line_numbers = false
@extra_accessor_flags = {}
@promiscuous = false
@force_update = false
@css = nil
@webcvs = nil
@charset = case $KCODE
when /^S/i
'Shift_JIS'
when /^E/i
'EUC-JP'
else
'iso-8859-1'
end
accessors = []
go = GetoptLong.new(*OptionList.options)
go.quiet = true
go.each do |opt, arg|
case opt
when "--all" then @show_all = true
when "--charset" then @charset = arg
when "--debug" then $DEBUG = true
when "--exclude" then @exclude << Regexp.new(arg)
when "--inline-source" then @inline_source = true
when "--line-numbers" then @include_line_numbers = true
when "--main" then @main_page = arg
when "--merge" then @merge = true
when "--one-file" then @all_one_file = @inline_source = true
when "--op" then @op_dir = arg
when "--opname" then @op_name = arg
when "--promiscuous" then @promiscuous = true
when "--quiet" then @quiet = true
when "--show-hash" then @show_hash = true
when "--style" then @css = arg
when "--template" then @template = arg
when "--title" then @title = arg
when "--webcvs" then @webcvs = arg
when "--accessor"
arg.split(/,/).each do |accessor|
if accessor =~ /^(\w+)(=(.*))?$/
accessors << $1
@extra_accessor_flags[$1] = $3
end
end
when "--diagram"
check_diagram
@diagram = true
when "--fileboxes"
@fileboxes = true if @diagram
when "--fmt"
@generator_name = arg.downcase
setup_generator(generators)
when "--help"
OptionList.usage(generators.keys)
when "--help-output"
OptionList.help_output
when "--image-format"
if ['gif', 'png', 'jpeg', 'jpg'].include?(arg)
@image_format = arg
else
raise GetoptLong::InvalidOption.new("unknown image format: #{arg}")
end
when "--include"
@rdoc_include.concat arg.split(/\s*,\s*/)
when "--ri", "--ri-site", "--ri-system"
@generator_name = "ri"
@op_dir = case opt
when "--ri" then RI::Paths::HOMEDIR
when "--ri-site" then RI::Paths::SITEDIR
when "--ri-system" then RI::Paths::SYSDIR
else fail opt
end
setup_generator(generators)
when "--tab-width"
begin
@tab_width = Integer(arg)
rescue
$stderr.puts "Invalid tab width: '#{arg}'"
exit 1
end
when "--extension"
new, old = arg.split(/=/, 2)
OptionList.error("Invalid parameter to '-E'") unless new && old
unless RDoc::ParserFactory.alias_extension(old, new)
OptionList.error("Unknown extension .#{old} to -E")
end
when "--force-update"
@force_update = true
when "--version"
puts VERSION_STRING
exit
end
end
@files = ARGV.dup
@rdoc_include << "." if @rdoc_include.empty?
if @exclude.empty?
@exclude = nil
else
@exclude = Regexp.new(@exclude.join("|"))
end
check_files
# If no template was specified, use the default
# template for the output formatter
@template ||= @generator_name
# Generate a regexp from the accessors
unless accessors.empty?
re = '^(' + accessors.map{|a| Regexp.quote(a)}.join('|') + ')$'
@extra_accessors = Regexp.new(re)
end
rescue GetoptLong::InvalidOption, GetoptLong::MissingArgument => error
OptionList.error(error.message)
ensure
ARGV.replace(old_argv)
end
end
def title
@title ||= "RDoc Documentation"
end
# Set the title, but only if not already set. This means that a title set from
# the command line trumps one set in a source file
def title=(string)
@title ||= string
end
private
# Set up an output generator for the format in @generator_name
def setup_generator(generators)
@generator = generators[@generator_name]
if !@generator
OptionList.error("Invalid output formatter")
end
if @generator_name == "xml"
@all_one_file = true
@inline_source = true
end
end
# Check that the right version of 'dot' is available.
# Unfortuately this doesn't work correctly under Windows NT,
# so we'll bypass the test under Windows
def check_diagram
return if RUBY_PLATFORM =~ /mswin|cygwin|mingw|bccwin/
ok = false
ver = nil
IO.popen("dot -V 2>&1") do |io|
ver = io.read
if ver =~ /dot.+version(?:\s+gviz)?\s+(\d+)\.(\d+)/
ok = ($1.to_i > 1) || ($1.to_i == 1 && $2.to_i >= 8)
end
end
unless ok
if ver =~ /^dot.+version/
$stderr.puts "Warning: You may need dot V1.8.6 or later to use\n",
"the --diagram option correctly. You have:\n\n ",
ver,
"\nDiagrams might have strange background colors.\n\n"
else
$stderr.puts "You need the 'dot' program to produce diagrams.",
"(see http://www.research.att.com/sw/tools/graphviz/)\n\n"
exit
end
# exit
end
end
# Check that the files on the command line exist
def check_files
@files.each do |f|
stat = File.stat f rescue error("File not found: #{f}")
error("File '#{f}' not readable") unless stat.readable?
end
end
def error(str)
$stderr.puts str
exit(1)
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/rdoc.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/rdoc.rb | # See README.
#
VERSION_STRING = %{RDoc V1.0.1 - 20041108}
require 'rdoc/parsers/parse_rb.rb'
require 'rdoc/parsers/parse_c.rb'
require 'rdoc/parsers/parse_f95.rb'
require 'rdoc/parsers/parse_simple.rb'
require 'rdoc/options'
require 'rdoc/diagram'
require 'find'
require 'ftools'
require 'time'
# We put rdoc stuff in the RDoc module to avoid namespace
# clutter.
#
# ToDo: This isn't universally true.
#
# :include: README
module RDoc
# Name of the dotfile that contains the description of files to be
# processed in the current directory
DOT_DOC_FILENAME = ".document"
# Simple stats collector
class Stats
attr_accessor :num_files, :num_classes, :num_modules, :num_methods
def initialize
@num_files = @num_classes = @num_modules = @num_methods = 0
@start = Time.now
end
def print
puts "Files: #@num_files"
puts "Classes: #@num_classes"
puts "Modules: #@num_modules"
puts "Methods: #@num_methods"
puts "Elapsed: " + sprintf("%0.3fs", Time.now - @start)
end
end
# Exception thrown by any rdoc error. Only the #message part is
# of use externally.
class RDocError < Exception
end
# Encapsulate the production of rdoc documentation. Basically
# you can use this as you would invoke rdoc from the command
# line:
#
# rdoc = RDoc::RDoc.new
# rdoc.document(args)
#
# where _args_ is an array of strings, each corresponding to
# an argument you'd give rdoc on the command line. See rdoc/rdoc.rb
# for details.
class RDoc
##
# This is the list of output generators that we
# support
Generator = Struct.new(:file_name, :class_name, :key)
GENERATORS = {}
$:.collect {|d|
File::expand_path(d)
}.find_all {|d|
File::directory?("#{d}/rdoc/generators")
}.each {|dir|
Dir::entries("#{dir}/rdoc/generators").each {|gen|
next unless /(\w+)_generator.rb$/ =~ gen
type = $1
unless GENERATORS.has_key? type
GENERATORS[type] = Generator.new("rdoc/generators/#{gen}",
"#{type.upcase}Generator".intern,
type)
end
}
}
#######
private
#######
##
# Report an error message and exit
def error(msg)
raise RDocError.new(msg)
end
##
# Create an output dir if it doesn't exist. If it does
# exist, but doesn't contain the flag file <tt>created.rid</tt>
# then we refuse to use it, as we may clobber some
# manually generated documentation
def setup_output_dir(op_dir, force)
flag_file = output_flag_file(op_dir)
if File.exist?(op_dir)
unless File.directory?(op_dir)
error "'#{op_dir}' exists, and is not a directory"
end
begin
created = File.read(flag_file)
rescue SystemCallError
error "\nDirectory #{op_dir} already exists, but it looks like it\n" +
"isn't an RDoc directory. Because RDoc doesn't want to risk\n" +
"destroying any of your existing files, you'll need to\n" +
"specify a different output directory name (using the\n" +
"--op <dir> option).\n\n"
else
last = (Time.parse(created) unless force rescue nil)
end
else
File.makedirs(op_dir)
end
last
end
# Update the flag file in an output directory.
def update_output_dir(op_dir, time)
File.open(output_flag_file(op_dir), "w") {|f| f.puts time.rfc2822 }
end
# Return the path name of the flag file in an output directory.
def output_flag_file(op_dir)
File.join(op_dir, "created.rid")
end
# The .document file contains a list of file and directory name
# patterns, representing candidates for documentation. It may
# also contain comments (starting with '#')
def parse_dot_doc_file(in_dir, filename, options)
# read and strip comments
patterns = File.read(filename).gsub(/#.*/, '')
result = []
patterns.split.each do |patt|
candidates = Dir.glob(File.join(in_dir, patt))
result.concat(normalized_file_list(options, candidates))
end
result
end
# Given a list of files and directories, create a list
# of all the Ruby files they contain.
#
# If +force_doc+ is true, we always add the given files.
# If false, only add files that we guarantee we can parse
# It is true when looking at files given on the command line,
# false when recursing through subdirectories.
#
# The effect of this is that if you want a file with a non-
# standard extension parsed, you must name it explicity.
#
def normalized_file_list(options, relative_files, force_doc = false, exclude_pattern=nil)
file_list = []
relative_files.each do |rel_file_name|
next if exclude_pattern && exclude_pattern =~ rel_file_name
stat = File.stat(rel_file_name)
case type = stat.ftype
when "file"
next if @last_created and stat.mtime < @last_created
file_list << rel_file_name.sub(/^\.\//, '') if force_doc || ParserFactory.can_parse(rel_file_name)
when "directory"
next if rel_file_name == "CVS" || rel_file_name == ".svn"
dot_doc = File.join(rel_file_name, DOT_DOC_FILENAME)
if File.file?(dot_doc)
file_list.concat(parse_dot_doc_file(rel_file_name, dot_doc, options))
else
file_list.concat(list_files_in_directory(rel_file_name, options))
end
else
raise RDocError.new("I can't deal with a #{type} #{rel_file_name}")
end
end
file_list
end
# Return a list of the files to be processed in
# a directory. We know that this directory doesn't have
# a .document file, so we're looking for real files. However
# we may well contain subdirectories which must
# be tested for .document files
def list_files_in_directory(dir, options)
normalized_file_list(options, Dir.glob(File.join(dir, "*")), false, options.exclude)
end
# Parse each file on the command line, recursively entering
# directories
def parse_files(options)
file_info = []
files = options.files
files = ["."] if files.empty?
file_list = normalized_file_list(options, files, true)
file_list.each do |fn|
$stderr.printf("\n%35s: ", File.basename(fn)) unless options.quiet
content = File.open(fn, "r") {|f| f.read}
top_level = TopLevel.new(fn)
parser = ParserFactory.parser_for(top_level, fn, content, options, @stats)
file_info << parser.scan
@stats.num_files += 1
end
file_info
end
public
###################################################################
#
# Format up one or more files according to the given arguments.
# For simplicity, _argv_ is an array of strings, equivalent to the
# strings that would be passed on the command line. (This isn't a
# coincidence, as we _do_ pass in ARGV when running
# interactively). For a list of options, see rdoc/rdoc.rb. By
# default, output will be stored in a directory called +doc+ below
# the current directory, so make sure you're somewhere writable
# before invoking.
#
# Throws: RDocError on error
def document(argv)
TopLevel::reset
@stats = Stats.new
options = Options.instance
options.parse(argv, GENERATORS)
@last_created = nil
unless options.all_one_file
@last_created = setup_output_dir(options.op_dir, options.force_update)
end
start_time = Time.now
file_info = parse_files(options)
if file_info.empty?
$stderr.puts "\nNo newer files." unless options.quiet
else
gen = options.generator
$stderr.puts "\nGenerating #{gen.key.upcase}..." unless options.quiet
require gen.file_name
gen_class = Generators.const_get(gen.class_name)
gen = gen_class.for(options)
pwd = Dir.pwd
Dir.chdir(options.op_dir) unless options.all_one_file
begin
Diagram.new(file_info, options).draw if options.diagram
gen.generate(file_info)
update_output_dir(".", start_time)
ensure
Dir.chdir(pwd)
end
end
unless options.quiet
puts
@stats.print
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/tokenstream.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/tokenstream.rb | # A TokenStream is a list of tokens, gathered during the parse
# of some entity (say a method). Entities populate these streams
# by being registered with the lexer. Any class can collect tokens
# by including TokenStream. From the outside, you use such an object
# by calling the start_collecting_tokens method, followed by calls
# to add_token and pop_token
module TokenStream
def token_stream
@token_stream
end
def start_collecting_tokens
@token_stream = []
end
def add_token(tk)
@token_stream << tk
end
def add_tokens(tks)
tks.each {|tk| add_token(tk)}
end
def pop_token
@token_stream.pop
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/code_objects.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/code_objects.rb | # We represent the various high-level code constructs that appear
# in Ruby programs: classes, modules, methods, and so on.
require 'rdoc/tokenstream'
module RDoc
# We contain the common stuff for contexts (which are containers)
# and other elements (methods, attributes and so on)
#
class CodeObject
attr_accessor :parent
# We are the model of the code, but we know that at some point
# we will be worked on by viewers. By implementing the Viewable
# protocol, viewers can associated themselves with these objects.
attr_accessor :viewer
# are we done documenting (ie, did we come across a :enddoc:)?
attr_accessor :done_documenting
# Which section are we in
attr_accessor :section
# do we document ourselves?
attr_reader :document_self
def document_self=(val)
@document_self = val
if !val
remove_methods_etc
end
end
# set and cleared by :startdoc: and :enddoc:, this is used to toggle
# the capturing of documentation
def start_doc
@document_self = true
@document_children = true
end
def stop_doc
@document_self = false
@document_children = false
end
# do we document ourselves and our children
attr_reader :document_children
def document_children=(val)
@document_children = val
if !val
remove_classes_and_modules
end
end
# Do we _force_ documentation, even is we wouldn't normally show the entity
attr_accessor :force_documentation
# Default callbacks to nothing, but this is overridden for classes
# and modules
def remove_classes_and_modules
end
def remove_methods_etc
end
def initialize
@document_self = true
@document_children = true
@force_documentation = false
@done_documenting = false
end
# Access the code object's comment
attr_reader :comment
# Update the comment, but don't overwrite a real comment
# with an empty one
def comment=(comment)
@comment = comment unless comment.empty?
end
# There's a wee trick we pull. Comment blocks can have directives that
# override the stuff we extract during the parse. So, we have a special
# class method, attr_overridable, that lets code objects list
# those directives. Wehn a comment is assigned, we then extract
# out any matching directives and update our object
def CodeObject.attr_overridable(name, *aliases)
@overridables ||= {}
attr_accessor name
aliases.unshift name
aliases.each do |directive_name|
@overridables[directive_name.to_s] = name
end
end
end
# A Context is something that can hold modules, classes, methods,
# attributes, aliases, requires, and includes. Classes, modules, and
# files are all Contexts.
class Context < CodeObject
attr_reader :name, :method_list, :attributes, :aliases, :constants
attr_reader :requires, :includes, :in_files, :visibility
attr_reader :sections
class Section
attr_reader :title, :comment, :sequence
@@sequence = "SEC00000"
def initialize(title, comment)
@title = title
@@sequence.succ!
@sequence = @@sequence.dup
set_comment(comment)
end
private
# Set the comment for this section from the original comment block
# If the first line contains :section:, strip it and use the rest. Otherwise
# remove lines up to the line containing :section:, and look for
# those lines again at the end and remove them. This lets us write
#
# # ---------------------
# # :SECTION: The title
# # The body
# # ---------------------
def set_comment(comment)
return unless comment
if comment =~ /^.*?:section:.*$/
start = $`
rest = $'
if start.empty?
@comment = rest
else
@comment = rest.sub(/#{start.chomp}\Z/, '')
end
else
@comment = comment
end
@comment = nil if @comment.empty?
end
end
def initialize
super()
@in_files = []
@name ||= "unknown"
@comment ||= ""
@parent = nil
@visibility = :public
@current_section = Section.new(nil, nil)
@sections = [ @current_section ]
initialize_methods_etc
initialize_classes_and_modules
end
# map the class hash to an array externally
def classes
@classes.values
end
# map the module hash to an array externally
def modules
@modules.values
end
# Change the default visibility for new methods
def ongoing_visibility=(vis)
@visibility = vis
end
# Given an array +methods+ of method names, set the
# visibility of the corresponding AnyMethod object
def set_visibility_for(methods, vis, singleton=false)
count = 0
@method_list.each do |m|
if methods.include?(m.name) && m.singleton == singleton
m.visibility = vis
count += 1
end
end
return if count == methods.size || singleton
# perhaps we need to look at attributes
@attributes.each do |a|
if methods.include?(a.name)
a.visibility = vis
count += 1
end
end
end
# Record the file that we happen to find it in
def record_location(toplevel)
@in_files << toplevel unless @in_files.include?(toplevel)
end
# Return true if at least part of this thing was defined in +file+
def defined_in?(file)
@in_files.include?(file)
end
def add_class(class_type, name, superclass)
add_class_or_module(@classes, class_type, name, superclass)
end
def add_module(class_type, name)
add_class_or_module(@modules, class_type, name, nil)
end
def add_method(a_method)
puts "Adding #@visibility method #{a_method.name} to #@name" if $DEBUG
a_method.visibility = @visibility
add_to(@method_list, a_method)
end
def add_attribute(an_attribute)
add_to(@attributes, an_attribute)
end
def add_alias(an_alias)
meth = find_instance_method_named(an_alias.old_name)
if meth
new_meth = AnyMethod.new(an_alias.text, an_alias.new_name)
new_meth.is_alias_for = meth
new_meth.singleton = meth.singleton
new_meth.params = meth.params
new_meth.comment = "Alias for \##{meth.name}"
meth.add_alias(new_meth)
add_method(new_meth)
else
add_to(@aliases, an_alias)
end
end
def add_include(an_include)
add_to(@includes, an_include)
end
def add_constant(const)
add_to(@constants, const)
end
# Requires always get added to the top-level (file) context
def add_require(a_require)
if self.kind_of? TopLevel
add_to(@requires, a_require)
else
parent.add_require(a_require)
end
end
def add_class_or_module(collection, class_type, name, superclass=nil)
cls = collection[name]
if cls
puts "Reusing class/module #{name}" if $DEBUG
else
cls = class_type.new(name, superclass)
puts "Adding class/module #{name} to #@name" if $DEBUG
# collection[name] = cls if @document_self && !@done_documenting
collection[name] = cls if !@done_documenting
cls.parent = self
cls.section = @current_section
end
cls
end
def add_to(array, thing)
array << thing if @document_self && !@done_documenting
thing.parent = self
thing.section = @current_section
end
# If a class's documentation is turned off after we've started
# collecting methods etc., we need to remove the ones
# we have
def remove_methods_etc
initialize_methods_etc
end
def initialize_methods_etc
@method_list = []
@attributes = []
@aliases = []
@requires = []
@includes = []
@constants = []
end
# and remove classes and modules when we see a :nodoc: all
def remove_classes_and_modules
initialize_classes_and_modules
end
def initialize_classes_and_modules
@classes = {}
@modules = {}
end
# Find a named module
def find_module_named(name)
return self if self.name == name
res = @modules[name] || @classes[name]
return res if res
find_enclosing_module_named(name)
end
# find a module at a higher scope
def find_enclosing_module_named(name)
parent && parent.find_module_named(name)
end
# Iterate over all the classes and modules in
# this object
def each_classmodule
@modules.each_value {|m| yield m}
@classes.each_value {|c| yield c}
end
def each_method
@method_list.each {|m| yield m}
end
def each_attribute
@attributes.each {|a| yield a}
end
def each_constant
@constants.each {|c| yield c}
end
# Return the toplevel that owns us
def toplevel
return @toplevel if defined? @toplevel
@toplevel = self
@toplevel = @toplevel.parent until TopLevel === @toplevel
@toplevel
end
# allow us to sort modules by name
def <=>(other)
name <=> other.name
end
# Look up the given symbol. If method is non-nil, then
# we assume the symbol references a module that
# contains that method
def find_symbol(symbol, method=nil)
result = nil
case symbol
when /^::(.*)/
result = toplevel.find_symbol($1)
when /::/
modules = symbol.split(/::/)
unless modules.empty?
module_name = modules.shift
result = find_module_named(module_name)
if result
modules.each do |module_name|
result = result.find_module_named(module_name)
break unless result
end
end
end
else
# if a method is specified, then we're definitely looking for
# a module, otherwise it could be any symbol
if method
result = find_module_named(symbol)
else
result = find_local_symbol(symbol)
if result.nil?
if symbol =~ /^[A-Z]/
result = parent
while result && result.name != symbol
result = result.parent
end
end
end
end
end
if result && method
if !result.respond_to?(:find_local_symbol)
p result.name
p method
fail
end
result = result.find_local_symbol(method)
end
result
end
def find_local_symbol(symbol)
res = find_method_named(symbol) ||
find_constant_named(symbol) ||
find_attribute_named(symbol) ||
find_module_named(symbol)
end
# Handle sections
def set_current_section(title, comment)
@current_section = Section.new(title, comment)
@sections << @current_section
end
private
# Find a named method, or return nil
def find_method_named(name)
@method_list.find {|meth| meth.name == name}
end
# Find a named instance method, or return nil
def find_instance_method_named(name)
@method_list.find {|meth| meth.name == name && !meth.singleton}
end
# Find a named constant, or return nil
def find_constant_named(name)
@constants.find {|m| m.name == name}
end
# Find a named attribute, or return nil
def find_attribute_named(name)
@attributes.find {|m| m.name == name}
end
end
# A TopLevel context is a source file
class TopLevel < Context
attr_accessor :file_stat
attr_accessor :file_relative_name
attr_accessor :file_absolute_name
attr_accessor :diagram
@@all_classes = {}
@@all_modules = {}
def TopLevel::reset
@@all_classes = {}
@@all_modules = {}
end
def initialize(file_name)
super()
@name = "TopLevel"
@file_relative_name = file_name
@file_absolute_name = file_name
@file_stat = File.stat(file_name)
@diagram = nil
end
def full_name
nil
end
# Adding a class or module to a TopLevel is special, as we only
# want one copy of a particular top-level class. For example,
# if both file A and file B implement class C, we only want one
# ClassModule object for C. This code arranges to share
# classes and modules between files.
def add_class_or_module(collection, class_type, name, superclass)
cls = collection[name]
if cls
puts "Reusing class/module #{name}" if $DEBUG
else
if class_type == NormalModule
all = @@all_modules
else
all = @@all_classes
end
cls = all[name]
if !cls
cls = class_type.new(name, superclass)
all[name] = cls unless @done_documenting
end
puts "Adding class/module #{name} to #@name" if $DEBUG
collection[name] = cls unless @done_documenting
cls.parent = self
end
cls
end
def TopLevel.all_classes_and_modules
@@all_classes.values + @@all_modules.values
end
def TopLevel.find_class_named(name)
@@all_classes.each_value do |c|
res = c.find_class_named(name)
return res if res
end
nil
end
def find_local_symbol(symbol)
find_class_or_module_named(symbol) || super
end
def find_class_or_module_named(symbol)
@@all_classes.each_value {|c| return c if c.name == symbol}
@@all_modules.each_value {|m| return m if m.name == symbol}
nil
end
# Find a named module
def find_module_named(name)
find_class_or_module_named(name) || find_enclosing_module_named(name)
end
end
# ClassModule is the base class for objects representing either a
# class or a module.
class ClassModule < Context
attr_reader :superclass
attr_accessor :diagram
def initialize(name, superclass = nil)
@name = name
@diagram = nil
@superclass = superclass
@comment = ""
super()
end
# Return the fully qualified name of this class or module
def full_name
if @parent && @parent.full_name
@parent.full_name + "::" + @name
else
@name
end
end
def http_url(prefix)
path = full_name.split("::")
File.join(prefix, *path) + ".html"
end
# Return +true+ if this object represents a module
def is_module?
false
end
# to_s is simply for debugging
def to_s
res = self.class.name + ": " + @name
res << @comment.to_s
res << super
res
end
def find_class_named(name)
return self if full_name == name
@classes.each_value {|c| return c if c.find_class_named(name) }
nil
end
end
# Anonymous classes
class AnonClass < ClassModule
end
# Normal classes
class NormalClass < ClassModule
end
# Singleton classes
class SingleClass < ClassModule
end
# Module
class NormalModule < ClassModule
def is_module?
true
end
end
# AnyMethod is the base class for objects representing methods
class AnyMethod < CodeObject
attr_accessor :name
attr_accessor :visibility
attr_accessor :block_params
attr_accessor :dont_rename_initialize
attr_accessor :singleton
attr_reader :aliases # list of other names for this method
attr_accessor :is_alias_for # or a method we're aliasing
attr_overridable :params, :param, :parameters, :parameter
attr_accessor :call_seq
include TokenStream
def initialize(text, name)
super()
@text = text
@name = name
@token_stream = nil
@visibility = :public
@dont_rename_initialize = false
@block_params = nil
@aliases = []
@is_alias_for = nil
@comment = ""
@call_seq = nil
end
def <=>(other)
@name <=> other.name
end
def to_s
res = self.class.name + ": " + @name + " (" + @text + ")\n"
res << @comment.to_s
res
end
def param_seq
p = params.gsub(/\s*\#.*/, '')
p = p.tr("\n", " ").squeeze(" ")
p = "(" + p + ")" unless p[0] == ?(
if (block = block_params)
# If this method has explicit block parameters, remove any
# explicit &block
$stderr.puts p
p.sub!(/,?\s*&\w+/)
$stderr.puts p
block.gsub!(/\s*\#.*/, '')
block = block.tr("\n", " ").squeeze(" ")
if block[0] == ?(
block.sub!(/^\(/, '').sub!(/\)/, '')
end
p << " {|#{block}| ...}"
end
p
end
def add_alias(method)
@aliases << method
end
end
# Represent an alias, which is an old_name/ new_name pair associated
# with a particular context
class Alias < CodeObject
attr_accessor :text, :old_name, :new_name, :comment
def initialize(text, old_name, new_name, comment)
super()
@text = text
@old_name = old_name
@new_name = new_name
self.comment = comment
end
def to_s
"alias: #{self.old_name} -> #{self.new_name}\n#{self.comment}"
end
end
# Represent a constant
class Constant < CodeObject
attr_accessor :name, :value
def initialize(name, value, comment)
super()
@name = name
@value = value
self.comment = comment
end
end
# Represent attributes
class Attr < CodeObject
attr_accessor :text, :name, :rw, :visibility
def initialize(text, name, rw, comment)
super()
@text = text
@name = name
@rw = rw
@visibility = :public
self.comment = comment
end
def to_s
"attr: #{self.name} #{self.rw}\n#{self.comment}"
end
def <=>(other)
self.name <=> other.name
end
end
# a required file
class Require < CodeObject
attr_accessor :name
def initialize(name, comment)
super()
@name = name.gsub(/'|"/, "") #'
self.comment = comment
end
end
# an included module
class Include < CodeObject
attr_accessor :name
def initialize(name, comment)
super()
@name = name
self.comment = comment
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/template.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/template.rb | # Cheap-n-cheerful HTML page template system. You create a
# template containing:
#
# * variable names between percent signs (<tt>%fred%</tt>)
# * blocks of repeating stuff:
#
# START:key
# ... stuff
# END:key
#
# You feed the code a hash. For simple variables, the values
# are resolved directly from the hash. For blocks, the hash entry
# corresponding to +key+ will be an array of hashes. The block will
# be generated once for each entry. Blocks can be nested arbitrarily
# deeply.
#
# The template may also contain
#
# IF:key
# ... stuff
# ENDIF:key
#
# _stuff_ will only be included in the output if the corresponding
# key is set in the value hash.
#
# Usage: Given a set of templates <tt>T1, T2,</tt> etc
#
# values = { "name" => "Dave", state => "TX" }
#
# t = TemplatePage.new(T1, T2, T3)
# File.open(name, "w") {|f| t.write_html_on(f, values)}
# or
# res = ''
# t.write_html_on(res, values)
#
#
class TemplatePage
##########
# A context holds a stack of key/value pairs (like a symbol
# table). When asked to resolve a key, it first searches the top of
# the stack, then the next level, and so on until it finds a match
# (or runs out of entries)
class Context
def initialize
@stack = []
end
def push(hash)
@stack.push(hash)
end
def pop
@stack.pop
end
# Find a scalar value, throwing an exception if not found. This
# method is used when substituting the %xxx% constructs
def find_scalar(key)
@stack.reverse_each do |level|
if val = level[key]
return val unless val.kind_of? Array
end
end
raise "Template error: can't find variable '#{key}'"
end
# Lookup any key in the stack of hashes
def lookup(key)
@stack.reverse_each do |level|
val = level[key]
return val if val
end
nil
end
end
#########
# Simple class to read lines out of a string
class LineReader
# we're initialized with an array of lines
def initialize(lines)
@lines = lines
end
# read the next line
def read
@lines.shift
end
# Return a list of lines up to the line that matches
# a pattern. That last line is discarded.
def read_up_to(pattern)
res = []
while line = read
if pattern.match(line)
return LineReader.new(res)
else
res << line
end
end
raise "Missing end tag in template: #{pattern.source}"
end
# Return a copy of ourselves that can be modified without
# affecting us
def dup
LineReader.new(@lines.dup)
end
end
# +templates+ is an array of strings containing the templates.
# We start at the first, and substitute in subsequent ones
# where the string <tt>!INCLUDE!</tt> occurs. For example,
# we could have the overall page template containing
#
# <html><body>
# <h1>Master</h1>
# !INCLUDE!
# </bost></html>
#
# and substitute subpages in to it by passing [master, sub_page].
# This gives us a cheap way of framing pages
def initialize(*templates)
result = "!INCLUDE!"
templates.each do |content|
result.sub!(/!INCLUDE!/, content)
end
@lines = LineReader.new(result.split($/))
end
# Render the templates into HTML, storing the result on +op+
# using the method <tt><<</tt>. The <tt>value_hash</tt> contains
# key/value pairs used to drive the substitution (as described above)
def write_html_on(op, value_hash)
@context = Context.new
op << substitute_into(@lines, value_hash).tr("\000", '\\')
end
# Substitute a set of key/value pairs into the given template.
# Keys with scalar values have them substituted directly into
# the page. Those with array values invoke <tt>substitute_array</tt>
# (below), which examples a block of the template once for each
# row in the array.
#
# This routine also copes with the <tt>IF:</tt>_key_ directive,
# removing chunks of the template if the corresponding key
# does not appear in the hash, and the START: directive, which
# loops its contents for each value in an array
def substitute_into(lines, values)
@context.push(values)
skip_to = nil
result = []
while line = lines.read
case line
when /^IF:(\w+)/
lines.read_up_to(/^ENDIF:#$1/) unless @context.lookup($1)
when /^IFNOT:(\w+)/
lines.read_up_to(/^ENDIF:#$1/) if @context.lookup($1)
when /^ENDIF:/
;
when /^START:(\w+)/
tag = $1
body = lines.read_up_to(/^END:#{tag}/)
inner_values = @context.lookup(tag)
raise "unknown tag: #{tag}" unless inner_values
raise "not array: #{tag}" unless inner_values.kind_of?(Array)
inner_values.each do |vals|
result << substitute_into(body.dup, vals)
end
else
result << expand_line(line.dup)
end
end
@context.pop
result.join("\n")
end
# Given an individual line, we look for %xxx% constructs and
# HREF:ref:name: constructs, substituting for each.
def expand_line(line)
# Generate a cross reference if a reference is given,
# otherwise just fill in the name part
line.gsub!(/HREF:(\w+?):(\w+?):/) {
ref = @context.lookup($1)
name = @context.find_scalar($2)
if ref and !ref.kind_of?(Array)
"<a href=\"#{ref}\">#{name}</a>"
else
name
end
}
# Substitute in values for %xxx% constructs. This is made complex
# because the replacement string may contain characters that are
# meaningful to the regexp (like \1)
line = line.gsub(/%([a-zA-Z]\w*)%/) {
val = @context.find_scalar($1)
val.tr('\\', "\000")
}
line
rescue Exception => e
$stderr.puts "Error in template: #{e}"
$stderr.puts "Original line: #{line}"
exit
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/dot/dot.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/dot/dot.rb | module DOT
# these glogal vars are used to make nice graph source
$tab = ' '
$tab2 = $tab * 2
# if we don't like 4 spaces, we can change it any time
def change_tab( t )
$tab = t
$tab2 = t * 2
end
# options for node declaration
NODE_OPTS = [
'bgcolor',
'color',
'fontcolor',
'fontname',
'fontsize',
'height',
'width',
'label',
'layer',
'rank',
'shape',
'shapefile',
'style',
'URL',
]
# options for edge declaration
EDGE_OPTS = [
'color',
'decorate',
'dir',
'fontcolor',
'fontname',
'fontsize',
'id',
'label',
'layer',
'lhead',
'ltail',
'minlen',
'style',
'weight'
]
# options for graph declaration
GRAPH_OPTS = [
'bgcolor',
'center',
'clusterrank',
'color',
'compound',
'concentrate',
'fillcolor',
'fontcolor',
'fontname',
'fontsize',
'label',
'layerseq',
'margin',
'mclimit',
'nodesep',
'nslimit',
'ordering',
'orientation',
'page',
'rank',
'rankdir',
'ranksep',
'ratio',
'size',
'style',
'URL'
]
# a root class for any element in dot notation
class DOTSimpleElement
attr_accessor :name
def initialize( params = {} )
@label = params['name'] ? params['name'] : ''
end
def to_s
@name
end
end
# an element that has options ( node, edge or graph )
class DOTElement < DOTSimpleElement
#attr_reader :parent
attr_accessor :name, :options
def initialize( params = {}, option_list = [] )
super( params )
@name = params['name'] ? params['name'] : nil
@parent = params['parent'] ? params['parent'] : nil
@options = {}
option_list.each{ |i|
@options[i] = params[i] if params[i]
}
@options['label'] ||= @name if @name != 'node'
end
def each_option
@options.each{ |i| yield i }
end
def each_option_pair
@options.each_pair{ |key, val| yield key, val }
end
#def parent=( thing )
# @parent.delete( self ) if defined?( @parent ) and @parent
# @parent = thing
#end
end
# this is used when we build nodes that have shape=record
# ports don't have options :)
class DOTPort < DOTSimpleElement
attr_accessor :label
def initialize( params = {} )
super( params )
@name = params['label'] ? params['label'] : ''
end
def to_s
( @name && @name != "" ? "<#{@name}>" : "" ) + "#{@label}"
end
end
# node element
class DOTNode < DOTElement
def initialize( params = {}, option_list = NODE_OPTS )
super( params, option_list )
@ports = params['ports'] ? params['ports'] : []
end
def each_port
@ports.each{ |i| yield i }
end
def << ( thing )
@ports << thing
end
def push ( thing )
@ports.push( thing )
end
def pop
@ports.pop
end
def to_s( t = '' )
label = @options['shape'] != 'record' && @ports.length == 0 ?
@options['label'] ?
t + $tab + "label = \"#{@options['label']}\"\n" :
'' :
t + $tab + 'label = "' + " \\\n" +
t + $tab2 + "#{@options['label']}| \\\n" +
@ports.collect{ |i|
t + $tab2 + i.to_s
}.join( "| \\\n" ) + " \\\n" +
t + $tab + '"' + "\n"
t + "#{@name} [\n" +
@options.to_a.collect{ |i|
i[1] && i[0] != 'label' ?
t + $tab + "#{i[0]} = #{i[1]}" : nil
}.compact.join( ",\n" ) + ( label != '' ? ",\n" : "\n" ) +
label +
t + "]\n"
end
end
# subgraph element is the same to graph, but has another header in dot
# notation
class DOTSubgraph < DOTElement
def initialize( params = {}, option_list = GRAPH_OPTS )
super( params, option_list )
@nodes = params['nodes'] ? params['nodes'] : []
@dot_string = 'subgraph'
end
def each_node
@nodes.each{ |i| yield i }
end
def << ( thing )
@nodes << thing
end
def push( thing )
@nodes.push( thing )
end
def pop
@nodes.pop
end
def to_s( t = '' )
hdr = t + "#{@dot_string} #{@name} {\n"
options = @options.to_a.collect{ |name, val|
val && name != 'label' ?
t + $tab + "#{name} = #{val}" :
name ? t + $tab + "#{name} = \"#{val}\"" : nil
}.compact.join( "\n" ) + "\n"
nodes = @nodes.collect{ |i|
i.to_s( t + $tab )
}.join( "\n" ) + "\n"
hdr + options + nodes + t + "}\n"
end
end
# this is graph
class DOTDigraph < DOTSubgraph
def initialize( params = {}, option_list = GRAPH_OPTS )
super( params, option_list )
@dot_string = 'digraph'
end
end
# this is edge
class DOTEdge < DOTElement
attr_accessor :from, :to
def initialize( params = {}, option_list = EDGE_OPTS )
super( params, option_list )
@from = params['from'] ? params['from'] : nil
@to = params['to'] ? params['to'] : nil
end
def to_s( t = '' )
t + "#{@from} -> #{to} [\n" +
@options.to_a.collect{ |i|
i[1] && i[0] != 'label' ?
t + $tab + "#{i[0]} = #{i[1]}" :
i[1] ? t + $tab + "#{i[0]} = \"#{i[1]}\"" : nil
}.compact.join( "\n" ) + "\n" + t + "]\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/1.8/rdoc/ri/ri_options.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/ri/ri_options.rb | # We handle the parsing of options, and subsequently as a singleton
# object to be queried for option values
module RI
require 'rdoc/ri/ri_paths'
require 'rdoc/ri/ri_display'
VERSION_STRING = "ri v1.0.1 - 20041108"
class Options
require 'singleton'
require 'getoptlong'
include Singleton
# No not use a pager. Writable, because ri sets it if it
# can't find a pager
attr_accessor :use_stdout
# should we just display a class list and exit
attr_reader :list_classes
# should we look for java classes instead of ruby rdoc
attr_reader :java_classes
# should we display a list of all names
attr_reader :list_names
# The width of the output line
attr_reader :width
# the formatting we apply to the output
attr_reader :formatter
# the directory we search for original documentation
attr_reader :doc_dir
module OptionList
OPTION_LIST = [
[ "--help", "-h", nil,
"you're looking at it" ],
[ "--classes", "-c", nil,
"Display the names of classes and modules we\n" +
"know about"],
[ "--java", "-j", nil,
"Interpret arguments as the names of Java classes\n"],
[ "--doc-dir", "-d", "<dirname>",
"A directory to search for documentation. If not\n" +
"specified, we search the standard rdoc/ri directories.\n" +
"May be repeated."],
[ "--system", nil, nil,
"Include documentation from Ruby's standard library:\n " +
RI::Paths::SYSDIR ],
[ "--site", nil, nil,
"Include documentation from libraries installed in site_lib:\n " +
RI::Paths::SITEDIR ],
[ "--home", nil, nil,
"Include documentation stored in ~/.rdoc:\n " +
(RI::Paths::HOMEDIR || "No ~/.rdoc found") ],
[ "--gems", nil, nil,
"Include documentation from RubyGems:\n" +
(RI::Paths::GEMDIRS ?
Gem.path.map { |dir| " #{dir}/doc/*/ri" }.join("\n") :
"No Rubygems ri found.") ],
[ "--format", "-f", "<name>",
"Format to use when displaying output:\n" +
" " + RI::TextFormatter.list + "\n" +
"Use 'bs' (backspace) with most pager programs.\n" +
"To use ANSI, either also use the -T option, or\n" +
"tell your pager to allow control characters\n" +
"(for example using the -R option to less)"],
[ "--list-names", "-l", nil,
"List all the names known to RDoc, one per line"
],
[ "--no-pager", "-T", nil,
"Send output directly to stdout."
],
[ "--width", "-w", "output width",
"Set the width of the output" ],
[ "--version", "-v", nil,
"Display the version of ri"
],
]
def OptionList.options
OPTION_LIST.map do |long, short, arg,|
option = []
option << long
option << short unless short.nil?
option << (arg ? GetoptLong::REQUIRED_ARGUMENT :
GetoptLong::NO_ARGUMENT)
option
end
end
def OptionList.strip_output(text)
text =~ /^\s+/
leading_spaces = $&
text.gsub!(/^#{leading_spaces}/, '')
$stdout.puts text
end
# Show an error and exit
def OptionList.error(msg)
$stderr.puts
$stderr.puts msg
name = File.basename $PROGRAM_NAME
$stderr.puts "\nFor help on options, try '#{name} --help'\n\n"
exit 1
end
# Show usage and exit
def OptionList.usage(short_form=false)
puts
puts(RI::VERSION_STRING)
puts
name = File.basename($0)
directories = [
RI::Paths::SYSDIR,
RI::Paths::SITEDIR,
RI::Paths::HOMEDIR
]
if RI::Paths::GEMDIRS then
Gem.path.each do |dir|
directories << "#{dir}/doc/*/ri"
end
end
directories = directories.join("\n ")
OptionList.strip_output(<<-EOT)
Usage:
#{name} [options] [names...]
Display information on Ruby classes, modules, and methods.
Give the names of classes or methods to see their documentation.
Partial names may be given: if the names match more than
one entity, a list will be shown, otherwise details on
that entity will be displayed.
Nested classes and modules can be specified using the normal
Name::Name notation, and instance methods can be distinguished
from class methods using "." (or "#") instead of "::".
For example:
#{name} File
#{name} File.new
#{name} F.n
#{name} zip
Note that shell quoting may be required for method names
containing punctuation:
#{name} 'Array.[]'
#{name} compact\\!
By default ri searches for documentation in the following
directories:
#{directories}
Specifying the --system, --site, --home, --gems or --doc-dir
options will limit ri to searching only the specified
directories.
EOT
if short_form
puts "For help on options, type '#{name} -h'"
puts "For a list of classes I know about, type '#{name} -c'"
else
puts "Options:\n\n"
OPTION_LIST.each do|long, short, arg, desc|
opt = ''
opt << (short ? sprintf("%15s", "#{long}, #{short}") :
sprintf("%15s", long))
if arg
opt << " " << arg
end
print opt
desc = desc.split("\n")
if opt.size < 17
print " "*(18-opt.size)
puts desc.shift
else
puts
end
desc.each do |line|
puts(" "*18 + line)
end
puts
end
puts "Options may also be passed in the 'RI' environment variable"
exit 0
end
end
end
# Show the version and exit
def show_version
puts VERSION_STRING
exit(0)
end
def initialize
@use_stdout = !STDOUT.tty?
@width = 72
@formatter = RI::TextFormatter.for("plain")
@list_classes = false
@java_classes = false
@list_names = false
# By default all paths are used. If any of these are true, only those
# directories are used.
@use_system = false
@use_site = false
@use_home = false
@use_gems = false
@doc_dirs = []
end
# Parse command line options.
def parse(args)
old_argv = ARGV.dup
ARGV.replace(args)
begin
go = GetoptLong.new(*OptionList.options)
go.quiet = true
go.each do |opt, arg|
case opt
when "--help" then OptionList.usage
when "--version" then show_version
when "--list-names" then @list_names = true
when "--no-pager" then @use_stdout = true
when "--classes" then @list_classes = true
when "--java" then @java_classes = true
when "--system" then @use_system = true
when "--site" then @use_site = true
when "--home" then @use_home = true
when "--gems" then @use_gems = true
when "--doc-dir"
if File.directory?(arg)
@doc_dirs << arg
else
$stderr.puts "Invalid directory: #{arg}"
exit 1
end
when "--format"
@formatter = RI::TextFormatter.for(arg)
unless @formatter
$stderr.print "Invalid formatter (should be one of "
$stderr.puts RI::TextFormatter.list + ")"
exit 1
end
when "--width"
begin
@width = Integer(arg)
rescue
$stderr.puts "Invalid width: '#{arg}'"
exit 1
end
end
end
rescue GetoptLong::InvalidOption, GetoptLong::MissingArgument => error
OptionList.error(error.message)
end
end
# Return the selected documentation directories.
def path
RI::Paths.path(@use_system, @use_site, @use_home, @use_gems, *@doc_dirs)
end
def raw_path
RI::Paths.raw_path(@use_system, @use_site, @use_home, @use_gems,
*@doc_dirs)
end
# Return an instance of the displayer (the thing that actually writes
# the information). This allows us to load in new displayer classes
# at runtime (for example to help with IDE integration)
def displayer
::RiDisplay.new(self)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/ri/ri_paths.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/ri/ri_paths.rb | module RI
# Encapsulate all the strangeness to do with finding out
# where to find RDoc files
#
# We basically deal with three directories:
#
# 1. The 'system' documentation directory, which holds
# the documentation distributed with Ruby, and which
# is managed by the Ruby install process
# 2. The 'site' directory, which contains site-wide
# documentation added locally.
# 3. The 'user' documentation directory, stored under the
# user's own home directory.
#
# There's contention about all this, but for now:
#
# system:: $datadir/ri/<ver>/system/...
# site:: $datadir/ri/<ver>/site/...
# user:: ~/.rdoc
module Paths
#:stopdoc:
require 'rbconfig'
DOC_DIR = "doc/rdoc"
version = Config::CONFIG['ruby_version']
base = File.join(Config::CONFIG['datadir'], "ri", version)
SYSDIR = File.join(base, "system")
SITEDIR = File.join(base, "site")
homedir = ENV['HOME'] || ENV['USERPROFILE'] || ENV['HOMEPATH']
if homedir
HOMEDIR = File.join(homedir, ".rdoc")
else
HOMEDIR = nil
end
# This is the search path for 'ri'
PATH = [ SYSDIR, SITEDIR, HOMEDIR ].find_all {|p| p && File.directory?(p)}
begin
require 'rubygems'
# HACK dup'd from Gem.latest_partials and friends
all_paths = []
all_paths = Gem.path.map do |dir|
Dir[File.join(dir, 'doc', '*', 'ri')]
end.flatten
ri_paths = {}
all_paths.each do |dir|
base = File.basename File.dirname(dir)
if base =~ /(.*)-((\d+\.)*\d+)/ then
name, version = $1, $2
ver = Gem::Version.new version
if ri_paths[name].nil? or ver > ri_paths[name][0] then
ri_paths[name] = [ver, dir]
end
end
end
GEMDIRS = ri_paths.map { |k,v| v.last }.sort
GEMDIRS.each { |dir| RI::Paths::PATH << dir }
rescue LoadError
GEMDIRS = nil
end
# Returns the selected documentation directories as an Array, or PATH if no
# overriding directories were given.
def self.path(use_system, use_site, use_home, use_gems, *extra_dirs)
path = raw_path(use_system, use_site, use_home, use_gems, *extra_dirs)
return path.select { |directory| File.directory? directory }
end
# Returns the selected documentation directories including nonexistent
# directories. Used to print out what paths were searched if no ri was
# found.
def self.raw_path(use_system, use_site, use_home, use_gems, *extra_dirs)
return PATH unless use_system or use_site or use_home or use_gems or
not extra_dirs.empty?
path = []
path << extra_dirs unless extra_dirs.empty?
path << RI::Paths::SYSDIR if use_system
path << RI::Paths::SITEDIR if use_site
path << RI::Paths::HOMEDIR if use_home
path << RI::Paths::GEMDIRS if use_gems
return path.flatten.compact
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/ri/ri_display.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/ri/ri_display.rb | require 'rdoc/ri/ri_util'
require 'rdoc/ri/ri_formatter'
require 'rdoc/ri/ri_options'
# This is a kind of 'flag' module. If you want to write your
# own 'ri' display module (perhaps because you'r writing
# an IDE or somesuch beast), you simply write a class
# which implements the various 'display' methods in 'DefaultDisplay',
# and include the 'RiDisplay' module in that class.
#
# To access your class from the command line, you can do
#
# ruby -r <your source file> ../ri ....
#
# If folks _really_ want to do this from the command line,
# I'll build an option in
module RiDisplay
@@display_class = nil
def RiDisplay.append_features(display_class)
@@display_class = display_class
end
def RiDisplay.new(*args)
@@display_class.new(*args)
end
end
######################################################################
#
# A paging display module. Uses the ri_formatter class to do the
# actual presentation
#
class DefaultDisplay
include RiDisplay
def initialize(options)
@options = options
@formatter = @options.formatter.new(@options, " ")
end
######################################################################
def display_usage
page do
RI::Options::OptionList.usage(short_form=true)
end
end
######################################################################
def display_method_info(method)
page do
@formatter.draw_line(method.full_name)
display_params(method)
@formatter.draw_line
display_flow(method.comment)
if method.aliases && !method.aliases.empty?
@formatter.blankline
aka = "(also known as "
aka << method.aliases.map {|a| a.name }.join(", ")
aka << ")"
@formatter.wrap(aka)
end
end
end
######################################################################
def display_class_info(klass, ri_reader)
page do
superclass = klass.superclass_string
if superclass
superclass = " < " + superclass
else
superclass = ""
end
@formatter.draw_line(klass.display_name + ": " +
klass.full_name + superclass)
display_flow(klass.comment)
@formatter.draw_line
unless klass.includes.empty?
@formatter.blankline
@formatter.display_heading("Includes:", 2, "")
incs = []
klass.includes.each do |inc|
inc_desc = ri_reader.find_class_by_name(inc.name)
if inc_desc
str = inc.name + "("
str << inc_desc.instance_methods.map{|m| m.name}.join(", ")
str << ")"
incs << str
else
incs << inc.name
end
end
@formatter.wrap(incs.sort.join(', '))
end
unless klass.constants.empty?
@formatter.blankline
@formatter.display_heading("Constants:", 2, "")
len = 0
klass.constants.each { |c| len = c.name.length if c.name.length > len }
len += 2
klass.constants.each do |c|
@formatter.wrap(c.value,
@formatter.indent+((c.name+":").ljust(len)))
end
end
unless klass.class_methods.empty?
@formatter.blankline
@formatter.display_heading("Class methods:", 2, "")
@formatter.wrap(klass.class_methods.map{|m| m.name}.sort.join(', '))
end
unless klass.instance_methods.empty?
@formatter.blankline
@formatter.display_heading("Instance methods:", 2, "")
@formatter.wrap(klass.instance_methods.map{|m| m.name}.sort.join(', '))
end
unless klass.attributes.empty?
@formatter.blankline
@formatter.wrap("Attributes:", "")
@formatter.wrap(klass.attributes.map{|a| a.name}.sort.join(', '))
end
end
end
######################################################################
# Display a list of method names
def display_method_list(methods)
page do
puts "More than one method matched your request. You can refine"
puts "your search by asking for information on one of:\n\n"
@formatter.wrap(methods.map {|m| m.full_name} .join(", "))
end
end
######################################################################
def display_class_list(namespaces)
page do
puts "More than one class or module matched your request. You can refine"
puts "your search by asking for information on one of:\n\n"
@formatter.wrap(namespaces.map {|m| m.full_name}.join(", "))
end
end
######################################################################
def list_known_classes(classes)
if classes.empty?
warn_no_database
else
page do
@formatter.draw_line("Known classes and modules")
@formatter.blankline
@formatter.wrap(classes.sort.join(", "))
end
end
end
######################################################################
def list_known_names(names)
if names.empty?
warn_no_database
else
page do
names.each {|n| @formatter.raw_print_line(n)}
end
end
end
######################################################################
private
######################################################################
def page
return yield unless pager = setup_pager
begin
save_stdout = STDOUT.clone
STDOUT.reopen(pager)
yield
ensure
STDOUT.reopen(save_stdout)
save_stdout.close
pager.close
end
end
######################################################################
def setup_pager
unless @options.use_stdout
for pager in [ ENV['PAGER'], "less", "more", 'pager' ].compact.uniq
return IO.popen(pager, "w") rescue nil
end
@options.use_stdout = true
nil
end
end
######################################################################
def display_params(method)
params = method.params
if params[0,1] == "("
if method.is_singleton
params = method.full_name + params
else
params = method.name + params
end
end
params.split(/\n/).each do |p|
@formatter.wrap(p)
@formatter.break_to_newline
end
end
######################################################################
def display_flow(flow)
if !flow || flow.empty?
@formatter.wrap("(no description...)")
else
@formatter.display_flow(flow)
end
end
######################################################################
def warn_no_database
puts "Before using ri, you need to generate documentation"
puts "using 'rdoc' with the --ri option"
end
end # class RiDisplay
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/ri/ri_driver.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/ri/ri_driver.rb | require 'rdoc/ri/ri_paths'
require 'rdoc/usage'
require 'rdoc/ri/ri_cache'
require 'rdoc/ri/ri_util'
require 'rdoc/ri/ri_reader'
require 'rdoc/ri/ri_formatter'
require 'rdoc/ri/ri_options'
######################################################################
class RiDriver
def initialize
@options = RI::Options.instance
args = ARGV
if ENV["RI"]
args = ENV["RI"].split.concat(ARGV)
end
@options.parse(args)
path = @options.path
report_missing_documentation @options.raw_path if path.empty?
@ri_reader = RI::RiReader.new(RI::RiCache.new(path))
@display = @options.displayer
end
# Couldn't find documentation in +path+, so tell the user what to do
def report_missing_documentation(path)
STDERR.puts "No ri documentation found in:"
path.each do |d|
STDERR.puts " #{d}"
end
STDERR.puts "\nWas rdoc run to create documentation?\n\n"
RDoc::usage("Installing Documentation")
end
######################################################################
# If the list of matching methods contains exactly one entry, or
# if it contains an entry that exactly matches the requested method,
# then display that entry, otherwise display the list of
# matching method names
def report_method_stuff(requested_method_name, methods)
if methods.size == 1
method = @ri_reader.get_method(methods[0])
@display.display_method_info(method)
else
entries = methods.find_all {|m| m.name == requested_method_name}
if entries.size == 1
method = @ri_reader.get_method(entries[0])
@display.display_method_info(method)
else
@display.display_method_list(methods)
end
end
end
######################################################################
def report_class_stuff(namespaces)
if namespaces.size == 1
klass = @ri_reader.get_class(namespaces[0])
@display.display_class_info(klass, @ri_reader)
else
# entries = namespaces.find_all {|m| m.full_name == requested_class_name}
# if entries.size == 1
# klass = @ri_reader.get_class(entries[0])
# @display.display_class_info(klass, @ri_reader)
# else
@display.display_class_list(namespaces)
# end
end
end
######################################################################
def get_info_for(arg)
desc = NameDescriptor.new(arg)
namespaces = @ri_reader.top_level_namespace
for class_name in desc.class_names
namespaces = @ri_reader.lookup_namespace_in(class_name, namespaces)
if namespaces.empty?
raise RiError.new("Nothing known about #{arg}")
end
end
# at this point, if we have multiple possible namespaces, but one
# is an exact match for our requested class, prune down to just it
full_class_name = desc.full_class_name
entries = namespaces.find_all {|m| m.full_name == full_class_name}
namespaces = entries if entries.size == 1
if desc.method_name.nil?
report_class_stuff(namespaces)
else
methods = @ri_reader.find_methods(desc.method_name,
desc.is_class_method,
namespaces)
if methods.empty?
raise RiError.new("Nothing known about #{arg}")
else
report_method_stuff(desc.method_name, methods)
end
end
end
######################################################################
def process_args
if @options.java_classes
if ARGV.size.zero?
@display.display_usage
else
begin
require 'rdoc/ri/ri_java'
ARGV.each do |arg|
get_java_info_for(arg)
end
rescue RiError => e
STDERR.puts(e.message)
exit(1)
end
end
elsif @options.list_classes
classes = @ri_reader.full_class_names
@display.list_known_classes(classes)
elsif @options.list_names
names = @ri_reader.all_names
@display.list_known_names(names)
else
if ARGV.size.zero?
@display.display_usage
else
begin
ARGV.each do |arg|
get_info_for(arg)
end
rescue RiError => e
STDERR.puts(e.message)
exit(1)
end
end
end
end
end # class RiDriver
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/ri/ri_util.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/ri/ri_util.rb | ######################################################################
class RiError < Exception; end
#
# Break argument into its constituent class or module names, an
# optional method type, and a method name
class NameDescriptor
attr_reader :class_names
attr_reader :method_name
# true and false have the obvious meaning. nil means we don't care
attr_reader :is_class_method
# arg may be
# 1. a class or module name (optionally qualified with other class
# or module names (Kernel, File::Stat etc)
# 2. a method name
# 3. a method name qualified by a optionally fully qualified class
# or module name
#
# We're fairly casual about delimiters: folks can say Kernel::puts,
# Kernel.puts, or Kernel\#puts for example. There's one exception:
# if you say IO::read, we look for a class method, but if you
# say IO.read, we look for an instance method
def initialize(arg)
@class_names = []
separator = nil
tokens = arg.split(/(\.|::|#)/)
# Skip leading '::', '#' or '.', but remember it might
# be a method name qualifier
separator = tokens.shift if tokens[0] =~ /^(\.|::|#)/
# Skip leading '::', but remember we potentially have an inst
# leading stuff must be class names
while tokens[0] =~ /^[A-Z]/
@class_names << tokens.shift
unless tokens.empty?
separator = tokens.shift
break unless separator == "::"
end
end
# Now must have a single token, the method name, or an empty
# array
unless tokens.empty?
@method_name = tokens.shift
# We may now have a trailing !, ?, or = to roll into
# the method name
if !tokens.empty? && tokens[0] =~ /^[!?=]$/
@method_name << tokens.shift
end
if @method_name =~ /::|\.|#/ or !tokens.empty?
raise RiError.new("Bad argument: #{arg}")
end
if separator && separator != '.'
@is_class_method = separator == "::"
end
end
end
# Return the full class name (with '::' between the components)
# or "" if there's no class name
def full_class_name
@class_names.join("::")
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/ri/ri_descriptions.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/ri/ri_descriptions.rb | require 'yaml'
require 'rdoc/markup/simple_markup/fragments'
# Descriptions are created by RDoc (in ri_generator) and
# written out in serialized form into the documentation
# tree. ri then reads these to generate the documentation
module RI
class NamedThing
attr_reader :name
def initialize(name)
@name = name
end
def <=>(other)
@name <=> other.name
end
def hash
@name.hash
end
def eql?(other)
@name.eql?(other)
end
end
# Alias = Struct.new(:old_name, :new_name)
class AliasName < NamedThing
end
class Attribute < NamedThing
attr_reader :rw, :comment
def initialize(name, rw, comment)
super(name)
@rw = rw
@comment = comment
end
end
class Constant < NamedThing
attr_reader :value, :comment
def initialize(name, value, comment)
super(name)
@value = value
@comment = comment
end
end
class IncludedModule < NamedThing
end
class MethodSummary < NamedThing
def initialize(name="")
super
end
end
class Description
attr_accessor :name
attr_accessor :full_name
attr_accessor :comment
def serialize
self.to_yaml
end
def Description.deserialize(from)
YAML.load(from)
end
def <=>(other)
@name <=> other.name
end
end
class ModuleDescription < Description
attr_accessor :class_methods
attr_accessor :instance_methods
attr_accessor :attributes
attr_accessor :constants
attr_accessor :includes
# merge in another class desscription into this one
def merge_in(old)
merge(@class_methods, old.class_methods)
merge(@instance_methods, old.instance_methods)
merge(@attributes, old.attributes)
merge(@constants, old.constants)
merge(@includes, old.includes)
if @comment.nil? || @comment.empty?
@comment = old.comment
else
unless old.comment.nil? or old.comment.empty? then
@comment << SM::Flow::RULE.new
@comment.concat old.comment
end
end
end
def display_name
"Module"
end
# the 'ClassDescription' subclass overrides this
# to format up the name of a parent
def superclass_string
nil
end
private
def merge(into, from)
names = {}
into.each {|i| names[i.name] = i }
from.each {|i| names[i.name] = i }
into.replace(names.keys.sort.map {|n| names[n]})
end
end
class ClassDescription < ModuleDescription
attr_accessor :superclass
def display_name
"Class"
end
def superclass_string
if @superclass && @superclass != "Object"
@superclass
else
nil
end
end
end
class MethodDescription < Description
attr_accessor :is_class_method
attr_accessor :visibility
attr_accessor :block_params
attr_accessor :is_singleton
attr_accessor :aliases
attr_accessor :is_alias_for
attr_accessor :params
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/ri/ri_java.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/ri/ri_java.rb | require 'java'
require 'rdoc/ri/ri_driver'
require 'rdoc/ri/ri_reader'
class RiDriver
def report_java_method_stuff(java_methods)
method = @ri_reader.get_java_method(java_methods)
@display.display_method_info(method)
end
def report_java_class_stuff(cls)
klass = @ri_reader.get_java_class(cls)
@display.display_class_info(klass, @ri_reader)
end
def get_java_info_for(arg)
cls_name = arg
if arg['#']
cls_name, mth_name = arg.split '#'
static = -1
begin
cls = java.lang.Class.for_name(cls_name)
rescue Exception
raise RiError.new("Nothing known about #{arg}")
end
elsif arg['::']
cls_name, mth_name = arg.split '::'
static = 1
begin
cls = java.lang.Class.for_name(cls_name)
rescue Exception
raise RiError.new("Nothing known about #{arg}")
end
else
static = 0
begin
cls = java.lang.Class.for_name(cls_name)
rescue Exception
begin
splitted = arg.split('.')
cls_name = splitted[0..-2].join('.')
mth_name = splitted[-1]
cls = java.lang.Class.for_name(cls_name)
end
end
end
if mth_name
# print method info
if static == -1 # instance
methods = cls.methods.select do |m|
m.name == mth_name &&
!java.lang.reflect.Modifier.is_static(m.modifiers)
end
elsif
static == 1 # static
methods = cls.methods.select do |m|
m.name == mth_name &&
java.lang.reflect.Modifier.is_static(m.modifiers)
end
else # one or other
last = nil
methods = cls.methods.select do |m|
# filter by name
next false unless m.name == mth_name
# track whether we've seen both static and instance
static = java.lang.reflect.Modifier.is_static(m.modifiers) ? 1 : -1
if last && last != static
raise RiError.new("Ambiguous: try using \# or :: for #{arg}")
end
last = static
true
end
end
if !methods || methods.empty?
raise RiError.new("Nothing known about #{arg}")
end
report_java_method_stuff(methods)
else
report_java_class_stuff(cls)
end
end
end
module RI
class RiReader
def get_nice_java_class_name(cls)
if cls.primitive?
cls.name
elsif cls.array?
"#{get_nice_java_class_name(cls.component_type)}[]"
else
cls.name
end
end
def get_java_method(java_methods)
modifier = java.lang.reflect.Modifier
desc = RI::MethodDescription.new
is_static = modifier.is_static(java_methods[0].modifiers)
desc.is_class_method = is_static
desc.visibility = "public"
desc.name = java_methods[0].name
desc.full_name =
"#{java_methods[0].declaring_class.name}#{is_static ? '.' : '#'}#{desc.name}"
desc.params = ""
java_methods.each do |java_method|
param_strs = java_method.parameter_types.map {|cls| get_nice_java_class_name(cls)}
desc.params <<
"#{java_method.name}(#{param_strs.join(',')}) => #{get_nice_java_class_name(java_method.return_type)}\n"
end
desc
end
def get_java_class(class_entry)
desc = RI::ClassDescription.new
desc.full_name = class_entry.name
desc.superclass = class_entry.superclass.name if class_entry.superclass
# TODO interfaces?
desc.includes = []
# TODO constants
desc.constants = []
# TODO bean attributes or something?
desc.attributes = []
modifier = java.lang.reflect.Modifier
methods = class_entry.methods
cls_methods = {}
methods.select {|m| modifier.is_static(m.modifiers)}.each {|m| cls_methods[m.name] = m}
inst_methods = {}
methods.select {|m| !modifier.is_static(m.modifiers)}.each {|m| inst_methods[m.name] = m}
desc.class_methods = []
cls_methods.keys.each do |name|
desc.class_methods << RI::MethodSummary.new(name)
end
desc.instance_methods = []
inst_methods.keys.each do |name|
desc.instance_methods << RI::MethodSummary.new(name)
end
desc
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/ri/ri_formatter.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/ri/ri_formatter.rb | module RI
class TextFormatter
attr_reader :indent
def initialize(options, indent)
@options = options
@width = options.width
@indent = indent
end
######################################################################
def draw_line(label=nil)
len = @width
len -= (label.size+1) if label
print "-"*len
if label
print(" ")
bold_print(label)
end
puts
end
######################################################################
def wrap(txt, prefix=@indent, linelen=@width)
return unless txt && !txt.empty?
work = conv_markup(txt)
textLen = linelen - prefix.length
patt = Regexp.new("^(.{0,#{textLen}})[ \n]")
next_prefix = prefix.tr("^ ", " ")
res = []
while work.length > textLen
if work =~ patt
res << $1
work.slice!(0, $&.length)
else
res << work.slice!(0, textLen)
end
end
res << work if work.length.nonzero?
puts(prefix + res.join("\n" + next_prefix))
end
######################################################################
def blankline
puts
end
######################################################################
# called when we want to ensure a nbew 'wrap' starts on a newline
# Only needed for HtmlFormatter, because the rest do their
# own line breaking
def break_to_newline
end
######################################################################
def bold_print(txt)
print txt
end
######################################################################
def raw_print_line(txt)
puts txt
end
######################################################################
# convert HTML entities back to ASCII
def conv_html(txt)
txt.
gsub(/>/, '>').
gsub(/</, '<').
gsub(/"/, '"').
gsub(/&/, '&')
end
# convert markup into display form
def conv_markup(txt)
txt.
gsub(%r{<tt>(.*?)</tt>}) { "+#$1+" } .
gsub(%r{<code>(.*?)</code>}) { "+#$1+" } .
gsub(%r{<b>(.*?)</b>}) { "*#$1*" } .
gsub(%r{<em>(.*?)</em>}) { "_#$1_" }
end
######################################################################
def display_list(list)
case list.type
when SM::ListBase::BULLET
prefixer = proc { |ignored| @indent + "* " }
when SM::ListBase::NUMBER,
SM::ListBase::UPPERALPHA,
SM::ListBase::LOWERALPHA
start = case list.type
when SM::ListBase::NUMBER then 1
when SM::ListBase::UPPERALPHA then 'A'
when SM::ListBase::LOWERALPHA then 'a'
end
prefixer = proc do |ignored|
res = @indent + "#{start}.".ljust(4)
start = start.succ
res
end
when SM::ListBase::LABELED
prefixer = proc do |li|
li.label
end
when SM::ListBase::NOTE
longest = 0
list.contents.each do |item|
if item.kind_of?(SM::Flow::LI) && item.label.length > longest
longest = item.label.length
end
end
prefixer = proc do |li|
@indent + li.label.ljust(longest+1)
end
else
fail "unknown list type"
end
list.contents.each do |item|
if item.kind_of? SM::Flow::LI
prefix = prefixer.call(item)
display_flow_item(item, prefix)
else
display_flow_item(item)
end
end
end
######################################################################
def display_flow_item(item, prefix=@indent)
case item
when SM::Flow::P, SM::Flow::LI
wrap(conv_html(item.body), prefix)
blankline
when SM::Flow::LIST
display_list(item)
when SM::Flow::VERB
display_verbatim_flow_item(item, @indent)
when SM::Flow::H
display_heading(conv_html(item.text), item.level, @indent)
when SM::Flow::RULE
draw_line
else
fail "Unknown flow element: #{item.class}"
end
end
######################################################################
def display_verbatim_flow_item(item, prefix=@indent)
item.body.split(/\n/).each do |line|
print @indent, conv_html(line), "\n"
end
blankline
end
######################################################################
def display_heading(text, level, indent)
text = strip_attributes(text)
case level
when 1
ul = "=" * text.length
puts
puts text.upcase
puts ul
# puts
when 2
ul = "-" * text.length
puts
puts text
puts ul
# puts
else
print indent, text, "\n"
end
end
def display_flow(flow)
flow.each do |f|
display_flow_item(f)
end
end
def strip_attributes(txt)
tokens = txt.split(%r{(</?(?:b|code|em|i|tt)>)})
text = []
attributes = 0
tokens.each do |tok|
case tok
when %r{^</(\w+)>$}, %r{^<(\w+)>$}
;
else
text << tok
end
end
text.join
end
end
######################################################################
# Handle text with attributes. We're a base class: there are
# different presentation classes (one, for example, uses overstrikes
# to handle bold and underlining, while another using ANSI escape
# sequences
class AttributeFormatter < TextFormatter
BOLD = 1
ITALIC = 2
CODE = 4
ATTR_MAP = {
"b" => BOLD,
"code" => CODE,
"em" => ITALIC,
"i" => ITALIC,
"tt" => CODE
}
# TODO: struct?
class AttrChar
attr_reader :char
attr_reader :attr
def initialize(char, attr)
@char = char
@attr = attr
end
end
class AttributeString
attr_reader :txt
def initialize
@txt = []
@optr = 0
end
def <<(char)
@txt << char
end
def empty?
@optr >= @txt.length
end
# accept non space, then all following spaces
def next_word
start = @optr
len = @txt.length
while @optr < len && @txt[@optr].char != " "
@optr += 1
end
while @optr < len && @txt[@optr].char == " "
@optr += 1
end
@txt[start...@optr]
end
end
######################################################################
# overrides base class. Looks for <tt>...</tt> etc sequences
# and generates an array of AttrChars. This array is then used
# as the basis for the split
def wrap(txt, prefix=@indent, linelen=@width)
return unless txt && !txt.empty?
txt = add_attributes_to(txt)
next_prefix = prefix.tr("^ ", " ")
linelen -= prefix.size
line = []
until txt.empty?
word = txt.next_word
if word.size + line.size > linelen
write_attribute_text(prefix, line)
prefix = next_prefix
line = []
end
line.concat(word)
end
write_attribute_text(prefix, line) if line.length > 0
end
protected
# overridden in specific formatters
def write_attribute_text(prefix, line)
print prefix
line.each do |achar|
print achar.char
end
puts
end
# again, overridden
def bold_print(txt)
print txt
end
private
def add_attributes_to(txt)
tokens = txt.split(%r{(</?(?:b|code|em|i|tt)>)})
text = AttributeString.new
attributes = 0
tokens.each do |tok|
case tok
when %r{^</(\w+)>$} then attributes &= ~(ATTR_MAP[$1]||0)
when %r{^<(\w+)>$} then attributes |= (ATTR_MAP[$1]||0)
else
tok.split(//).each {|ch| text << AttrChar.new(ch, attributes)}
end
end
text
end
end
##################################################
# This formatter generates overstrike-style formatting, which
# works with pagers such as man and less.
class OverstrikeFormatter < AttributeFormatter
BS = "\C-h"
def write_attribute_text(prefix, line)
print prefix
line.each do |achar|
attr = achar.attr
if (attr & (ITALIC+CODE)) != 0
print "_", BS
end
if (attr & BOLD) != 0
print achar.char, BS
end
print achar.char
end
puts
end
# draw a string in bold
def bold_print(text)
text.split(//).each do |ch|
print ch, BS, ch
end
end
end
##################################################
# This formatter uses ANSI escape sequences
# to colorize stuff
# works with pages such as man and less.
class AnsiFormatter < AttributeFormatter
def initialize(*args)
print "\033[0m"
super
end
def write_attribute_text(prefix, line)
print prefix
curr_attr = 0
line.each do |achar|
attr = achar.attr
if achar.attr != curr_attr
update_attributes(achar.attr)
curr_attr = achar.attr
end
print achar.char
end
update_attributes(0) unless curr_attr.zero?
puts
end
def bold_print(txt)
print "\033[1m#{txt}\033[m"
end
HEADINGS = {
1 => [ "\033[1;32m", "\033[m" ] ,
2 => ["\033[4;32m", "\033[m" ],
3 => ["\033[32m", "\033[m" ]
}
def display_heading(text, level, indent)
level = 3 if level > 3
heading = HEADINGS[level]
print indent
print heading[0]
print strip_attributes(text)
puts heading[1]
end
private
ATTR_MAP = {
BOLD => "1",
ITALIC => "33",
CODE => "36"
}
def update_attributes(attr)
str = "\033["
for quality in [ BOLD, ITALIC, CODE]
unless (attr & quality).zero?
str << ATTR_MAP[quality]
end
end
print str, "m"
end
end
##################################################
# This formatter uses HTML.
class HtmlFormatter < AttributeFormatter
def initialize(*args)
super
end
def write_attribute_text(prefix, line)
curr_attr = 0
line.each do |achar|
attr = achar.attr
if achar.attr != curr_attr
update_attributes(curr_attr, achar.attr)
curr_attr = achar.attr
end
print(escape(achar.char))
end
update_attributes(curr_attr, 0) unless curr_attr.zero?
end
def draw_line(label=nil)
if label != nil
bold_print(label)
end
puts("<hr>")
end
def bold_print(txt)
tag("b") { txt }
end
def blankline()
puts("<p>")
end
def break_to_newline
puts("<br>")
end
def display_heading(text, level, indent)
level = 4 if level > 4
tag("h#{level}") { text }
puts
end
######################################################################
def display_list(list)
case list.type
when SM::ListBase::BULLET
list_type = "ul"
prefixer = proc { |ignored| "<li>" }
when SM::ListBase::NUMBER,
SM::ListBase::UPPERALPHA,
SM::ListBase::LOWERALPHA
list_type = "ol"
prefixer = proc { |ignored| "<li>" }
when SM::ListBase::LABELED
list_type = "dl"
prefixer = proc do |li|
"<dt><b>" + escape(li.label) + "</b><dd>"
end
when SM::ListBase::NOTE
list_type = "table"
prefixer = proc do |li|
%{<tr valign="top"><td>#{li.label.gsub(/ /, ' ')}</td><td>}
end
else
fail "unknown list type"
end
print "<#{list_type}>"
list.contents.each do |item|
if item.kind_of? SM::Flow::LI
prefix = prefixer.call(item)
print prefix
display_flow_item(item, prefix)
else
display_flow_item(item)
end
end
print "</#{list_type}>"
end
def display_verbatim_flow_item(item, prefix=@indent)
print("<pre>")
puts item.body
puts("</pre>")
end
private
ATTR_MAP = {
BOLD => "b>",
ITALIC => "i>",
CODE => "tt>"
}
def update_attributes(current, wanted)
str = ""
# first turn off unwanted ones
off = current & ~wanted
for quality in [ BOLD, ITALIC, CODE]
if (off & quality) > 0
str << "</" + ATTR_MAP[quality]
end
end
# now turn on wanted
for quality in [ BOLD, ITALIC, CODE]
unless (wanted & quality).zero?
str << "<" << ATTR_MAP[quality]
end
end
print str
end
def tag(code)
print("<#{code}>")
print(yield)
print("</#{code}>")
end
def escape(str)
str.
gsub(/&/n, '&').
gsub(/\"/n, '"').
gsub(/>/n, '>').
gsub(/</n, '<')
end
end
##################################################
# This formatter reduces extra lines for a simpler output.
# It improves way output looks for tools like IRC bots.
class SimpleFormatter < TextFormatter
######################################################################
# No extra blank lines
def blankline
end
######################################################################
# Display labels only, no lines
def draw_line(label=nil)
unless label.nil? then
bold_print(label)
puts
end
end
######################################################################
# Place heading level indicators inline with heading.
def display_heading(text, level, indent)
text = strip_attributes(text)
case level
when 1
puts "= " + text.upcase
when 2
puts "-- " + text
else
print indent, text, "\n"
end
end
end
# Finally, fill in the list of known formatters
class TextFormatter
FORMATTERS = {
"ansi" => AnsiFormatter,
"bs" => OverstrikeFormatter,
"html" => HtmlFormatter,
"plain" => TextFormatter,
"simple" => SimpleFormatter,
}
def TextFormatter.list
FORMATTERS.keys.sort.join(", ")
end
def TextFormatter.for(name)
FORMATTERS[name.downcase]
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/ri/ri_reader.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/ri/ri_reader.rb | require 'rdoc/ri/ri_descriptions'
require 'rdoc/ri/ri_writer'
require 'rdoc/markup/simple_markup/to_flow'
module RI
class RiReader
def initialize(ri_cache)
@cache = ri_cache
end
def top_level_namespace
[ @cache.toplevel ]
end
def lookup_namespace_in(target, namespaces)
result = []
for n in namespaces
result.concat(n.contained_modules_matching(target))
end
result
end
def find_class_by_name(full_name)
names = full_name.split(/::/)
ns = @cache.toplevel
for name in names
ns = ns.contained_class_named(name)
return nil if ns.nil?
end
get_class(ns)
end
def find_methods(name, is_class_method, namespaces)
result = []
namespaces.each do |ns|
result.concat ns.methods_matching(name, is_class_method)
end
result
end
# return the MethodDescription for a given MethodEntry
# by deserializing the YAML
def get_method(method_entry)
path = method_entry.path_name
File.open(path) { |f| RI::Description.deserialize(f) }
end
# Return a class description
def get_class(class_entry)
result = nil
for path in class_entry.path_names
path = RiWriter.class_desc_path(path, class_entry)
desc = File.open(path) {|f| RI::Description.deserialize(f) }
if result
result.merge_in(desc)
else
result = desc
end
end
result
end
# return the names of all classes and modules
def full_class_names
res = []
find_classes_in(res, @cache.toplevel)
end
# return a list of all classes, modules, and methods
def all_names
res = []
find_names_in(res, @cache.toplevel)
end
# ----
private
# ----
def find_classes_in(res, klass)
classes = klass.classes_and_modules
for c in classes
res << c.full_name
find_classes_in(res, c)
end
res
end
def find_names_in(res, klass)
classes = klass.classes_and_modules
for c in classes
res << c.full_name
res.concat c.all_method_names
find_names_in(res, c)
end
res
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/ri/ri_writer.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/ri/ri_writer.rb | require 'fileutils'
module RI
class RiWriter
def RiWriter.class_desc_path(dir, class_desc)
File.join(dir, "cdesc-" + class_desc.name + ".yaml")
end
# Convert a name from internal form (containing punctuation)
# to an external form (where punctuation is replaced
# by %xx)
def RiWriter.internal_to_external(name)
name.gsub(/\W/) { sprintf("%%%02x", $&[0]) }
end
# And the reverse operation
def RiWriter.external_to_internal(name)
name.gsub(/%([0-9a-f]{2,2})/) { $1.to_i(16).chr }
end
def initialize(base_dir)
@base_dir = base_dir
end
def remove_class(class_desc)
FileUtils.rm_rf(path_to_dir(class_desc.full_name))
end
def add_class(class_desc)
dir = path_to_dir(class_desc.full_name)
FileUtils.mkdir_p(dir)
class_file_name = RiWriter.class_desc_path(dir, class_desc)
File.open(class_file_name, "w") do |f|
f.write(class_desc.serialize)
end
end
def add_method(class_desc, method_desc)
dir = path_to_dir(class_desc.full_name)
file_name = RiWriter.internal_to_external(method_desc.name)
meth_file_name = File.join(dir, file_name)
if method_desc.is_singleton
meth_file_name += "-c.yaml"
else
meth_file_name += "-i.yaml"
end
File.open(meth_file_name, "w") do |f|
f.write(method_desc.serialize)
end
end
private
def path_to_dir(class_name)
File.join(@base_dir, *class_name.split('::'))
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/ri/ri_cache.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/ri/ri_cache.rb | module RI
class ClassEntry
attr_reader :name
attr_reader :path_names
def initialize(path_name, name, in_class)
@path_names = [ path_name ]
@name = name
@in_class = in_class
@class_methods = []
@instance_methods = []
@inferior_classes = []
end
# We found this class in more tha one place, so add
# in the name from there.
def add_path(path)
@path_names << path
end
# read in our methods and any classes
# and modules in our namespace. Methods are
# stored in files called name-c|i.yaml,
# where the 'name' portion is the external
# form of the method name and the c|i is a class|instance
# flag
def load_from(dir)
Dir.foreach(dir) do |name|
next if name =~ /^\./
# convert from external to internal form, and
# extract the instance/class flag
if name =~ /^(.*?)-(c|i).yaml$/
external_name = $1
is_class_method = $2 == "c"
internal_name = RiWriter.external_to_internal(external_name)
list = is_class_method ? @class_methods : @instance_methods
path = File.join(dir, name)
list << MethodEntry.new(path, internal_name, is_class_method, self)
else
full_name = File.join(dir, name)
if File.directory?(full_name)
inf_class = @inferior_classes.find {|c| c.name == name }
if inf_class
inf_class.add_path(full_name)
else
inf_class = ClassEntry.new(full_name, name, self)
@inferior_classes << inf_class
end
inf_class.load_from(full_name)
end
end
end
end
# Return a list of any classes or modules that we contain
# that match a given string
def contained_modules_matching(name)
@inferior_classes.find_all {|c| c.name[name]}
end
def classes_and_modules
@inferior_classes
end
# Return an exact match to a particular name
def contained_class_named(name)
@inferior_classes.find {|c| c.name == name}
end
# return the list of local methods matching name
# We're split into two because we need distinct behavior
# when called from the _toplevel_
def methods_matching(name, is_class_method)
local_methods_matching(name, is_class_method)
end
# Find methods matching 'name' in ourselves and in
# any classes we contain
def recursively_find_methods_matching(name, is_class_method)
res = local_methods_matching(name, is_class_method)
@inferior_classes.each do |c|
res.concat(c.recursively_find_methods_matching(name, is_class_method))
end
res
end
# Return our full name
def full_name
res = @in_class.full_name
res << "::" unless res.empty?
res << @name
end
# Return a list of all out method names
def all_method_names
res = @class_methods.map {|m| m.full_name }
@instance_methods.each {|m| res << m.full_name}
res
end
private
# Return a list of all our methods matching a given string.
# Is +is_class_methods+ if 'nil', we don't care if the method
# is a class method or not, otherwise we only return
# those methods that match
def local_methods_matching(name, is_class_method)
list = case is_class_method
when nil then @class_methods + @instance_methods
when true then @class_methods
when false then @instance_methods
else fail "Unknown is_class_method: #{is_class_method.inspect}"
end
list.find_all {|m| m.name; m.name[name]}
end
end
# A TopLevelEntry is like a class entry, but when asked to search
# for methods searches all classes, not just itself
class TopLevelEntry < ClassEntry
def methods_matching(name, is_class_method)
res = recursively_find_methods_matching(name, is_class_method)
end
def full_name
""
end
def module_named(name)
end
end
class MethodEntry
attr_reader :name
attr_reader :path_name
def initialize(path_name, name, is_class_method, in_class)
@path_name = path_name
@name = name
@is_class_method = is_class_method
@in_class = in_class
end
def full_name
res = @in_class.full_name
unless res.empty?
if @is_class_method
res << "::"
else
res << "#"
end
end
res << @name
end
end
# We represent everything know about all 'ri' files
# accessible to this program
class RiCache
attr_reader :toplevel
def initialize(dirs)
# At the top level we have a dummy module holding the
# overall namespace
@toplevel = TopLevelEntry.new('', '::', nil)
dirs.each do |dir|
@toplevel.load_from(dir)
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/generators/xml_generator.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/generators/xml_generator.rb |
require 'ftools'
require 'rdoc/options'
require 'rdoc/markup/simple_markup'
require 'rdoc/markup/simple_markup/to_html'
require 'rdoc/generators/html_generator'
module Generators
# Generate XML output as one big file
class XMLGenerator < HTMLGenerator
# Standard generator factory
def XMLGenerator.for(options)
XMLGenerator.new(options)
end
def initialize(*args)
super
end
##
# Build the initial indices and output objects
# based on an array of TopLevel objects containing
# the extracted information.
def generate(info)
@info = info
@files = []
@classes = []
@hyperlinks = {}
build_indices
generate_xml
end
##
# Generate:
#
# * a list of HtmlFile objects for each TopLevel object.
# * a list of HtmlClass objects for each first level
# class or module in the TopLevel objects
# * a complete list of all hyperlinkable terms (file,
# class, module, and method names)
def build_indices
@info.each do |toplevel|
@files << HtmlFile.new(toplevel, @options, FILE_DIR)
end
RDoc::TopLevel.all_classes_and_modules.each do |cls|
build_class_list(cls, @files[0], CLASS_DIR)
end
end
def build_class_list(from, html_file, class_dir)
@classes << HtmlClass.new(from, html_file, class_dir, @options)
from.each_classmodule do |mod|
build_class_list(mod, html_file, class_dir)
end
end
##
# Generate all the HTML. For the one-file case, we generate
# all the information in to one big hash
#
def generate_xml
values = {
'charset' => @options.charset,
'files' => gen_into(@files),
'classes' => gen_into(@classes)
}
# this method is defined in the template file
write_extra_pages if defined? write_extra_pages
template = TemplatePage.new(RDoc::Page::ONE_PAGE)
if @options.op_name
opfile = File.open(@options.op_name, "w")
else
opfile = $stdout
end
template.write_html_on(opfile, values)
end
def gen_into(list)
res = []
list.each do |item|
res << item.value_hash
end
res
end
def gen_file_index
gen_an_index(@files, 'Files')
end
def gen_class_index
gen_an_index(@classes, 'Classes')
end
def gen_method_index
gen_an_index(HtmlMethod.all_methods, 'Methods')
end
def gen_an_index(collection, title)
res = []
collection.sort.each do |f|
if f.document_self
res << { "href" => f.path, "name" => f.index_name }
end
end
return {
"entries" => res,
'list_title' => title,
'index_url' => main_url,
}
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/generators/chm_generator.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/generators/chm_generator.rb | require 'rdoc/generators/html_generator'
module Generators
class CHMGenerator < HTMLGenerator
HHC_PATH = "c:/Program Files/HTML Help Workshop/hhc.exe"
# Standard generator factory
def CHMGenerator.for(options)
CHMGenerator.new(options)
end
def initialize(*args)
super
@op_name = @options.op_name || "rdoc"
check_for_html_help_workshop
end
def check_for_html_help_workshop
stat = File.stat(HHC_PATH)
rescue
$stderr <<
"\n.chm output generation requires that Microsoft's Html Help\n" <<
"Workshop is installed. RDoc looks for it in:\n\n " <<
HHC_PATH <<
"\n\nYou can download a copy for free from:\n\n" <<
" http://msdn.microsoft.com/library/default.asp?" <<
"url=/library/en-us/htmlhelp/html/hwMicrosoftHTMLHelpDownloads.asp\n\n"
exit 99
end
# Generate the html as normal, then wrap it
# in a help project
def generate(info)
super
@project_name = @op_name + ".hhp"
create_help_project
end
# The project contains the project file, a table of contents
# and an index
def create_help_project
create_project_file
create_contents_and_index
compile_project
end
# The project file links together all the various
# files that go to make up the help.
def create_project_file
template = TemplatePage.new(RDoc::Page::HPP_FILE)
values = { "title" => @options.title, "opname" => @op_name }
files = []
@files.each do |f|
files << { "html_file_name" => f.path }
end
values['all_html_files'] = files
File.open(@project_name, "w") do |f|
template.write_html_on(f, values)
end
end
# The contents is a list of all files and modules.
# For each we include as sub-entries the list
# of methods they contain. As we build the contents
# we also build an index file
def create_contents_and_index
contents = []
index = []
(@files+@classes).sort.each do |entry|
content_entry = { "c_name" => entry.name, "ref" => entry.path }
index << { "name" => entry.name, "aref" => entry.path }
internals = []
methods = entry.build_method_summary_list(entry.path)
content_entry["methods"] = methods unless methods.empty?
contents << content_entry
index.concat methods
end
values = { "contents" => contents }
template = TemplatePage.new(RDoc::Page::CONTENTS)
File.open("contents.hhc", "w") do |f|
template.write_html_on(f, values)
end
values = { "index" => index }
template = TemplatePage.new(RDoc::Page::CHM_INDEX)
File.open("index.hhk", "w") do |f|
template.write_html_on(f, values)
end
end
# Invoke the windows help compiler to compiler the project
def compile_project
system(HHC_PATH, @project_name)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/generators/html_generator.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/generators/html_generator.rb | # We're responsible for generating all the HTML files
# from the object tree defined in code_objects.rb. We
# generate:
#
# [files] an html file for each input file given. These
# input files appear as objects of class
# TopLevel
#
# [classes] an html file for each class or module encountered.
# These classes are not grouped by file: if a file
# contains four classes, we'll generate an html
# file for the file itself, and four html files
# for the individual classes.
#
# [indices] we generate three indices for files, classes,
# and methods. These are displayed in a browser
# like window with three index panes across the
# top and the selected description below
#
# Method descriptions appear in whatever entity (file, class,
# or module) that contains them.
#
# We generate files in a structure below a specified subdirectory,
# normally +doc+.
#
# opdir
# |
# |___ files
# | |__ per file summaries
# |
# |___ classes
# |__ per class/module descriptions
#
# HTML is generated using the Template class.
#
require 'ftools'
require 'rdoc/options'
require 'rdoc/template'
require 'rdoc/markup/simple_markup'
require 'rdoc/markup/simple_markup/to_html'
require 'cgi'
module Generators
# Name of sub-direcories that hold file and class/module descriptions
FILE_DIR = "files"
CLASS_DIR = "classes"
CSS_NAME = "rdoc-style.css"
##
# Build a hash of all items that can be cross-referenced.
# This is used when we output required and included names:
# if the names appear in this hash, we can generate
# an html cross reference to the appropriate description.
# We also use this when parsing comment blocks: any decorated
# words matching an entry in this list are hyperlinked.
class AllReferences
@@refs = {}
def AllReferences::reset
@@refs = {}
end
def AllReferences.add(name, html_class)
@@refs[name] = html_class
end
def AllReferences.[](name)
@@refs[name]
end
def AllReferences.keys
@@refs.keys
end
end
##
# Subclass of the SM::ToHtml class that supports looking
# up words in the AllReferences list. Those that are
# found (like AllReferences in this comment) will
# be hyperlinked
class HyperlinkHtml < SM::ToHtml
# We need to record the html path of our caller so we can generate
# correct relative paths for any hyperlinks that we find
def initialize(from_path, context)
super()
@from_path = from_path
@parent_name = context.parent_name
@parent_name += "::" if @parent_name
@context = context
end
# We're invoked when any text matches the CROSSREF pattern
# (defined in MarkUp). If we fine the corresponding reference,
# generate a hyperlink. If the name we're looking for contains
# no punctuation, we look for it up the module/class chain. For
# example, HyperlinkHtml is found, even without the Generators::
# prefix, because we look for it in module Generators first.
def handle_special_CROSSREF(special)
name = special.text
if name[0,1] == '#'
lookup = name[1..-1]
name = lookup unless Options.instance.show_hash
else
lookup = name
end
# Find class, module, or method in class or module.
if /([A-Z]\w*)[.\#](\w+[!?=]?)/ =~ lookup
container = $1
method = $2
ref = @context.find_symbol(container, method)
elsif /([A-Za-z]\w*)[.\#](\w+(\([\.\w+\*\/\+\-\=\<\>]+\))?)/ =~ lookup
container = $1
method = $2
ref = @context.find_symbol(container, method)
else
ref = @context.find_symbol(lookup)
end
if ref and ref.document_self
"<a href=\"#{ref.as_href(@from_path)}\">#{name}</a>"
else
name
end
end
# Generate a hyperlink for url, labeled with text. Handle the
# special cases for img: and link: described under handle_special_HYPEDLINK
def gen_url(url, text)
if url =~ /([A-Za-z]+):(.*)/
type = $1
path = $2
else
type = "http"
path = url
url = "http://#{url}"
end
if type == "link"
if path[0,1] == '#' # is this meaningful?
url = path
else
url = HTMLGenerator.gen_url(@from_path, path)
end
end
if (type == "http" || type == "link") &&
url =~ /\.(gif|png|jpg|jpeg|bmp)$/
"<img src=\"#{url}\" />"
else
"<a href=\"#{url}\">#{text.sub(%r{^#{type}:/*}, '')}</a>"
end
end
# And we're invoked with a potential external hyperlink mailto:
# just gets inserted. http: links are checked to see if they
# reference an image. If so, that image gets inserted using an
# <img> tag. Otherwise a conventional <a href> is used. We also
# support a special type of hyperlink, link:, which is a reference
# to a local file whose path is relative to the --op directory.
def handle_special_HYPERLINK(special)
url = special.text
gen_url(url, url)
end
# HEre's a hypedlink where the label is different to the URL
# <label>[url]
#
def handle_special_TIDYLINK(special)
text = special.text
# unless text =~ /(\S+)\[(.*?)\]/
unless text =~ /\{(.*?)\}\[(.*?)\]/ or text =~ /(\S+)\[(.*?)\]/
return text
end
label = $1
url = $2
gen_url(url, label)
end
end
#####################################################################
#
# Handle common markup tasks for the various Html classes
#
module MarkUp
# Convert a string in markup format into HTML. We keep a cached
# SimpleMarkup object lying around after the first time we're
# called per object.
def markup(str, remove_para=false)
return '' unless str
unless defined? @markup
@markup = SM::SimpleMarkup.new
# class names, variable names, or instance variables
@markup.add_special(/(
\w+(::\w+)*[.\#]\w+(\([\.\w+\*\/\+\-\=\<\>]+\))? # A::B.meth(**) (for operator in Fortran95)
| \#\w+(\([.\w\*\/\+\-\=\<\>]+\))? # meth(**) (for operator in Fortran95)
| \b([A-Z]\w*(::\w+)*[.\#]\w+) # A::B.meth
| \b([A-Z]\w+(::\w+)*) # A::B..
| \#\w+[!?=]? # #meth_name
| \b\w+([_\/\.]+\w+)*[!?=]? # meth_name
)/x,
:CROSSREF)
# external hyperlinks
@markup.add_special(/((link:|https?:|mailto:|ftp:|www\.)\S+\w)/, :HYPERLINK)
# and links of the form <text>[<url>]
@markup.add_special(/(((\{.*?\})|\b\S+?)\[\S+?\.\S+?\])/, :TIDYLINK)
# @markup.add_special(/\b(\S+?\[\S+?\.\S+?\])/, :TIDYLINK)
end
unless defined? @html_formatter
@html_formatter = HyperlinkHtml.new(self.path, self)
end
# Convert leading comment markers to spaces, but only
# if all non-blank lines have them
if str =~ /^(?>\s*)[^\#]/
content = str
else
content = str.gsub(/^\s*(#+)/) { $1.tr('#',' ') }
end
res = @markup.convert(content, @html_formatter)
if remove_para
res.sub!(/^<p>/, '')
res.sub!(/<\/p>$/, '')
end
res
end
# Qualify a stylesheet URL; if if +css_name+ does not begin with '/' or
# 'http[s]://', prepend a prefix relative to +path+. Otherwise, return it
# unmodified.
def style_url(path, css_name=nil)
# $stderr.puts "style_url( #{path.inspect}, #{css_name.inspect} )"
css_name ||= CSS_NAME
if %r{^(https?:/)?/} =~ css_name
return css_name
else
return HTMLGenerator.gen_url(path, css_name)
end
end
# Build a webcvs URL with the given 'url' argument. URLs with a '%s' in them
# get the file's path sprintfed into them; otherwise they're just catenated
# together.
def cvs_url(url, full_path)
if /%s/ =~ url
return sprintf( url, full_path )
else
return url + full_path
end
end
end
#####################################################################
#
# A Context is built by the parser to represent a container: contexts
# hold classes, modules, methods, require lists and include lists.
# ClassModule and TopLevel are the context objects we process here
#
class ContextUser
include MarkUp
attr_reader :context
def initialize(context, options)
@context = context
@options = options
end
# convenience method to build a hyperlink
def href(link, cls, name)
%{<a href="#{link}" class="#{cls}">#{name}</a>} #"
end
# return a reference to outselves to be used as an href=
# the form depends on whether we're all in one file
# or in multiple files
def as_href(from_path)
if @options.all_one_file
"#" + path
else
HTMLGenerator.gen_url(from_path, path)
end
end
# Create a list of HtmlMethod objects for each method
# in the corresponding context object. If the @options.show_all
# variable is set (corresponding to the <tt>--all</tt> option,
# we include all methods, otherwise just the public ones.
def collect_methods
list = @context.method_list
unless @options.show_all
list = list.find_all {|m| m.visibility == :public || m.visibility == :protected || m.force_documentation }
end
@methods = list.collect {|m| HtmlMethod.new(m, self, @options) }
end
# Build a summary list of all the methods in this context
def build_method_summary_list(path_prefix="")
collect_methods unless @methods
meths = @methods.sort
res = []
meths.each do |meth|
res << {
"name" => CGI.escapeHTML(meth.name),
"aref" => "#{path_prefix}\##{meth.aref}"
}
end
res
end
# Build a list of aliases for which we couldn't find a
# corresponding method
def build_alias_summary_list(section)
values = []
@context.aliases.each do |al|
next unless al.section == section
res = {
'old_name' => al.old_name,
'new_name' => al.new_name,
}
if al.comment && !al.comment.empty?
res['desc'] = markup(al.comment, true)
end
values << res
end
values
end
# Build a list of constants
def build_constants_summary_list(section)
values = []
@context.constants.each do |co|
next unless co.section == section
res = {
'name' => co.name,
'value' => CGI.escapeHTML(co.value)
}
res['desc'] = markup(co.comment, true) if co.comment && !co.comment.empty?
values << res
end
values
end
def build_requires_list(context)
potentially_referenced_list(context.requires) {|fn| [fn + ".rb"] }
end
def build_include_list(context)
potentially_referenced_list(context.includes)
end
# Build a list from an array of <i>Htmlxxx</i> items. Look up each
# in the AllReferences hash: if we find a corresponding entry,
# we generate a hyperlink to it, otherwise just output the name.
# However, some names potentially need massaging. For example,
# you may require a Ruby file without the .rb extension,
# but the file names we know about may have it. To deal with
# this, we pass in a block which performs the massaging,
# returning an array of alternative names to match
def potentially_referenced_list(array)
res = []
array.each do |i|
ref = AllReferences[i.name]
# if !ref
# container = @context.parent
# while !ref && container
# name = container.name + "::" + i.name
# ref = AllReferences[name]
# container = container.parent
# end
# end
ref = @context.find_symbol(i.name)
ref = ref.viewer if ref
if !ref && block_given?
possibles = yield(i.name)
while !ref and !possibles.empty?
ref = AllReferences[possibles.shift]
end
end
h_name = CGI.escapeHTML(i.name)
if ref and ref.document_self
path = url(ref.path)
res << { "name" => h_name, "aref" => path }
else
res << { "name" => h_name }
end
end
res
end
# Build an array of arrays of method details. The outer array has up
# to six entries, public, private, and protected for both class
# methods, the other for instance methods. The inner arrays contain
# a hash for each method
def build_method_detail_list(section)
outer = []
methods = @methods.sort
for singleton in [true, false]
for vis in [ :public, :protected, :private ]
res = []
methods.each do |m|
if m.section == section and
m.document_self and
m.visibility == vis and
m.singleton == singleton
row = {}
if m.call_seq
row["callseq"] = m.call_seq.gsub(/->/, '→')
else
row["name"] = CGI.escapeHTML(m.name)
row["params"] = m.params
end
desc = m.description.strip
row["m_desc"] = desc unless desc.empty?
row["aref"] = m.aref
row["visibility"] = m.visibility.to_s
alias_names = []
m.aliases.each do |other|
if other.viewer # won't be if the alias is private
alias_names << {
'name' => other.name,
'aref' => other.viewer.as_href(path)
}
end
end
unless alias_names.empty?
row["aka"] = alias_names
end
if @options.inline_source
code = m.source_code
row["sourcecode"] = code if code
else
code = m.src_url
if code
row["codeurl"] = code
row["imgurl"] = m.img_url
end
end
res << row
end
end
if res.size > 0
outer << {
"type" => vis.to_s.capitalize,
"category" => singleton ? "Class" : "Instance",
"methods" => res
}
end
end
end
outer
end
# Build the structured list of classes and modules contained
# in this context.
def build_class_list(level, from, section, infile=nil)
res = ""
prefix = " ::" * level;
from.modules.sort.each do |mod|
next unless mod.section == section
next if infile && !mod.defined_in?(infile)
if mod.document_self
res <<
prefix <<
"Module " <<
href(url(mod.viewer.path), "link", mod.full_name) <<
"<br />\n" <<
build_class_list(level + 1, mod, section, infile)
end
end
from.classes.sort.each do |cls|
next unless cls.section == section
next if infile && !cls.defined_in?(infile)
if cls.document_self
res <<
prefix <<
"Class " <<
href(url(cls.viewer.path), "link", cls.full_name) <<
"<br />\n" <<
build_class_list(level + 1, cls, section, infile)
end
end
res
end
def url(target)
HTMLGenerator.gen_url(path, target)
end
def aref_to(target)
if @options.all_one_file
"#" + target
else
url(target)
end
end
def document_self
@context.document_self
end
def diagram_reference(diagram)
res = diagram.gsub(/((?:src|href)=")(.*?)"/) {
$1 + url($2) + '"'
}
res
end
# Find a symbol in ourselves or our parent
def find_symbol(symbol, method=nil)
res = @context.find_symbol(symbol, method)
if res
res = res.viewer
end
res
end
# create table of contents if we contain sections
def add_table_of_sections
toc = []
@context.sections.each do |section|
if section.title
toc << {
'secname' => section.title,
'href' => section.sequence
}
end
end
@values['toc'] = toc unless toc.empty?
end
end
#####################################################################
#
# Wrap a ClassModule context
class HtmlClass < ContextUser
attr_reader :path
def initialize(context, html_file, prefix, options)
super(context, options)
@html_file = html_file
@is_module = context.is_module?
@values = {}
context.viewer = self
if options.all_one_file
@path = context.full_name
else
@path = http_url(context.full_name, prefix)
end
collect_methods
AllReferences.add(name, self)
end
# return the relative file name to store this class in,
# which is also its url
def http_url(full_name, prefix)
path = full_name.dup
if path['<<']
path.gsub!(/<<\s*(\w*)/) { "from-#$1" }
end
File.join(prefix, path.split("::")) + ".html"
end
def name
@context.full_name
end
def parent_name
@context.parent.full_name
end
def index_name
name
end
def write_on(f)
value_hash
template = TemplatePage.new(RDoc::Page::BODY,
RDoc::Page::CLASS_PAGE,
RDoc::Page::METHOD_LIST)
template.write_html_on(f, @values)
end
def value_hash
class_attribute_values
add_table_of_sections
@values["charset"] = @options.charset
@values["style_url"] = style_url(path, @options.css)
d = markup(@context.comment)
@values["description"] = d unless d.empty?
ml = build_method_summary_list
@values["methods"] = ml unless ml.empty?
il = build_include_list(@context)
@values["includes"] = il unless il.empty?
@values["sections"] = @context.sections.map do |section|
secdata = {
"sectitle" => section.title,
"secsequence" => section.sequence,
"seccomment" => markup(section.comment)
}
al = build_alias_summary_list(section)
secdata["aliases"] = al unless al.empty?
co = build_constants_summary_list(section)
secdata["constants"] = co unless co.empty?
al = build_attribute_list(section)
secdata["attributes"] = al unless al.empty?
cl = build_class_list(0, @context, section)
secdata["classlist"] = cl unless cl.empty?
mdl = build_method_detail_list(section)
secdata["method_list"] = mdl unless mdl.empty?
secdata
end
@values
end
def build_attribute_list(section)
atts = @context.attributes.sort
res = []
atts.each do |att|
next unless att.section == section
if att.visibility == :public || att.visibility == :protected || @options.show_all
entry = {
"name" => CGI.escapeHTML(att.name),
"rw" => att.rw,
"a_desc" => markup(att.comment, true)
}
unless att.visibility == :public || att.visibility == :protected
entry["rw"] << "-"
end
res << entry
end
end
res
end
def class_attribute_values
h_name = CGI.escapeHTML(name)
@values["classmod"] = @is_module ? "Module" : "Class"
@values["title"] = "#{@values['classmod']}: #{h_name}"
c = @context
c = c.parent while c and !c.diagram
if c && c.diagram
@values["diagram"] = diagram_reference(c.diagram)
end
@values["full_name"] = h_name
parent_class = @context.superclass
if parent_class
@values["parent"] = CGI.escapeHTML(parent_class)
if parent_name
lookup = parent_name + "::" + parent_class
else
lookup = parent_class
end
parent_url = AllReferences[lookup] || AllReferences[parent_class]
if parent_url and parent_url.document_self
@values["par_url"] = aref_to(parent_url.path)
end
end
files = []
@context.in_files.each do |f|
res = {}
full_path = CGI.escapeHTML(f.file_absolute_name)
res["full_path"] = full_path
res["full_path_url"] = aref_to(f.viewer.path) if f.document_self
if @options.webcvs
res["cvsurl"] = cvs_url( @options.webcvs, full_path )
end
files << res
end
@values['infiles'] = files
end
def <=>(other)
self.name <=> other.name
end
end
#####################################################################
#
# Handles the mapping of a file's information to HTML. In reality,
# a file corresponds to a +TopLevel+ object, containing modules,
# classes, and top-level methods. In theory it _could_ contain
# attributes and aliases, but we ignore these for now.
class HtmlFile < ContextUser
attr_reader :path
attr_reader :name
def initialize(context, options, file_dir)
super(context, options)
@values = {}
if options.all_one_file
@path = filename_to_label
else
@path = http_url(file_dir)
end
@name = @context.file_relative_name
collect_methods
AllReferences.add(name, self)
context.viewer = self
end
def http_url(file_dir)
File.join(file_dir, @context.file_relative_name.tr('.', '_')) +
".html"
end
def filename_to_label
@context.file_relative_name.gsub(/%|\/|\?|\#/) {|s| '%' + ("%x" % s[0]) }
end
def index_name
name
end
def parent_name
nil
end
def value_hash
file_attribute_values
add_table_of_sections
@values["charset"] = @options.charset
@values["href"] = path
@values["style_url"] = style_url(path, @options.css)
if @context.comment
d = markup(@context.comment)
@values["description"] = d if d.size > 0
end
ml = build_method_summary_list
@values["methods"] = ml unless ml.empty?
il = build_include_list(@context)
@values["includes"] = il unless il.empty?
rl = build_requires_list(@context)
@values["requires"] = rl unless rl.empty?
if @options.promiscuous
file_context = nil
else
file_context = @context
end
@values["sections"] = @context.sections.map do |section|
secdata = {
"sectitle" => section.title,
"secsequence" => section.sequence,
"seccomment" => markup(section.comment)
}
cl = build_class_list(0, @context, section, file_context)
@values["classlist"] = cl unless cl.empty?
mdl = build_method_detail_list(section)
secdata["method_list"] = mdl unless mdl.empty?
al = build_alias_summary_list(section)
secdata["aliases"] = al unless al.empty?
co = build_constants_summary_list(section)
@values["constants"] = co unless co.empty?
secdata
end
@values
end
def write_on(f)
value_hash
template = TemplatePage.new(RDoc::Page::BODY,
RDoc::Page::FILE_PAGE,
RDoc::Page::METHOD_LIST)
template.write_html_on(f, @values)
end
def file_attribute_values
full_path = @context.file_absolute_name
short_name = File.basename(full_path)
@values["title"] = CGI.escapeHTML("File: #{short_name}")
if @context.diagram
@values["diagram"] = diagram_reference(@context.diagram)
end
@values["short_name"] = CGI.escapeHTML(short_name)
@values["full_path"] = CGI.escapeHTML(full_path)
@values["dtm_modified"] = @context.file_stat.mtime.to_s
if @options.webcvs
@values["cvsurl"] = cvs_url( @options.webcvs, @values["full_path"] )
end
end
def <=>(other)
self.name <=> other.name
end
end
#####################################################################
class HtmlMethod
include MarkUp
attr_reader :context
attr_reader :src_url
attr_reader :img_url
attr_reader :source_code
@@seq = "M000000"
@@all_methods = []
def HtmlMethod::reset
@@all_methods = []
end
def initialize(context, html_class, options)
@context = context
@html_class = html_class
@options = options
@@seq = @@seq.succ
@seq = @@seq
@@all_methods << self
context.viewer = self
if (ts = @context.token_stream)
@source_code = markup_code(ts)
unless @options.inline_source
@src_url = create_source_code_file(@source_code)
@img_url = HTMLGenerator.gen_url(path, 'source.png')
end
end
AllReferences.add(name, self)
end
# return a reference to outselves to be used as an href=
# the form depends on whether we're all in one file
# or in multiple files
def as_href(from_path)
if @options.all_one_file
"#" + path
else
HTMLGenerator.gen_url(from_path, path)
end
end
def name
@context.name
end
def section
@context.section
end
def index_name
"#{@context.name} (#{@html_class.name})"
end
def parent_name
if @context.parent.parent
@context.parent.parent.full_name
else
nil
end
end
def aref
@seq
end
def path
if @options.all_one_file
aref
else
@html_class.path + "#" + aref
end
end
def description
markup(@context.comment)
end
def visibility
@context.visibility
end
def singleton
@context.singleton
end
def call_seq
cs = @context.call_seq
if cs
cs.gsub(/\n/, "<br />\n")
else
nil
end
end
def params
# params coming from a call-seq in 'C' will start with the
# method name
p = @context.params
if p !~ /^\w/
p = @context.params.gsub(/\s*\#.*/, '')
p = p.tr("\n", " ").squeeze(" ")
p = "(" + p + ")" unless p[0] == ?(
if (block = @context.block_params)
# If this method has explicit block parameters, remove any
# explicit &block
p.sub!(/,?\s*&\w+/, '')
block.gsub!(/\s*\#.*/, '')
block = block.tr("\n", " ").squeeze(" ")
if block[0] == ?(
block.sub!(/^\(/, '').sub!(/\)/, '')
end
p << " {|#{block.strip}| ...}"
end
end
CGI.escapeHTML(p)
end
def create_source_code_file(code_body)
meth_path = @html_class.path.sub(/\.html$/, '.src')
File.makedirs(meth_path)
file_path = File.join(meth_path, @seq) + ".html"
template = TemplatePage.new(RDoc::Page::SRC_PAGE)
File.open(file_path, "w") do |f|
values = {
'title' => CGI.escapeHTML(index_name),
'code' => code_body,
'style_url' => style_url(file_path, @options.css),
'charset' => @options.charset
}
template.write_html_on(f, values)
end
HTMLGenerator.gen_url(path, file_path)
end
def HtmlMethod.all_methods
@@all_methods
end
def <=>(other)
@context <=> other.context
end
##
# Given a sequence of source tokens, mark up the source code
# to make it look purty.
def markup_code(tokens)
src = ""
tokens.each do |t|
next unless t
# p t.class
# style = STYLE_MAP[t.class]
style = case t
when RubyToken::TkCONSTANT then "ruby-constant"
when RubyToken::TkKW then "ruby-keyword kw"
when RubyToken::TkIVAR then "ruby-ivar"
when RubyToken::TkOp then "ruby-operator"
when RubyToken::TkId then "ruby-identifier"
when RubyToken::TkNode then "ruby-node"
when RubyToken::TkCOMMENT then "ruby-comment cmt"
when RubyToken::TkREGEXP then "ruby-regexp re"
when RubyToken::TkSTRING then "ruby-value str"
when RubyToken::TkVal then "ruby-value"
else
nil
end
text = CGI.escapeHTML(t.text)
if style
src << "<span class=\"#{style}\">#{text}</span>"
else
src << text
end
end
add_line_numbers(src) if Options.instance.include_line_numbers
src
end
# we rely on the fact that the first line of a source code
# listing has
# # File xxxxx, line dddd
def add_line_numbers(src)
if src =~ /\A.*, line (\d+)/
first = $1.to_i - 1
last = first + src.count("\n")
size = last.to_s.length
real_fmt = "%#{size}d: "
fmt = " " * (size+2)
src.gsub!(/^/) do
res = sprintf(fmt, first)
first += 1
fmt = real_fmt
res
end
end
end
def document_self
@context.document_self
end
def aliases
@context.aliases
end
def find_symbol(symbol, method=nil)
res = @context.parent.find_symbol(symbol, method)
if res
res = res.viewer
end
res
end
end
#####################################################################
class HTMLGenerator
include MarkUp
##
# convert a target url to one that is relative to a given
# path
def HTMLGenerator.gen_url(path, target)
from = File.dirname(path)
to, to_file = File.split(target)
from = from.split("/")
to = to.split("/")
while from.size > 0 and to.size > 0 and from[0] == to[0]
from.shift
to.shift
end
from.fill("..")
from.concat(to)
from << to_file
File.join(*from)
end
# Generators may need to return specific subclasses depending
# on the options they are passed. Because of this
# we create them using a factory
def HTMLGenerator.for(options)
AllReferences::reset
HtmlMethod::reset
if options.all_one_file
HTMLGeneratorInOne.new(options)
else
HTMLGenerator.new(options)
end
end
class <<self
protected :new
end
# Set up a new HTML generator. Basically all we do here is load
# up the correct output temlate
def initialize(options) #:not-new:
@options = options
load_html_template
end
##
# Build the initial indices and output objects
# based on an array of TopLevel objects containing
# the extracted information.
def generate(toplevels)
@toplevels = toplevels
@files = []
@classes = []
write_style_sheet
gen_sub_directories()
build_indices
generate_html
end
private
##
# Load up the HTML template specified in the options.
# If the template name contains a slash, use it literally
#
def load_html_template
template = @options.template
unless template =~ %r{/|\\}
template = File.join("rdoc/generators/template",
@options.generator.key, template)
end
require template
extend RDoc::Page
rescue LoadError
$stderr.puts "Could not find HTML template '#{template}'"
exit 99
end
##
# Write out the style sheet used by the main frames
#
def write_style_sheet
template = TemplatePage.new(RDoc::Page::STYLE)
unless @options.css
File.open(CSS_NAME, "w") do |f|
values = { "fonts" => RDoc::Page::FONTS }
template.write_html_on(f, values)
end
end
end
##
# See the comments at the top for a description of the
# directory structure
def gen_sub_directories
File.makedirs(FILE_DIR, CLASS_DIR)
rescue
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | true |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/generators/ri_generator.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/generators/ri_generator.rb | # We're responsible for generating all the HTML files
# from the object tree defined in code_objects.rb. We
# generate:
#
# [files] an html file for each input file given. These
# input files appear as objects of class
# TopLevel
#
# [classes] an html file for each class or module encountered.
# These classes are not grouped by file: if a file
# contains four classes, we'll generate an html
# file for the file itself, and four html files
# for the individual classes.
#
# [indices] we generate three indices for files, classes,
# and methods. These are displayed in a browser
# like window with three index panes across the
# top and the selected description below
#
# Method descriptions appear in whatever entity (file, class,
# or module) that contains them.
#
# We generate files in a structure below a specified subdirectory,
# normally +doc+.
#
# opdir
# |
# |___ files
# | |__ per file summaries
# |
# |___ classes
# |__ per class/module descriptions
#
# HTML is generated using the Template class.
#
require 'ftools'
require 'rdoc/options'
require 'rdoc/template'
require 'rdoc/markup/simple_markup'
require 'rdoc/markup/simple_markup/to_flow'
require 'cgi'
require 'rdoc/ri/ri_cache'
require 'rdoc/ri/ri_reader'
require 'rdoc/ri/ri_writer'
require 'rdoc/ri/ri_descriptions'
module Generators
class RIGenerator
# Generators may need to return specific subclasses depending
# on the options they are passed. Because of this
# we create them using a factory
def RIGenerator.for(options)
new(options)
end
class <<self
protected :new
end
# Set up a new HTML generator. Basically all we do here is load
# up the correct output temlate
def initialize(options) #:not-new:
@options = options
@ri_writer = RI::RiWriter.new(".")
@markup = SM::SimpleMarkup.new
@to_flow = SM::ToFlow.new
end
##
# Build the initial indices and output objects
# based on an array of TopLevel objects containing
# the extracted information.
def generate(toplevels)
RDoc::TopLevel.all_classes_and_modules.each do |cls|
process_class(cls)
end
end
def process_class(from_class)
generate_class_info(from_class)
# now recure into this classes constituent classess
from_class.each_classmodule do |mod|
process_class(mod)
end
end
def generate_class_info(cls)
if cls === RDoc::NormalModule
cls_desc = RI::ModuleDescription.new
else
cls_desc = RI::ClassDescription.new
cls_desc.superclass = cls.superclass
end
cls_desc.name = cls.name
cls_desc.full_name = cls.full_name
cls_desc.comment = markup(cls.comment)
cls_desc.attributes =cls.attributes.sort.map do |a|
RI::Attribute.new(a.name, a.rw, markup(a.comment))
end
cls_desc.constants = cls.constants.map do |c|
RI::Constant.new(c.name, c.value, markup(c.comment))
end
cls_desc.includes = cls.includes.map do |i|
RI::IncludedModule.new(i.name)
end
class_methods, instance_methods = method_list(cls)
cls_desc.class_methods = class_methods.map do |m|
RI::MethodSummary.new(m.name)
end
cls_desc.instance_methods = instance_methods.map do |m|
RI::MethodSummary.new(m.name)
end
update_or_replace(cls_desc)
class_methods.each do |m|
generate_method_info(cls_desc, m)
end
instance_methods.each do |m|
generate_method_info(cls_desc, m)
end
end
def generate_method_info(cls_desc, method)
meth_desc = RI::MethodDescription.new
meth_desc.name = method.name
meth_desc.full_name = cls_desc.full_name
if method.singleton
meth_desc.full_name += "::"
else
meth_desc.full_name += "#"
end
meth_desc.full_name << method.name
meth_desc.comment = markup(method.comment)
meth_desc.params = params_of(method)
meth_desc.visibility = method.visibility.to_s
meth_desc.is_singleton = method.singleton
meth_desc.block_params = method.block_params
meth_desc.aliases = method.aliases.map do |a|
RI::AliasName.new(a.name)
end
@ri_writer.add_method(cls_desc, meth_desc)
end
private
# return a list of class and instance methods that we'll be
# documenting
def method_list(cls)
list = cls.method_list
unless @options.show_all
list = list.find_all do |m|
m.visibility == :public || m.visibility == :protected || m.force_documentation
end
end
c = []
i = []
list.sort.each do |m|
if m.singleton
c << m
else
i << m
end
end
return c,i
end
def params_of(method)
if method.call_seq
method.call_seq
else
params = method.params || ""
p = params.gsub(/\s*\#.*/, '')
p = p.tr("\n", " ").squeeze(" ")
p = "(" + p + ")" unless p[0] == ?(
if (block = method.block_params)
block.gsub!(/\s*\#.*/, '')
block = block.tr("\n", " ").squeeze(" ")
if block[0] == ?(
block.sub!(/^\(/, '').sub!(/\)/, '')
end
p << " {|#{block.strip}| ...}"
end
p
end
end
def markup(comment)
return nil if !comment || comment.empty?
# Convert leading comment markers to spaces, but only
# if all non-blank lines have them
if comment =~ /^(?>\s*)[^\#]/
content = comment
else
content = comment.gsub(/^\s*(#+)/) { $1.tr('#',' ') }
end
@markup.convert(content, @to_flow)
end
# By default we replace existing classes with the
# same name. If the --merge option was given, we instead
# merge this definition into an existing class. We add
# our methods, aliases, etc to that class, but do not
# change the class's description.
def update_or_replace(cls_desc)
old_cls = nil
if @options.merge
rdr = RI::RiReader.new(RI::RiCache.new(@options.op_dir))
namespace = rdr.top_level_namespace
namespace = rdr.lookup_namespace_in(cls_desc.name, namespace)
if namespace.empty?
$stderr.puts "You asked me to merge this source into existing "
$stderr.puts "documentation. This file references a class or "
$stderr.puts "module called #{cls_desc.name} which I don't"
$stderr.puts "have existing documentation for."
$stderr.puts
$stderr.puts "Perhaps you need to generate its documentation first"
exit 1
else
old_cls = namespace[0]
end
end
if old_cls.nil?
# no merge: simply overwrite
@ri_writer.remove_class(cls_desc)
@ri_writer.add_class(cls_desc)
else
# existing class: merge in
old_desc = rdr.get_class(old_cls)
old_desc.merge_in(cls_desc)
@ri_writer.add_class(old_desc)
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/generators/template/chm/chm.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/generators/template/chm/chm.rb | module RDoc
module Page
require "rdoc/generators/template/html/html"
# This is a nasty little hack, but hhc doesn't support the <?xml
# tag, so...
BODY.sub!(/<\?xml.*\?>/, '')
SRC_PAGE.sub!(/<\?xml.*\?>/, '')
HPP_FILE = %{
[OPTIONS]
Auto Index = Yes
Compatibility=1.1 or later
Compiled file=%opname%.chm
Contents file=contents.hhc
Full-text search=Yes
Index file=index.hhk
Language=0x409 English(United States)
Title=%title%
[FILES]
START:all_html_files
%html_file_name%
END:all_html_files
}
CONTENTS = %{
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<HTML>
<HEAD>
<meta name="GENERATOR" content="Microsoft® HTML Help Workshop 4.1">
<!-- Sitemap 1.0 -->
</HEAD><BODY>
<OBJECT type="text/site properties">
<param name="Foreground" value="0x80">
<param name="Window Styles" value="0x800025">
<param name="ImageType" value="Folder">
</OBJECT>
<UL>
START:contents
<LI> <OBJECT type="text/sitemap">
<param name="Name" value="%c_name%">
<param name="Local" value="%ref%">
</OBJECT>
IF:methods
<ul>
START:methods
<LI> <OBJECT type="text/sitemap">
<param name="Name" value="%name%">
<param name="Local" value="%aref%">
</OBJECT>
END:methods
</ul>
ENDIF:methods
</LI>
END:contents
</UL>
</BODY></HTML>
}
CHM_INDEX = %{
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<HTML>
<HEAD>
<meta name="GENERATOR" content="Microsoft® HTML Help Workshop 4.1">
<!-- Sitemap 1.0 -->
</HEAD><BODY>
<OBJECT type="text/site properties">
<param name="Foreground" value="0x80">
<param name="Window Styles" value="0x800025">
<param name="ImageType" value="Folder">
</OBJECT>
<UL>
START:index
<LI> <OBJECT type="text/sitemap">
<param name="Name" value="%name%">
<param name="Local" value="%aref%">
</OBJECT>
END:index
</UL>
</BODY></HTML>
}
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/generators/template/xml/rdf.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/generators/template/xml/rdf.rb | module RDoc
module Page
CONTENTS_RDF = %{
IF:description
<description rd:parseType="Literal">
%description%
</description>
ENDIF:description
IF:requires
START:requires
<rd:required-file rd:name="%name%" />
END:requires
ENDIF:requires
IF:attributes
START:attributes
<contents>
<Attribute rd:name="%name%">
IF:rw
<attribute-rw>%rw%</attribute-rw>
ENDIF:rw
<description rdf:parseType="Literal">%a_desc%</description>
</Attribute>
</contents>
END:attributes
ENDIF:attributes
IF:includes
<IncludedModuleList>
START:includes
<included-module rd:name="%name%" />
END:includes
</IncludedModuleList>
ENDIF:includes
IF:method_list
START:method_list
IF:methods
START:methods
<contents>
<Method rd:name="%name%" rd:visibility="%type%"
rd:category="%category%" rd:id="%aref%">
<parameters>%params%</parameters>
IF:m_desc
<description rdf:parseType="Literal">
%m_desc%
</description>
ENDIF:m_desc
IF:sourcecode
<source-code-listing rdf:parseType="Literal">
%sourcecode%
</source-code-listing>
ENDIF:sourcecode
</Method>
</contents>
END:methods
ENDIF:methods
END:method_list
ENDIF:method_list
<!-- end method list -->
}
########################################################################
ONE_PAGE = %{<?xml version="1.0" encoding="utf-8"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns="http://pragprog.com/rdoc/rdoc.rdf#"
xmlns:rd="http://pragprog.com/rdoc/rdoc.rdf#">
<!-- RDoc -->
START:files
<rd:File rd:name="%short_name%" rd:id="%href%">
<path>%full_path%</path>
<dtm-modified>%dtm_modified%</dtm-modified>
} + CONTENTS_RDF + %{
</rd:File>
END:files
START:classes
<%classmod% rd:name="%full_name%" rd:id="%full_name%">
<classmod-info>
IF:infiles
<InFiles>
START:infiles
<infile>
<File rd:name="%full_path%"
IF:full_path_url
rdf:about="%full_path_url%"
ENDIF:full_path_url
/>
</infile>
END:infiles
</InFiles>
ENDIF:infiles
IF:parent
<superclass>HREF:par_url:parent:</superclass>
ENDIF:parent
</classmod-info>
} + CONTENTS_RDF + %{
</%classmod%>
END:classes
<!-- /RDoc -->
</rdf:RDF>
}
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/generators/template/xml/xml.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/generators/template/xml/xml.rb | module RDoc
module Page
CONTENTS_XML = %{
IF:description
<description>
%description%
</description>
ENDIF:description
<contents>
IF:requires
<required-file-list>
START:requires
<required-file name="%name%"
IF:aref
href="%aref%"
ENDIF:aref
/>
END:requires
</required-file-list>
ENDIF:requires
IF:attributes
<attribute-list>
START:attributes
<attribute name="%name%">
IF:rw
<attribute-rw>%rw%</attribute-rw>
ENDIF:rw
<description>%a_desc%</description>
</attribute>
END:attributes
</attribute-list>
ENDIF:attributes
IF:includes
<included-module-list>
START:includes
<included-module name="%name%"
IF:aref
href="%aref%"
ENDIF:aref
/>
END:includes
</included-module-list>
ENDIF:includes
IF:method_list
<method-list>
START:method_list
IF:methods
START:methods
<method name="%name%" type="%type%" category="%category%" id="%aref%">
<parameters>%params%</parameters>
IF:m_desc
<description>
%m_desc%
</description>
ENDIF:m_desc
IF:sourcecode
<source-code-listing>
%sourcecode%
</source-code-listing>
ENDIF:sourcecode
</method>
END:methods
ENDIF:methods
END:method_list
</method-list>
ENDIF:method_list
</contents>
}
########################################################################
ONE_PAGE = %{<?xml version="1.0" encoding="utf-8"?>
<rdoc>
<file-list>
START:files
<file name="%short_name%" id="%href%">
<file-info>
<path>%full_path%</path>
<dtm-modified>%dtm_modified%</dtm-modified>
</file-info>
} + CONTENTS_XML + %{
</file>
END:files
</file-list>
<class-module-list>
START:classes
<%classmod% name="%full_name%" id="%full_name%">
<classmod-info>
IF:infiles
<infiles>
START:infiles
<infile>HREF:full_path_url:full_path:</infile>
END:infiles
</infiles>
ENDIF:infiles
IF:parent
<superclass>HREF:par_url:parent:</superclass>
ENDIF:parent
</classmod-info>
} + CONTENTS_XML + %{
</%classmod%>
END:classes
</class-module-list>
</rdoc>
}
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/generators/template/html/old_html.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/generators/template/html/old_html.rb | module RDoc
# This is how you define the HTML that RDoc generates. Simply create
# a file in rdoc/generators/html_templates that creates the
# module RDoc::Page and populate it as described below. Then invoke
# rdoc using the --template <name of your file> option, and
# your template will be used.
#
# The constants defining pages use a simple templating system:
#
# * The templating system is passed a hash. Keys in the hash correspond
# to tags on this page. The tag %abc% is looked up in the hash,
# and is replaced by the corresponding hash value.
#
# * Some tags are optional. You can detect this using IF/ENDIF
#
# IF: title
# The value of title is %title%
# ENDIF: title
#
# * Some entries in the hash have values that are arrays, where each
# entry in the array is itself a hash. These are used to generate
# lists using the START: construct. For example, given a hash
# containing
#
# { 'people' => [ { 'name' => 'Fred', 'age' => '12' },
# { 'name' => 'Mary', 'age' => '21' } ]
#
# You could generate a simple table using
#
# <table>
# START:people
# <tr><td>%name%<td>%age%</tr>
# END:people
# </table>
#
# These lists can be nested to an arbitrary depth
#
# * the construct HREF:url:name: generates <a href="%url%">%name%</a>
# if +url+ is defined in the hash, or %name% otherwise.
#
#
# Your file must contain the following constants
#
# [*FONTS*] a list of fonts to be used
# [*STYLE*] a CSS section (without the <style> or comments). This is
# used to generate a style.css file
#
# [*BODY*]
# The main body of all non-index RDoc pages. BODY will contain
# two !INCLUDE!s. The first is used to include a document-type
# specific header (FILE_PAGE or CLASS_PAGE). The second include
# is for the method list (METHOD_LIST). THe body is passed:
#
# %title%::
# the page's title
#
# %style_url%::
# the url of a style sheet for this page
#
# %diagram%::
# the optional URL of a diagram for this page
#
# %description%::
# a (potentially multi-paragraph) string containing the
# description for th file/class/module.
#
# %requires%::
# an optional list of %aref%/%name% pairs, one for each module
# required by this file.
#
# %methods%::
# an optional list of %aref%/%name%, one for each method
# documented on this page. This is intended to be an index.
#
# %attributes%::
# An optional list. For each attribute it contains:
# %name%:: the attribute name
# %rw%:: r/o, w/o, or r/w
# %a_desc%:: description of the attribute
#
# %classlist%::
# An optional string containing an already-formatted list of
# classes and modules documented in this file
#
# For FILE_PAGE entries, the body will be passed
#
# %short_name%::
# The name of the file
#
# %full_path%::
# The full path to the file
#
# %dtm_modified%::
# The date/time the file was last changed
#
# For class and module pages, the body will be passed
#
# %classmod%::
# The name of the class or module
#
# %files%::
# A list. For each file this class is defined in, it contains:
# %full_path_url%:: an (optional) URL of the RDoc page
# for this file
# %full_path%:: the name of the file
#
# %par_url%::
# The (optional) URL of the RDoc page documenting this class's
# parent class
#
# %parent%::
# The name of this class's parent.
#
# For both files and classes, the body is passed the following information
# on includes and methods:
#
# %includes%::
# Optional list of included modules. For each, it receives
# %aref%:: optional URL to RDoc page for the module
# %name%:: the name of the module
#
# %method_list%::
# Optional list of methods of a particular class and category.
#
# Each method list entry contains:
#
# %type%:: public/private/protected
# %category%:: instance/class
# %methods%:: a list of method descriptions
#
# Each method description contains:
#
# %aref%:: a target aref, used when referencing this method
# description. You should code this as <a name="%aref%">
# %codeurl%:: the optional URL to the page containing this method's
# source code.
# %name%:: the method's name
# %params%:: the method's parameters
# %callseq%:: a full calling sequence
# %m_desc%:: the (potentially multi-paragraph) description of
# this method.
#
# [*CLASS_PAGE*]
# Header for pages documenting classes and modules. See
# BODY above for the available parameters.
#
# [*FILE_PAGE*]
# Header for pages documenting files. See
# BODY above for the available parameters.
#
# [*METHOD_LIST*]
# Controls the display of the listing of methods. See BODY for
# parameters.
#
# [*INDEX*]
# The top-level index page. For a browser-like environment
# define a frame set that includes the file, class, and
# method indices. Passed
# %title%:: title of page
# %initial_page% :: url of initial page to display
#
# [*CLASS_INDEX*]
# Individual files for the three indexes. Passed:
# %index_url%:: URL of main index page
# %entries%:: List of
# %name%:: name of an index entry
# %href%:: url of corresponding page
# [*METHOD_INDEX*]
# Same as CLASS_INDEX for methods
#
# [*FILE_INDEX*]
# Same as CLASS_INDEX for methods
#
# [*FR_INDEX_BODY*]
# A wrapper around CLASS_INDEX, METHOD_INDEX, and FILE_INDEX.
# If those index strings contain the complete HTML for the
# output, then FR_INDEX_BODY can simply be !INCLUDE!
#
# [*SRC_PAGE*]
# Page used to display source code. Passed %title% and %code%,
# the latter being a multi-line string of code.
module Page
FONTS = "Verdana, Arial, Helvetica, sans-serif"
STYLE = %{
body,td,p { font-family: %fonts%;
color: #000040;
}
.attr-rw { font-size: x-small; color: #444488 }
.title-row { background: #0000aa;
color: #eeeeff;
}
.big-title-font { color: white;
font-family: %fonts%;
font-size: large;
height: 50px}
.small-title-font { color: aqua;
font-family: %fonts%;
font-size: xx-small; }
.aqua { color: aqua }
.method-name, attr-name {
font-family: monospace; font-weight: bold;
}
.tablesubtitle, .tablesubsubtitle {
width: 100%;
margin-top: 1ex;
margin-bottom: .5ex;
padding: 5px 0px 5px 20px;
font-size: large;
color: aqua;
background: #3333cc;
}
.name-list {
font-family: monospace;
margin-left: 40px;
margin-bottom: 2ex;
line-height: 140%;
}
.description {
margin-left: 40px;
margin-top: -2ex;
margin-bottom: 2ex;
}
.description p {
line-height: 140%;
}
.aka {
margin-left: 40px;
margin-bottom: 2ex;
line-height: 100%;
font-size: small;
color: #808080;
}
.methodtitle {
font-size: medium;
text-decoration: none;
color: #0000AA;
background: white;
}
.paramsig {
font-size: small;
}
.srcbut { float: right }
pre { font-size: 1.2em; }
tt { font-size: 1.2em; }
pre.source {
border-style: groove;
background-color: #ddddff;
margin-left: 40px;
padding: 1em 0em 1em 2em;
}
.classlist {
margin-left: 40px;
margin-bottom: 2ex;
line-height: 140%;
}
li {
display: list-item;
margin-top: .6em;
}
.ruby-comment { color: green; font-style: italic }
.ruby-constant { color: #4433aa; font-weight: bold; }
.ruby-identifier { color: #222222; }
.ruby-ivar { color: #2233dd; }
.ruby-keyword { color: #3333FF; font-weight: bold }
.ruby-node { color: #777777; }
.ruby-operator { color: #111111; }
.ruby-regexp { color: #662222; }
.ruby-value { color: #662222; font-style: italic }
}
############################################################################
HEADER = %{
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>%title%</title>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
<link rel=StyleSheet href="%style_url%" type="text/css" media="screen" />
<script type="text/javascript" language="JavaScript">
<!--
function popCode(url) {
window.open(url, "Code",
"resizable=yes,scrollbars=yes,toolbar=no,status=no,height=150,width=400")
}
//-->
</script>
</head>
}
###################################################################
METHOD_LIST = %{
IF:includes
<table summary="Included modules" cellpadding="5" width="100%">
<tr><td class="tablesubtitle">Included modules</td></tr>
</table>
<div class="name-list">
START:includes
<span class="method-name">HREF:aref:name:</span>
END:includes
</div>
ENDIF:includes
IF:method_list
START:method_list
IF:methods
<table summary="Method list" cellpadding="5" width="100%">
<tr><td class="tablesubtitle">%type% %category% methods</td></tr>
</table>
START:methods
<table summary="method" width="100%" cellspacing="0" cellpadding="5" border="0">
<tr><td class="methodtitle">
<a name="%aref%"></a>
IF:codeurl
<a href="%codeurl%" target="Code" class="methodtitle"
onClick="popCode('%codeurl%');return false;">
ENDIF:codeurl
IF:callseq
<b>%callseq%</b>
ENDIF:callseq
IFNOT:callseq
<b>%name%</b>%params%
ENDIF:callseq
IF:codeurl
</a>
ENDIF:codeurl
</td></tr>
</table>
IF:m_desc
<div class="description">
%m_desc%
</div>
ENDIF:m_desc
IF:aka
<div class="aka">
This method is also aliased as
START:aka
<a href="%aref%">%name%</a>
END:aka
</div>
ENDIF:aka
IF:sourcecode
<pre class="source">
%sourcecode%
</pre>
ENDIF:sourcecode
END:methods
ENDIF:methods
END:method_list
ENDIF:method_list
}
###################################################################
CONTEXT_CONTENT = %{
IF:diagram
<table summary="Diagram of classes and modules" width="100%">
<tr><td align="center">
%diagram%
</td></tr></table>
ENDIF:diagram
IF:description
<div class="description">%description%</div>
ENDIF:description
IF:requires
<table summary="Requires" cellpadding="5" width="100%">
<tr><td class="tablesubtitle">Required files</td></tr>
</table>
<div class="name-list">
START:requires
HREF:aref:name:
END:requires
</div>
ENDIF:requires
IF:methods
<table summary="Methods" cellpadding="5" width="100%">
<tr><td class="tablesubtitle">Methods</td></tr>
</table>
<div class="name-list">
START:methods
HREF:aref:name:
END:methods
</div>
ENDIF:methods
IF:constants
<table summary="Constants" cellpadding="5" width="100%">
<tr><td class="tablesubtitle">Constants</td></tr>
</table>
<table cellpadding="5">
START:constants
<tr valign="top"><td>%name%</td><td>=</td><td>%value%</td></tr>
IF:desc
<tr><td></td><td></td><td>%desc%</td></tr>
ENDIF:desc
END:constants
</table>
ENDIF:constants
IF:aliases
<table summary="Aliases" cellpadding="5" width="100%">
<tr><td class="tablesubtitle">External Aliases</td></tr>
</table>
<div class="name-list">
START:aliases
%old_name% -> %new_name%<br />
END:aliases
</div>
ENDIF:aliases
IF:attributes
<table summary="Attributes" cellpadding="5" width="100%">
<tr><td class="tablesubtitle">Attributes</td></tr>
</table>
<table summary="Attribute details" cellspacing="5">
START:attributes
<tr valign="top">
<td class="attr-name">%name%</td>
IF:rw
<td align="center" class="attr-rw"> [%rw%] </td>
ENDIF:rw
IFNOT:rw
<td></td>
ENDIF:rw
<td>%a_desc%</td>
</tr>
END:attributes
</table>
ENDIF:attributes
IF:classlist
<table summary="List of classes" cellpadding="5" width="100%">
<tr><td class="tablesubtitle">Classes and Modules</td></tr>
</table>
<div class="classlist">
%classlist%
</div>
ENDIF:classlist
}
###############################################################################
BODY = HEADER + %{
<body bgcolor="white">
!INCLUDE! <!-- banner header -->
} +
CONTEXT_CONTENT + METHOD_LIST +
%{
</body>
</html>
}
###############################################################################
FILE_PAGE = <<_FILE_PAGE_
<table summary="Information on file" width="100%">
<tr class="title-row">
<td><table summary="layout" width="100%"><tr>
<td class="big-title-font" colspan="2">%short_name%</td>
<td align="right"><table summary="layout" cellspacing="0" cellpadding="2">
<tr>
<td class="small-title-font">Path:</td>
<td class="small-title-font">%full_path%
IF:cvsurl
(<a href="%cvsurl%"><acronym title="Concurrent Versioning System">CVS</acronym></a>)
ENDIF:cvsurl
</td>
</tr>
<tr>
<td class="small-title-font">Modified:</td>
<td class="small-title-font">%dtm_modified%</td>
</tr>
</table>
</td></tr></table></td>
</tr>
</table>
_FILE_PAGE_
###################################################################
CLASS_PAGE = %{
<table summary="Information on class" width="100%" border="0" cellspacing="0">
<tr class="title-row">
<td class="big-title-font">
<sup><font color="aqua">%classmod%</font></sup> %full_name%
</td>
<td align="right">
<table summary="layout" cellspacing="0" cellpadding="2">
<tr valign="top">
<td class="small-title-font">In:</td>
<td class="small-title-font">
START:infiles
IF:full_path_url
<a href="%full_path_url%" class="aqua">
ENDIF:full_path_url
%full_path%
IF:full_path_url
</a>
ENDIF:full_path_url
IF:cvsurl
(<a href="%cvsurl%"><acronym title="Concurrent Versioning System">CVS</acronym></a>)
ENDIF:cvsurl
<br />
END:infiles
</td>
</tr>
IF:parent
<tr>
<td class="small-title-font">Parent:</td>
<td class="small-title-font">
IF:par_url
<a href="%par_url%" class="aqua">
ENDIF:par_url
%parent%
IF:par_url
</a>
ENDIF:par_url
</td>
</tr>
ENDIF:parent
</table>
</td>
</tr>
</table>
}
=begin
=end
########################## Source code ##########################
SRC_PAGE = %{
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%">
<title>%title%</title>
<link rel="stylesheet" href="%style_url%" type="text/css" media="screen" />
</head>
<body bgcolor="white">
<pre>%code%</pre>
</body>
</html>
}
########################## Index ################################
FR_INDEX_BODY = %{
!INCLUDE!
}
FILE_INDEX = %{
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%">
<title>%list_title%</title>
<style type="text/css">
<!--
body {
background-color: #ddddff;
font-family: #{FONTS};
font-size: 11px;
font-style: normal;
line-height: 14px;
color: #000040;
}
div.banner {
background: #0000aa;
color: white;
padding: 1;
margin: 0;
font-size: 90%;
font-weight: bold;
line-height: 1.1;
text-align: center;
width: 100%;
}
A.xx { color: white; font-weight: bold; }
-->
</style>
<base target="docwin">
</head>
<body>
<div class="banner"><a href="%index_url%" class="xx">%list_title%</a></div>
START:entries
<a href="%href%">%name%</a><br />
END:entries
</body></html>
}
CLASS_INDEX = FILE_INDEX
METHOD_INDEX = FILE_INDEX
INDEX = %{
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%">
<title>%title%</title></head>
<frameset rows="20%, 80%">
<frameset cols="25%,35%,45%">
<frame src="fr_file_index.html" title="Files" name="Files">
<frame src="fr_class_index.html" name="Classes">
<frame src="fr_method_index.html" name="Methods">
</frameset>
<frame src="%initial_page%" name="docwin">
<noframes>
<body bgcolor="white">
Sorry, RDoc currently only generates HTML using frames.
</body>
</noframes>
</frameset>
</html>
}
######################################################################
#
# The following is used for the -1 option
#
CONTENTS_XML = %{
IF:description
%description%
ENDIF:description
IF:requires
<h4>Requires:</h4>
<ul>
START:requires
IF:aref
<li><a href="%aref%">%name%</a></li>
ENDIF:aref
IFNOT:aref
<li>%name%</li>
ENDIF:aref
END:requires
</ul>
ENDIF:requires
IF:attributes
<h4>Attributes</h4>
<table>
START:attributes
<tr><td>%name%</td><td>%rw%</td><td>%a_desc%</td></tr>
END:attributes
</table>
ENDIF:attributes
IF:includes
<h4>Includes</h4>
<ul>
START:includes
IF:aref
<li><a href="%aref%">%name%</a></li>
ENDIF:aref
IFNOT:aref
<li>%name%</li>
ENDIF:aref
END:includes
</ul>
ENDIF:includes
IF:method_list
<h3>Methods</h3>
START:method_list
IF:methods
START:methods
<h4>%type% %category% method: <a name="%aref%">%name%%params%</a></h4>
IF:m_desc
%m_desc%
ENDIF:m_desc
IF:sourcecode
<blockquote><pre>
%sourcecode%
</pre></blockquote>
ENDIF:sourcecode
END:methods
ENDIF:methods
END:method_list
ENDIF:method_list
}
end
end
require 'rdoc/generators/template/html/one_page_html'
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/generators/template/html/one_page_html.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/generators/template/html/one_page_html.rb | module RDoc
module Page
######################################################################
#
# The following is used for the -1 option
#
CONTENTS_XML = %{
IF:description
%description%
ENDIF:description
IF:requires
<h4>Requires:</h4>
<ul>
START:requires
IF:aref
<li><a href="%aref%">%name%</a></li>
ENDIF:aref
IFNOT:aref
<li>%name%</li>
ENDIF:aref
END:requires
</ul>
ENDIF:requires
IF:attributes
<h4>Attributes</h4>
<table>
START:attributes
<tr><td>%name%</td><td>%rw%</td><td>%a_desc%</td></tr>
END:attributes
</table>
ENDIF:attributes
IF:includes
<h4>Includes</h4>
<ul>
START:includes
IF:aref
<li><a href="%aref%">%name%</a></li>
ENDIF:aref
IFNOT:aref
<li>%name%</li>
ENDIF:aref
END:includes
</ul>
ENDIF:includes
IF:method_list
<h3>Methods</h3>
START:method_list
IF:methods
START:methods
<h4>%type% %category% method:
IF:callseq
<a name="%aref%">%callseq%</a>
ENDIF:callseq
IFNOT:callseq
<a name="%aref%">%name%%params%</a></h4>
ENDIF:callseq
IF:m_desc
%m_desc%
ENDIF:m_desc
IF:sourcecode
<blockquote><pre>
%sourcecode%
</pre></blockquote>
ENDIF:sourcecode
END:methods
ENDIF:methods
END:method_list
ENDIF:method_list
}
########################################################################
ONE_PAGE = %{
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>%title%</title>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
</head>
<body>
START:files
<h2>File: %short_name%</h2>
<table>
<tr><td>Path:</td><td>%full_path%</td></tr>
<tr><td>Modified:</td><td>%dtm_modified%</td></tr>
</table>
} + CONTENTS_XML + %{
END:files
IF:classes
<h2>Classes</h2>
START:classes
IF:parent
<h3>%classmod% %full_name% < HREF:par_url:parent:</h3>
ENDIF:parent
IFNOT:parent
<h3>%classmod% %full_name%</h3>
ENDIF:parent
IF:infiles
(in files
START:infiles
HREF:full_path_url:full_path:
END:infiles
)
ENDIF:infiles
} + CONTENTS_XML + %{
END:classes
ENDIF:classes
</body>
</html>
}
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/generators/template/html/hefss.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/generators/template/html/hefss.rb | module RDoc
module Page
FONTS = "Verdana, Arial, Helvetica, sans-serif"
STYLE = %{
body,p { font-family: Verdana, Arial, Helvetica, sans-serif;
color: #000040; background: #BBBBBB;
}
td { font-family: Verdana, Arial, Helvetica, sans-serif;
color: #000040;
}
.attr-rw { font-size: small; color: #444488 }
.title-row {color: #eeeeff;
background: #BBBBDD;
}
.big-title-font { color: white;
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: large;
height: 50px}
.small-title-font { color: purple;
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: small; }
.aqua { color: purple }
.method-name, attr-name {
font-family: monospace; font-weight: bold;
}
.tablesubtitle {
width: 100%;
margin-top: 1ex;
margin-bottom: .5ex;
padding: 5px 0px 5px 20px;
font-size: large;
color: purple;
background: #BBBBCC;
}
.tablesubsubtitle {
width: 100%;
margin-top: 1ex;
margin-bottom: .5ex;
padding: 5px 0px 5px 20px;
font-size: medium;
color: white;
background: #BBBBCC;
}
.name-list {
font-family: monospace;
margin-left: 40px;
margin-bottom: 2ex;
line-height: 140%;
}
.description {
margin-left: 40px;
margin-bottom: 2ex;
line-height: 140%;
}
.methodtitle {
font-size: medium;
text_decoration: none;
padding: 3px 3px 3px 20px;
color: #0000AA;
}
.column-title {
font-size: medium;
font-weight: bold;
text_decoration: none;
padding: 3px 3px 3px 20px;
color: #3333CC;
}
.variable-name {
font-family: monospace;
font-size: medium;
text_decoration: none;
padding: 3px 3px 3px 20px;
color: #0000AA;
}
.row-name {
font-size: medium;
font-weight: medium;
font-family: monospace;
text_decoration: none;
padding: 3px 3px 3px 20px;
}
.paramsig {
font-size: small;
}
.srcbut { float: right }
}
############################################################################
BODY = %{
<html><head>
<title>%title%</title>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%">
<link rel="stylesheet" href="%style_url%" type="text/css" media="screen" />
<script type="text/javascript" language="JavaScript">
<!--
function popCode(url) {
parent.frames.source.location = url
}
//-->
</script>
</head>
<body bgcolor="#BBBBBB">
!INCLUDE! <!-- banner header -->
IF:diagram
<table width="100%"><tr><td align="center">
%diagram%
</td></tr></table>
ENDIF:diagram
IF:description
<div class="description">%description%</div>
ENDIF:description
IF:requires
<table cellpadding="5" width="100%">
<tr><td class="tablesubtitle">Required files</td></tr>
</table><br />
<div class="name-list">
START:requires
HREF:aref:name:
END:requires
ENDIF:requires
</div>
IF:methods
<table cellpadding="5" width="100%">
<tr><td class="tablesubtitle">Subroutines and Functions</td></tr>
</table><br />
<div class="name-list">
START:methods
HREF:aref:name:,
END:methods
</div>
ENDIF:methods
IF:attributes
<table cellpadding="5" width="100%">
<tr><td class="tablesubtitle">Arguments</td></tr>
</table><br />
<table cellspacing="5">
START:attributes
<tr valign="top">
IF:rw
<td align="center" class="attr-rw"> [%rw%] </td>
ENDIF:rw
IFNOT:rw
<td></td>
ENDIF:rw
<td class="attr-name">%name%</td>
<td>%a_desc%</td>
</tr>
END:attributes
</table>
ENDIF:attributes
IF:classlist
<table cellpadding="5" width="100%">
<tr><td class="tablesubtitle">Modules</td></tr>
</table><br />
%classlist%<br />
ENDIF:classlist
!INCLUDE! <!-- method descriptions -->
</body>
</html>
}
###############################################################################
FILE_PAGE = <<_FILE_PAGE_
<table width="100%">
<tr class="title-row">
<td><table width="100%"><tr>
<td class="big-title-font" colspan="2"><font size="-3"><b>File</b><br /></font>%short_name%</td>
<td align="right"><table cellspacing="0" cellpadding="2">
<tr>
<td class="small-title-font">Path:</td>
<td class="small-title-font">%full_path%
IF:cvsurl
(<a href="%cvsurl%"><acronym title="Concurrent Versioning System">CVS</acronym></a>)
ENDIF:cvsurl
</td>
</tr>
<tr>
<td class="small-title-font">Modified:</td>
<td class="small-title-font">%dtm_modified%</td>
</tr>
</table>
</td></tr></table></td>
</tr>
</table><br />
_FILE_PAGE_
###################################################################
CLASS_PAGE = %{
<table width="100%" border="0" cellspacing="0">
<tr class="title-row">
<td class="big-title-font">
<font size="-3"><b>%classmod%</b><br /></font>%full_name%
</td>
<td align="right">
<table cellspacing="0" cellpadding="2">
<tr valign="top">
<td class="small-title-font">In:</td>
<td class="small-title-font">
START:infiles
HREF:full_path_url:full_path:
IF:cvsurl
(<a href="%cvsurl%"><acronym title="Concurrent Versioning System">CVS</acronym></a>)
ENDIF:cvsurl
END:infiles
</td>
</tr>
IF:parent
<tr>
<td class="small-title-font">Parent:</td>
<td class="small-title-font">
IF:par_url
<a href="%par_url%" class="cyan">
ENDIF:par_url
%parent%
IF:par_url
</a>
ENDIF:par_url
</td>
</tr>
ENDIF:parent
</table>
</td>
</tr>
</table><br />
}
###################################################################
METHOD_LIST = %{
IF:includes
<div class="tablesubsubtitle">Uses</div><br />
<div class="name-list">
START:includes
<span class="method-name">HREF:aref:name:</span>
END:includes
</div>
ENDIF:includes
IF:method_list
START:method_list
IF:methods
<table cellpadding="5" width="100%">
<tr><td class="tablesubtitle">%type% %category% methods</td></tr>
</table>
START:methods
<table width="100%" cellspacing="0" cellpadding="5" border="0">
<tr><td class="methodtitle">
<a name="%aref%">
<b>%name%</b>%params%
IF:codeurl
<a href="%codeurl%" target="source" class="srclink">src</a>
ENDIF:codeurl
</a></td></tr>
</table>
IF:m_desc
<div class="description">
%m_desc%
</div>
ENDIF:m_desc
END:methods
ENDIF:methods
END:method_list
ENDIF:method_list
}
=begin
=end
########################## Source code ##########################
SRC_PAGE = %{
<html>
<head><title>%title%</title>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%">
<style type="text/css">
.kw { color: #3333FF; font-weight: bold }
.cmt { color: green; font-style: italic }
.str { color: #662222; font-style: italic }
.re { color: #662222; }
.ruby-comment { color: green; font-style: italic }
.ruby-constant { color: #4433aa; font-weight: bold; }
.ruby-identifier { color: #222222; }
.ruby-ivar { color: #2233dd; }
.ruby-keyword { color: #3333FF; font-weight: bold }
.ruby-node { color: #777777; }
.ruby-operator { color: #111111; }
.ruby-regexp { color: #662222; }
.ruby-value { color: #662222; font-style: italic }
</style>
</head>
<body bgcolor="#BBBBBB">
<pre>%code%</pre>
</body>
</html>
}
########################## Index ################################
FR_INDEX_BODY = %{
!INCLUDE!
}
FILE_INDEX = %{
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%">
<style type="text/css">
<!--
body {
background-color: #bbbbbb;
font-family: #{FONTS};
font-size: 11px;
font-style: normal;
line-height: 14px;
color: #000040;
}
div.banner {
background: #bbbbcc;
color: white;
padding: 1;
margin: 0;
font-size: 90%;
font-weight: bold;
line-height: 1.1;
text-align: center;
width: 100%;
}
-->
</style>
<base target="docwin">
</head>
<body>
<div class="banner">%list_title%</div>
START:entries
<a href="%href%">%name%</a><br />
END:entries
</body></html>
}
CLASS_INDEX = FILE_INDEX
METHOD_INDEX = FILE_INDEX
INDEX = %{
<html>
<head>
<title>%title%</title>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%">
</head>
<frameset cols="20%,*">
<frameset rows="15%,35%,50%">
<frame src="fr_file_index.html" title="Files" name="Files">
<frame src="fr_class_index.html" name="Modules">
<frame src="fr_method_index.html" name="Subroutines and Functions">
</frameset>
<frameset rows="80%,20%">
<frame src="%initial_page%" name="docwin">
<frame src="blank.html" name="source">
</frameset>
<noframes>
<body bgcolor="#BBBBBB">
Click <a href="html/index.html">here</a> for a non-frames
version of this page.
</body>
</noframes>
</frameset>
</html>
}
# and a blank page to use as a target
BLANK = %{
<html><body bgcolor="#BBBBBB"></body></html>
}
def write_extra_pages
template = TemplatePage.new(BLANK)
File.open("blank.html", "w") { |f| template.write_html_on(f, {}) }
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/generators/template/html/kilmer.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/generators/template/html/kilmer.rb | module RDoc
module Page
FONTS = "Verdana, Arial, Helvetica, sans-serif"
STYLE = %{
body,td,p { font-family: %fonts%;
color: #000040;
}
.attr-rw { font-size: xx-small; color: #444488 }
.title-row { background-color: #CCCCFF;
color: #000010;
}
.big-title-font {
color: black;
font-weight: bold;
font-family: %fonts%;
font-size: large;
height: 60px;
padding: 10px 3px 10px 3px;
}
.small-title-font { color: black;
font-family: %fonts%;
font-size:10; }
.aqua { color: black }
.method-name, .attr-name {
font-family: font-family: %fonts%;
font-weight: bold;
font-size: small;
margin-left: 20px;
color: #000033;
}
.tablesubtitle, .tablesubsubtitle {
width: 100%;
margin-top: 1ex;
margin-bottom: .5ex;
padding: 5px 0px 5px 3px;
font-size: large;
color: black;
background-color: #CCCCFF;
border: thin;
}
.name-list {
margin-left: 5px;
margin-bottom: 2ex;
line-height: 105%;
}
.description {
margin-left: 5px;
margin-bottom: 2ex;
line-height: 105%;
font-size: small;
}
.methodtitle {
font-size: small;
font-weight: bold;
text-decoration: none;
color: #000033;
background-color: white;
}
.srclink {
font-size: small;
font-weight: bold;
text-decoration: none;
color: #0000DD;
background-color: white;
}
.paramsig {
font-size: small;
}
.srcbut { float: right }
}
############################################################################
BODY = %{
<html><head>
<title>%title%</title>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%">
<link rel="stylesheet" href="%style_url%" type="text/css" media="screen" />
<script type="text/javascript" language="JavaScript">
<!--
function popCode(url) {
parent.frames.source.location = url
}
//-->
</script>
</head>
<body bgcolor="white">
!INCLUDE! <!-- banner header -->
IF:diagram
<table width="100%"><tr><td align="center">
%diagram%
</td></tr></table>
ENDIF:diagram
IF:description
<div class="description">%description%</div>
ENDIF:description
IF:requires
<table cellpadding="5" width="100%">
<tr><td class="tablesubtitle">Required files</td></tr>
</table><br />
<div class="name-list">
START:requires
HREF:aref:name:
END:requires
ENDIF:requires
</div>
IF:methods
<table cellpadding="5" width="100%">
<tr><td class="tablesubtitle">Methods</td></tr>
</table><br />
<div class="name-list">
START:methods
HREF:aref:name:,
END:methods
</div>
ENDIF:methods
START:sections
<div id="section">
IF:sectitle
<h2 class="section-title"><a name="%secsequence%">%sectitle%</a></h2>
IF:seccomment
<div class="section-comment">
%seccomment%
</div>
ENDIF:seccomment
ENDIF:sectitle
IF:attributes
<table cellpadding="5" width="100%">
<tr><td class="tablesubtitle">Attributes</td></tr>
</table><br />
<table cellspacing="5">
START:attributes
<tr valign="top">
IF:rw
<td align="center" class="attr-rw"> [%rw%] </td>
ENDIF:rw
IFNOT:rw
<td></td>
ENDIF:rw
<td class="attr-name">%name%</td>
<td>%a_desc%</td>
</tr>
END:attributes
</table>
ENDIF:attributes
IF:classlist
<table cellpadding="5" width="100%">
<tr><td class="tablesubtitle">Classes and Modules</td></tr>
</table><br />
%classlist%<br />
ENDIF:classlist
!INCLUDE! <!-- method descriptions -->
END:sections
</body>
</html>
}
###############################################################################
FILE_PAGE = <<_FILE_PAGE_
<table width="100%">
<tr class="title-row">
<td><table width="100%"><tr>
<td class="big-title-font" colspan="2"><font size="-3"><b>File</b><br /></font>%short_name%</td>
<td align="right"><table cellspacing="0" cellpadding="2">
<tr>
<td class="small-title-font">Path:</td>
<td class="small-title-font">%full_path%
IF:cvsurl
(<a href="%cvsurl%"><acronym title="Concurrent Versioning System">CVS</acronym></a>)
ENDIF:cvsurl
</td>
</tr>
<tr>
<td class="small-title-font">Modified:</td>
<td class="small-title-font">%dtm_modified%</td>
</tr>
</table>
</td></tr></table></td>
</tr>
</table><br />
_FILE_PAGE_
###################################################################
CLASS_PAGE = %{
<table width="100%" border="0" cellspacing="0">
<tr class="title-row">
<td class="big-title-font">
<font size="-3"><b>%classmod%</b><br /></font>%full_name%
</td>
<td align="right">
<table cellspacing="0" cellpadding="2">
<tr valign="top">
<td class="small-title-font">In:</td>
<td class="small-title-font">
START:infiles
HREF:full_path_url:full_path:
IF:cvsurl
(<a href="%cvsurl%"><acronym title="Concurrent Versioning System">CVS</acronym></a>)
ENDIF:cvsurl
END:infiles
</td>
</tr>
IF:parent
<tr>
<td class="small-title-font">Parent:</td>
<td class="small-title-font">
IF:par_url
<a href="%par_url%" class="cyan">
ENDIF:par_url
%parent%
IF:par_url
</a>
ENDIF:par_url
</td>
</tr>
ENDIF:parent
</table>
</td>
</tr>
</table><br />
}
###################################################################
METHOD_LIST = %{
IF:includes
<div class="tablesubsubtitle">Included modules</div><br />
<div class="name-list">
START:includes
<span class="method-name">HREF:aref:name:</span>
END:includes
</div>
ENDIF:includes
IF:method_list
START:method_list
IF:methods
<table cellpadding=5 width="100%">
<tr><td class="tablesubtitle">%type% %category% methods</td></tr>
</table>
START:methods
<table width="100%" cellspacing="0" cellpadding="5" border="0">
<tr><td class="methodtitle">
<a name="%aref%">
IF:callseq
<b>%callseq%</b>
ENDIF:callseq
IFNOT:callseq
<b>%name%</b>%params%
ENDIF:callseq
IF:codeurl
<a href="%codeurl%" target="source" class="srclink">src</a>
ENDIF:codeurl
</a></td></tr>
</table>
IF:m_desc
<div class="description">
%m_desc%
</div>
ENDIF:m_desc
IF:aka
<div class="aka">
This method is also aliased as
START:aka
<a href="%aref%">%name%</a>
END:aka
</div>
ENDIF:aka
IF:sourcecode
<pre class="source">
%sourcecode%
</pre>
ENDIF:sourcecode
END:methods
ENDIF:methods
END:method_list
ENDIF:method_list
}
=begin
=end
########################## Source code ##########################
SRC_PAGE = %{
<html>
<head><title>%title%</title>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%">
<style type="text/css">
.ruby-comment { color: green; font-style: italic }
.ruby-constant { color: #4433aa; font-weight: bold; }
.ruby-identifier { color: #222222; }
.ruby-ivar { color: #2233dd; }
.ruby-keyword { color: #3333FF; font-weight: bold }
.ruby-node { color: #777777; }
.ruby-operator { color: #111111; }
.ruby-regexp { color: #662222; }
.ruby-value { color: #662222; font-style: italic }
.kw { color: #3333FF; font-weight: bold }
.cmt { color: green; font-style: italic }
.str { color: #662222; font-style: italic }
.re { color: #662222; }
</style>
</head>
<body bgcolor="white">
<pre>%code%</pre>
</body>
</html>
}
########################## Index ################################
FR_INDEX_BODY = %{
!INCLUDE!
}
FILE_INDEX = %{
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%">
<style>
<!--
body {
background-color: #ddddff;
font-family: #{FONTS};
font-size: 11px;
font-style: normal;
line-height: 14px;
color: #000040;
}
div.banner {
background: #0000aa;
color: white;
padding: 1;
margin: 0;
font-size: 90%;
font-weight: bold;
line-height: 1.1;
text-align: center;
width: 100%;
}
-->
</style>
<base target="docwin">
</head>
<body>
<div class="banner">%list_title%</div>
START:entries
<a href="%href%">%name%</a><br />
END:entries
</body></html>
}
CLASS_INDEX = FILE_INDEX
METHOD_INDEX = FILE_INDEX
INDEX = %{
<html>
<head>
<title>%title%</title>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%">
</head>
<frameset cols="20%,*">
<frameset rows="15%,35%,50%">
<frame src="fr_file_index.html" title="Files" name="Files">
<frame src="fr_class_index.html" name="Classes">
<frame src="fr_method_index.html" name="Methods">
</frameset>
IF:inline_source
<frame src="%initial_page%" name="docwin">
ENDIF:inline_source
IFNOT:inline_source
<frameset rows="80%,20%">
<frame src="%initial_page%" name="docwin">
<frame src="blank.html" name="source">
</frameset>
ENDIF:inline_source
<noframes>
<body bgcolor="white">
Click <a href="html/index.html">here</a> for a non-frames
version of this page.
</body>
</noframes>
</frameset>
</html>
}
# and a blank page to use as a target
BLANK = %{
<html><body bgcolor="white"></body></html>
}
def write_extra_pages
template = TemplatePage.new(BLANK)
File.open("blank.html", "w") { |f| template.write_html_on(f, {}) }
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/generators/template/html/html.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/generators/template/html/html.rb | #
# = CSS2 RDoc HTML template
#
# This is a template for RDoc that uses XHTML 1.0 Transitional and dictates a
# bit more of the appearance of the output to cascading stylesheets than the
# default. It was designed for clean inline code display, and uses DHTMl to
# toggle the visbility of each method's source with each click on the '[source]'
# link.
#
# == Authors
#
# * Michael Granger <ged@FaerieMUD.org>
#
# Copyright (c) 2002, 2003 The FaerieMUD Consortium. Some rights reserved.
#
# This work is licensed under the Creative Commons Attribution License. To view
# a copy of this license, visit http://creativecommons.org/licenses/by/1.0/ or
# send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California
# 94305, USA.
#
module RDoc
module Page
FONTS = "Verdana,Arial,Helvetica,sans-serif"
STYLE = %{
body {
font-family: Verdana,Arial,Helvetica,sans-serif;
font-size: 90%;
margin: 0;
margin-left: 40px;
padding: 0;
background: white;
}
h1,h2,h3,h4 { margin: 0; color: #efefef; background: transparent; }
h1 { font-size: 150%; }
h2,h3,h4 { margin-top: 1em; }
a { background: #eef; color: #039; text-decoration: none; }
a:hover { background: #039; color: #eef; }
/* Override the base stylesheet's Anchor inside a table cell */
td > a {
background: transparent;
color: #039;
text-decoration: none;
}
/* and inside a section title */
.section-title > a {
background: transparent;
color: #eee;
text-decoration: none;
}
/* === Structural elements =================================== */
div#index {
margin: 0;
margin-left: -40px;
padding: 0;
font-size: 90%;
}
div#index a {
margin-left: 0.7em;
}
div#index .section-bar {
margin-left: 0px;
padding-left: 0.7em;
background: #ccc;
font-size: small;
}
div#classHeader, div#fileHeader {
width: auto;
color: white;
padding: 0.5em 1.5em 0.5em 1.5em;
margin: 0;
margin-left: -40px;
border-bottom: 3px solid #006;
}
div#classHeader a, div#fileHeader a {
background: inherit;
color: white;
}
div#classHeader td, div#fileHeader td {
background: inherit;
color: white;
}
div#fileHeader {
background: #057;
}
div#classHeader {
background: #048;
}
.class-name-in-header {
font-size: 180%;
font-weight: bold;
}
div#bodyContent {
padding: 0 1.5em 0 1.5em;
}
div#description {
padding: 0.5em 1.5em;
background: #efefef;
border: 1px dotted #999;
}
div#description h1,h2,h3,h4,h5,h6 {
color: #125;;
background: transparent;
}
div#validator-badges {
text-align: center;
}
div#validator-badges img { border: 0; }
div#copyright {
color: #333;
background: #efefef;
font: 0.75em sans-serif;
margin-top: 5em;
margin-bottom: 0;
padding: 0.5em 2em;
}
/* === Classes =================================== */
table.header-table {
color: white;
font-size: small;
}
.type-note {
font-size: small;
color: #DEDEDE;
}
.xxsection-bar {
background: #eee;
color: #333;
padding: 3px;
}
.section-bar {
color: #333;
border-bottom: 1px solid #999;
margin-left: -20px;
}
.section-title {
background: #79a;
color: #eee;
padding: 3px;
margin-top: 2em;
margin-left: -30px;
border: 1px solid #999;
}
.top-aligned-row { vertical-align: top }
.bottom-aligned-row { vertical-align: bottom }
/* --- Context section classes ----------------------- */
.context-row { }
.context-item-name { font-family: monospace; font-weight: bold; color: black; }
.context-item-value { font-size: small; color: #448; }
.context-item-desc { color: #333; padding-left: 2em; }
/* --- Method classes -------------------------- */
.method-detail {
background: #efefef;
padding: 0;
margin-top: 0.5em;
margin-bottom: 1em;
border: 1px dotted #ccc;
}
.method-heading {
color: black;
background: #ccc;
border-bottom: 1px solid #666;
padding: 0.2em 0.5em 0 0.5em;
}
.method-signature { color: black; background: inherit; }
.method-name { font-weight: bold; }
.method-args { font-style: italic; }
.method-description { padding: 0 0.5em 0 0.5em; }
/* --- Source code sections -------------------- */
a.source-toggle { font-size: 90%; }
div.method-source-code {
background: #262626;
color: #ffdead;
margin: 1em;
padding: 0.5em;
border: 1px dashed #999;
overflow: hidden;
}
div.method-source-code pre { color: #ffdead; overflow: hidden; }
/* --- Ruby keyword styles --------------------- */
.standalone-code { background: #221111; color: #ffdead; overflow: hidden; }
.ruby-constant { color: #7fffd4; background: transparent; }
.ruby-keyword { color: #00ffff; background: transparent; }
.ruby-ivar { color: #eedd82; background: transparent; }
.ruby-operator { color: #00ffee; background: transparent; }
.ruby-identifier { color: #ffdead; background: transparent; }
.ruby-node { color: #ffa07a; background: transparent; }
.ruby-comment { color: #b22222; font-weight: bold; background: transparent; }
.ruby-regexp { color: #ffa07a; background: transparent; }
.ruby-value { color: #7fffd4; background: transparent; }
}
#####################################################################
### H E A D E R T E M P L A T E
#####################################################################
XHTML_PREAMBLE = %{<?xml version="1.0" encoding="%charset%"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
}
HEADER = XHTML_PREAMBLE + %{
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>%title%</title>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<link rel="stylesheet" href="%style_url%" type="text/css" media="screen" />
<script type="text/javascript">
// <![CDATA[
function popupCode( url ) {
window.open(url, "Code", "resizable=yes,scrollbars=yes,toolbar=no,status=no,height=150,width=400")
}
function toggleCode( id ) {
if ( document.getElementById )
elem = document.getElementById( id );
else if ( document.all )
elem = eval( "document.all." + id );
else
return false;
elemStyle = elem.style;
if ( elemStyle.display != "block" ) {
elemStyle.display = "block"
} else {
elemStyle.display = "none"
}
return true;
}
// Make codeblocks hidden by default
document.writeln( "<style type=\\"text/css\\">div.method-source-code { display: none }</style>" )
// ]]>
</script>
</head>
<body>
}
#####################################################################
### C O N T E X T C O N T E N T T E M P L A T E
#####################################################################
CONTEXT_CONTENT = %{
}
#####################################################################
### F O O T E R T E M P L A T E
#####################################################################
FOOTER = %{
<div id="validator-badges">
<p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
</div>
</body>
</html>
}
#####################################################################
### F I L E P A G E H E A D E R T E M P L A T E
#####################################################################
FILE_PAGE = %{
<div id="fileHeader">
<h1>%short_name%</h1>
<table class="header-table">
<tr class="top-aligned-row">
<td><strong>Path:</strong></td>
<td>%full_path%
IF:cvsurl
(<a href="%cvsurl%"><acronym title="Concurrent Versioning System">CVS</acronym></a>)
ENDIF:cvsurl
</td>
</tr>
<tr class="top-aligned-row">
<td><strong>Last Update:</strong></td>
<td>%dtm_modified%</td>
</tr>
</table>
</div>
}
#####################################################################
### C L A S S P A G E H E A D E R T E M P L A T E
#####################################################################
CLASS_PAGE = %{
<div id="classHeader">
<table class="header-table">
<tr class="top-aligned-row">
<td><strong>%classmod%</strong></td>
<td class="class-name-in-header">%full_name%</td>
</tr>
<tr class="top-aligned-row">
<td><strong>In:</strong></td>
<td>
START:infiles
IF:full_path_url
<a href="%full_path_url%">
ENDIF:full_path_url
%full_path%
IF:full_path_url
</a>
ENDIF:full_path_url
IF:cvsurl
(<a href="%cvsurl%"><acronym title="Concurrent Versioning System">CVS</acronym></a>)
ENDIF:cvsurl
<br />
END:infiles
</td>
</tr>
IF:parent
<tr class="top-aligned-row">
<td><strong>Parent:</strong></td>
<td>
IF:par_url
<a href="%par_url%">
ENDIF:par_url
%parent%
IF:par_url
</a>
ENDIF:par_url
</td>
</tr>
ENDIF:parent
</table>
</div>
}
#####################################################################
### M E T H O D L I S T T E M P L A T E
#####################################################################
METHOD_LIST = %{
<div id="contextContent">
IF:diagram
<div id="diagram">
%diagram%
</div>
ENDIF:diagram
IF:description
<div id="description">
%description%
</div>
ENDIF:description
IF:requires
<div id="requires-list">
<h3 class="section-bar">Required files</h3>
<div class="name-list">
START:requires
HREF:aref:name:
END:requires
</div>
</div>
ENDIF:requires
IF:toc
<div id="contents-list">
<h3 class="section-bar">Contents</h3>
<ul>
START:toc
<li><a href="#%href%">%secname%</a></li>
END:toc
</ul>
ENDIF:toc
</div>
IF:methods
<div id="method-list">
<h3 class="section-bar">Methods</h3>
<div class="name-list">
START:methods
HREF:aref:name:
END:methods
</div>
</div>
ENDIF:methods
</div>
<!-- if includes -->
IF:includes
<div id="includes">
<h3 class="section-bar">Included Modules</h3>
<div id="includes-list">
START:includes
<span class="include-name">HREF:aref:name:</span>
END:includes
</div>
</div>
ENDIF:includes
START:sections
<div id="section">
IF:sectitle
<h2 class="section-title"><a name="%secsequence%">%sectitle%</a></h2>
IF:seccomment
<div class="section-comment">
%seccomment%
</div>
ENDIF:seccomment
ENDIF:sectitle
IF:classlist
<div id="class-list">
<h3 class="section-bar">Classes and Modules</h3>
%classlist%
</div>
ENDIF:classlist
IF:constants
<div id="constants-list">
<h3 class="section-bar">Constants</h3>
<div class="name-list">
<table summary="Constants">
START:constants
<tr class="top-aligned-row context-row">
<td class="context-item-name">%name%</td>
<td>=</td>
<td class="context-item-value">%value%</td>
IF:desc
<td width="3em"> </td>
<td class="context-item-desc">%desc%</td>
ENDIF:desc
</tr>
END:constants
</table>
</div>
</div>
ENDIF:constants
IF:aliases
<div id="aliases-list">
<h3 class="section-bar">External Aliases</h3>
<div class="name-list">
<table summary="aliases">
START:aliases
<tr class="top-aligned-row context-row">
<td class="context-item-name">%old_name%</td>
<td>-></td>
<td class="context-item-value">%new_name%</td>
</tr>
IF:desc
<tr class="top-aligned-row context-row">
<td> </td>
<td colspan="2" class="context-item-desc">%desc%</td>
</tr>
ENDIF:desc
END:aliases
</table>
</div>
</div>
ENDIF:aliases
IF:attributes
<div id="attribute-list">
<h3 class="section-bar">Attributes</h3>
<div class="name-list">
<table>
START:attributes
<tr class="top-aligned-row context-row">
<td class="context-item-name">%name%</td>
IF:rw
<td class="context-item-value"> [%rw%] </td>
ENDIF:rw
IFNOT:rw
<td class="context-item-value"> </td>
ENDIF:rw
<td class="context-item-desc">%a_desc%</td>
</tr>
END:attributes
</table>
</div>
</div>
ENDIF:attributes
<!-- if method_list -->
IF:method_list
<div id="methods">
START:method_list
IF:methods
<h3 class="section-bar">%type% %category% methods</h3>
START:methods
<div id="method-%aref%" class="method-detail">
<a name="%aref%"></a>
<div class="method-heading">
IF:codeurl
<a href="%codeurl%" target="Code" class="method-signature"
onclick="popupCode('%codeurl%');return false;">
ENDIF:codeurl
IF:sourcecode
<a href="#%aref%" class="method-signature">
ENDIF:sourcecode
IF:callseq
<span class="method-name">%callseq%</span>
ENDIF:callseq
IFNOT:callseq
<span class="method-name">%name%</span><span class="method-args">%params%</span>
ENDIF:callseq
IF:codeurl
</a>
ENDIF:codeurl
IF:sourcecode
</a>
ENDIF:sourcecode
</div>
<div class="method-description">
IF:m_desc
%m_desc%
ENDIF:m_desc
IF:sourcecode
<p><a class="source-toggle" href="#"
onclick="toggleCode('%aref%-source');return false;">[Source]</a></p>
<div class="method-source-code" id="%aref%-source">
<pre>
%sourcecode%
</pre>
</div>
ENDIF:sourcecode
</div>
</div>
END:methods
ENDIF:methods
END:method_list
</div>
ENDIF:method_list
END:sections
}
#####################################################################
### B O D Y T E M P L A T E
#####################################################################
BODY = HEADER + %{
!INCLUDE! <!-- banner header -->
<div id="bodyContent">
} + METHOD_LIST + %{
</div>
} + FOOTER
#####################################################################
### S O U R C E C O D E T E M P L A T E
#####################################################################
SRC_PAGE = XHTML_PREAMBLE + %{
<html>
<head>
<title>%title%</title>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
<link rel="stylesheet" href="%style_url%" type="text/css" media="screen" />
</head>
<body class="standalone-code">
<pre>%code%</pre>
</body>
</html>
}
#####################################################################
### I N D E X F I L E T E M P L A T E S
#####################################################################
FR_INDEX_BODY = %{
!INCLUDE!
}
FILE_INDEX = XHTML_PREAMBLE + %{
<!--
%list_title%
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>%list_title%</title>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
<link rel="stylesheet" href="%style_url%" type="text/css" />
<base target="docwin" />
</head>
<body>
<div id="index">
<h1 class="section-bar">%list_title%</h1>
<div id="index-entries">
START:entries
<a href="%href%">%name%</a><br />
END:entries
</div>
</div>
</body>
</html>
}
CLASS_INDEX = FILE_INDEX
METHOD_INDEX = FILE_INDEX
INDEX = %{<?xml version="1.0" encoding="%charset%"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<!--
%title%
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>%title%</title>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
</head>
<frameset rows="20%, 80%">
<frameset cols="25%,35%,45%">
<frame src="fr_file_index.html" title="Files" name="Files" />
<frame src="fr_class_index.html" name="Classes" />
<frame src="fr_method_index.html" name="Methods" />
</frameset>
<frame src="%initial_page%" name="docwin" />
</frameset>
</html>
}
end # module Page
end # class RDoc
require 'rdoc/generators/template/html/one_page_html'
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/parsers/parse_f95.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/parsers/parse_f95.rb | #= parse_f95.rb - Fortran95 Parser
#
#== Overview
#
#"parse_f95.rb" parses Fortran95 files with suffixes "f90", "F90", "f95"
#and "F95". Fortran95 files are expected to be conformed to Fortran95
#standards.
#
#== Rules
#
#Fundamental rules are same as that of the Ruby parser.
#But comment markers are '!' not '#'.
#
#=== Correspondence between RDoc documentation and Fortran95 programs
#
#"parse_f95.rb" parses main programs, modules, subroutines, functions,
#derived-types, public variables, public constants,
#defined operators and defined assignments.
#These components are described in items of RDoc documentation, as follows.
#
#Files :: Files (same as Ruby)
#Classes :: Modules
#Methods :: Subroutines, functions, variables, constants, derived-types, defined operators, defined assignments
#Required files :: Files in which imported modules, external subroutines and external functions are defined.
#Included Modules :: List of imported modules
#Attributes :: List of derived-types, List of imported modules all of whose components are published again
#
#Components listed in 'Methods' (subroutines, functions, ...)
#defined in modules are described in the item of 'Classes'.
#On the other hand, components defined in main programs or
#as external procedures are described in the item of 'Files'.
#
#=== Components parsed by default
#
#By default, documentation on public components (subroutines, functions,
#variables, constants, derived-types, defined operators,
#defined assignments) are generated.
#With "--all" option, documentation on all components
#are generated (almost same as the Ruby parser).
#
#=== Information parsed automatically
#
#The following information is automatically parsed.
#
#* Types of arguments
#* Types of variables and constants
#* Types of variables in the derived types, and initial values
#* NAMELISTs and types of variables in them, and initial values
#
#Aliases by interface statement are described in the item of 'Methods'.
#
#Components which are imported from other modules and published again
#are described in the item of 'Methods'.
#
#=== Format of comment blocks
#
#Comment blocks should be written as follows.
#Comment blocks are considered to be ended when the line without '!'
#appears.
#The indentation is not necessary.
#
# ! (Top of file)
# !
# ! Comment blocks for the files.
# !
# !--
# ! The comment described in the part enclosed by
# ! "!--" and "!++" is ignored.
# !++
# !
# module hogehoge
# !
# ! Comment blocks for the modules (or the programs).
# !
#
# private
#
# logical :: a ! a private variable
# real, public :: b ! a public variable
# integer, parameter :: c = 0 ! a public constant
#
# public :: c
# public :: MULTI_ARRAY
# public :: hoge, foo
#
# type MULTI_ARRAY
# !
# ! Comment blocks for the derived-types.
# !
# real, pointer :: var(:) =>null() ! Comments block for the variables.
# integer :: num = 0
# end type MULTI_ARRAY
#
# contains
#
# subroutine hoge( in, & ! Comment blocks between continuation lines are ignored.
# & out )
# !
# ! Comment blocks for the subroutines or functions
# !
# character(*),intent(in):: in ! Comment blocks for the arguments.
# character(*),intent(out),allocatable,target :: in
# ! Comment blocks can be
# ! written under Fortran statements.
#
# character(32) :: file ! This comment parsed as a variable in below NAMELIST.
# integer :: id
#
# namelist /varinfo_nml/ file, id
# !
# ! Comment blocks for the NAMELISTs.
# ! Information about variables are described above.
# !
#
# ....
#
# end subroutine hoge
#
# integer function foo( in )
# !
# ! This part is considered as comment block.
#
# ! Comment blocks under blank lines are ignored.
# !
# integer, intent(in):: inA ! This part is considered as comment block.
#
# ! This part is ignored.
#
# end function foo
#
# subroutine hide( in, &
# & out ) !:nodoc:
# !
# ! If "!:nodoc:" is described at end-of-line in subroutine
# ! statement as above, the subroutine is ignored.
# ! This assignment can be used to modules, subroutines,
# ! functions, variables, constants, derived-types,
# ! defined operators, defined assignments,
# ! list of imported modules ("use" statement).
# !
#
# ....
#
# end subroutine hide
#
# end module hogehoge
#
require "rdoc/code_objects"
module RDoc
class Token
NO_TEXT = "??".freeze
def initialize(line_no, char_no)
@line_no = line_no
@char_no = char_no
@text = NO_TEXT
end
# Because we're used in contexts that expect to return a token,
# we set the text string and then return ourselves
def set_text(text)
@text = text
self
end
attr_reader :line_no, :char_no, :text
end
# See rdoc/parsers/parse_f95.rb
class Fortran95parser
extend ParserFactory
parse_files_matching(/\.((f|F)9(0|5)|F)$/)
@@external_aliases = []
@@public_methods = []
# "false":: Comments are below source code
# "true" :: Comments are upper source code
COMMENTS_ARE_UPPER = false
# Internal alias message
INTERNAL_ALIAS_MES = "Alias for"
# External alias message
EXTERNAL_ALIAS_MES = "The entity is"
# prepare to parse a Fortran 95 file
def initialize(top_level, file_name, body, options, stats)
@body = body
@stats = stats
@file_name = file_name
@options = options
@top_level = top_level
@progress = $stderr unless options.quiet
end
# define code constructs
def scan
# remove private comment
remaining_code = remove_private_comments(@body)
# continuation lines are united to one line
remaining_code = united_to_one_line(remaining_code)
# semicolons are replaced to line feed
remaining_code = semicolon_to_linefeed(remaining_code)
# collect comment for file entity
whole_comment, remaining_code = collect_first_comment(remaining_code)
@top_level.comment = whole_comment
# String "remaining_code" is converted to Array "remaining_lines"
remaining_lines = remaining_code.split("\n")
# "module" or "program" parts are parsed (new)
#
level_depth = 0
block_searching_flag = nil
block_searching_lines = []
pre_comment = []
module_program_trailing = ""
module_program_name = ""
other_block_level_depth = 0
other_block_searching_flag = nil
remaining_lines.collect!{|line|
if !block_searching_flag && !other_block_searching_flag
if line =~ /^\s*?module\s+(\w+)\s*?(!.*?)?$/i
block_searching_flag = :module
block_searching_lines << line
module_program_name = $1
module_program_trailing = find_comments($2)
next false
elsif line =~ /^\s*?program\s+(\w+)\s*?(!.*?)?$/i ||
line =~ /^\s*?\w/ && !block_start?(line)
block_searching_flag = :program
block_searching_lines << line
module_program_name = $1 || ""
module_program_trailing = find_comments($2)
next false
elsif block_start?(line)
other_block_searching_flag = true
next line
elsif line =~ /^\s*?!\s?(.*)/
pre_comment << line
next line
else
pre_comment = []
next line
end
elsif other_block_searching_flag
other_block_level_depth += 1 if block_start?(line)
other_block_level_depth -= 1 if block_end?(line)
if other_block_level_depth < 0
other_block_level_depth = 0
other_block_searching_flag = nil
end
next line
end
block_searching_lines << line
level_depth += 1 if block_start?(line)
level_depth -= 1 if block_end?(line)
if level_depth >= 0
next false
end
# "module_program_code" is formatted.
# ":nodoc:" flag is checked.
#
module_program_code = block_searching_lines.join("\n")
module_program_code = remove_empty_head_lines(module_program_code)
if module_program_trailing =~ /^:nodoc:/
# next loop to search next block
level_depth = 0
block_searching_flag = false
block_searching_lines = []
pre_comment = []
next false
end
# NormalClass is created, and added to @top_level
#
if block_searching_flag == :module
module_name = module_program_name
module_code = module_program_code
module_trailing = module_program_trailing
progress "m"
@stats.num_modules += 1
f9x_module = @top_level.add_module NormalClass, module_name
f9x_module.record_location @top_level
f9x_comment = COMMENTS_ARE_UPPER ?
find_comments(pre_comment.join("\n")) + "\n" + module_trailing :
module_trailing + "\n" + find_comments(module_code.sub(/^.*$\n/i, ''))
f9x_module.comment = f9x_comment
parse_program_or_module(f9x_module, module_code)
TopLevel.all_files.each do |name, toplevel|
if toplevel.include_includes?(module_name, @options.ignore_case)
if !toplevel.include_requires?(@file_name, @options.ignore_case)
toplevel.add_require(Require.new(@file_name, ""))
end
end
toplevel.each_classmodule{|m|
if m.include_includes?(module_name, @options.ignore_case)
if !m.include_requires?(@file_name, @options.ignore_case)
m.add_require(Require.new(@file_name, ""))
end
end
}
end
elsif block_searching_flag == :program
program_name = module_program_name
program_code = module_program_code
program_trailing = module_program_trailing
progress "p"
program_comment = COMMENTS_ARE_UPPER ?
find_comments(pre_comment.join("\n")) + "\n" + program_trailing :
program_trailing + "\n" + find_comments(program_code.sub(/^.*$\n/i, ''))
program_comment = "\n\n= <i>Program</i> <tt>#{program_name}</tt>\n\n" \
+ program_comment
@top_level.comment << program_comment
parse_program_or_module(@top_level, program_code, :private)
end
# next loop to search next block
level_depth = 0
block_searching_flag = false
block_searching_lines = []
pre_comment = []
next false
}
remaining_lines.delete_if{ |line|
line == false
}
# External subprograms and functions are parsed
#
parse_program_or_module(@top_level, remaining_lines.join("\n"),
:public, true)
@top_level
end # End of scan
private
def parse_program_or_module(container, code,
visibility=:public, external=nil)
return unless container
return unless code
remaining_lines = code.split("\n")
remaining_code = "#{code}"
#
# Parse variables before "contains" in module
#
level_depth = 0
before_contains_lines = []
before_contains_code = nil
before_contains_flag = nil
remaining_lines.each{ |line|
if !before_contains_flag
if line =~ /^\s*?module\s+\w+\s*?(!.*?)?$/i
before_contains_flag = true
end
else
break if line =~ /^\s*?contains\s*?(!.*?)?$/i
level_depth += 1 if block_start?(line)
level_depth -= 1 if block_end?(line)
break if level_depth < 0
before_contains_lines << line
end
}
before_contains_code = before_contains_lines.join("\n")
if before_contains_code
before_contains_code.gsub!(/^\s*?interface\s+.*?\s+end\s+interface.*?$/im, "")
before_contains_code.gsub!(/^\s*?type[\s\,]+.*?\s+end\s+type.*?$/im, "")
end
#
# Parse global "use"
#
use_check_code = "#{before_contains_code}"
cascaded_modules_list = []
while use_check_code =~ /^\s*?use\s+(\w+)(.*?)(!.*?)?$/i
use_check_code = $~.pre_match
use_check_code << $~.post_match
used_mod_name = $1.strip.chomp
used_list = $2 || ""
used_trailing = $3 || ""
next if used_trailing =~ /!:nodoc:/
if !container.include_includes?(used_mod_name, @options.ignore_case)
progress "."
container.add_include Include.new(used_mod_name, "")
end
if ! (used_list =~ /\,\s*?only\s*?:/i )
cascaded_modules_list << "\#" + used_mod_name
end
end
#
# Parse public and private, and store information.
# This information is used when "add_method" and
# "set_visibility_for" are called.
#
visibility_default, visibility_info =
parse_visibility(remaining_lines.join("\n"), visibility, container)
@@public_methods.concat visibility_info
if visibility_default == :public
if !cascaded_modules_list.empty?
cascaded_modules =
Attr.new("Cascaded Modules",
"Imported modules all of whose components are published again",
"",
cascaded_modules_list.join(", "))
container.add_attribute(cascaded_modules)
end
end
#
# Check rename elements
#
use_check_code = "#{before_contains_code}"
while use_check_code =~ /^\s*?use\s+(\w+)\s*?\,(.+)$/i
use_check_code = $~.pre_match
use_check_code << $~.post_match
used_mod_name = $1.strip.chomp
used_elements = $2.sub(/\s*?only\s*?:\s*?/i, '')
used_elements.split(",").each{ |used|
if /\s*?(\w+)\s*?=>\s*?(\w+)\s*?/ =~ used
local = $1
org = $2
@@public_methods.collect!{ |pub_meth|
if local == pub_meth["name"] ||
local.upcase == pub_meth["name"].upcase &&
@options.ignore_case
pub_meth["name"] = org
pub_meth["local_name"] = local
end
pub_meth
}
end
}
end
#
# Parse private "use"
#
use_check_code = remaining_lines.join("\n")
while use_check_code =~ /^\s*?use\s+(\w+)(.*?)(!.*?)?$/i
use_check_code = $~.pre_match
use_check_code << $~.post_match
used_mod_name = $1.strip.chomp
used_trailing = $3 || ""
next if used_trailing =~ /!:nodoc:/
if !container.include_includes?(used_mod_name, @options.ignore_case)
progress "."
container.add_include Include.new(used_mod_name, "")
end
end
container.each_includes{ |inc|
TopLevel.all_files.each do |name, toplevel|
indicated_mod = toplevel.find_symbol(inc.name,
nil, @options.ignore_case)
if indicated_mod
indicated_name = indicated_mod.parent.file_relative_name
if !container.include_requires?(indicated_name, @options.ignore_case)
container.add_require(Require.new(indicated_name, ""))
end
break
end
end
}
#
# Parse derived-types definitions
#
derived_types_comment = ""
remaining_code = remaining_lines.join("\n")
while remaining_code =~ /^\s*?
type[\s\,]+(public|private)?\s*?(::)?\s*?
(\w+)\s*?(!.*?)?$
(.*?)
^\s*?end\s+type.*?$
/imx
remaining_code = $~.pre_match
remaining_code << $~.post_match
typename = $3.chomp.strip
type_elements = $5 || ""
type_code = remove_empty_head_lines($&)
type_trailing = find_comments($4)
next if type_trailing =~ /^:nodoc:/
type_visibility = $1
type_comment = COMMENTS_ARE_UPPER ?
find_comments($~.pre_match) + "\n" + type_trailing :
type_trailing + "\n" + find_comments(type_code.sub(/^.*$\n/i, ''))
type_element_visibility_public = true
type_code.split("\n").each{ |line|
if /^\s*?private\s*?$/ =~ line
type_element_visibility_public = nil
break
end
} if type_code
args_comment = ""
type_args_info = nil
if @options.show_all
args_comment = find_arguments(nil, type_code, true)
else
type_public_args_list = []
type_args_info = definition_info(type_code)
type_args_info.each{ |arg|
arg_is_public = type_element_visibility_public
arg_is_public = true if arg.include_attr?("public")
arg_is_public = nil if arg.include_attr?("private")
type_public_args_list << arg.varname if arg_is_public
}
args_comment = find_arguments(type_public_args_list, type_code)
end
type = AnyMethod.new("type #{typename}", typename)
type.singleton = false
type.params = ""
type.comment = "<b><em> Derived Type </em></b> :: <tt></tt>\n"
type.comment << args_comment if args_comment
type.comment << type_comment if type_comment
progress "t"
@stats.num_methods += 1
container.add_method type
set_visibility(container, typename, visibility_default, @@public_methods)
if type_visibility
type_visibility.gsub!(/\s/,'')
type_visibility.gsub!(/\,/,'')
type_visibility.gsub!(/:/,'')
type_visibility.downcase!
if type_visibility == "public"
container.set_visibility_for([typename], :public)
elsif type_visibility == "private"
container.set_visibility_for([typename], :private)
end
end
check_public_methods(type, container.name)
if @options.show_all
derived_types_comment << ", " unless derived_types_comment.empty?
derived_types_comment << typename
else
if type.visibility == :public
derived_types_comment << ", " unless derived_types_comment.empty?
derived_types_comment << typename
end
end
end
if !derived_types_comment.empty?
derived_types_table =
Attr.new("Derived Types", "Derived_Types", "",
derived_types_comment)
container.add_attribute(derived_types_table)
end
#
# move interface scope
#
interface_code = ""
while remaining_code =~ /^\s*?
interface(
\s+\w+ |
\s+operator\s*?\(.*?\) |
\s+assignment\s*?\(\s*?=\s*?\)
)?\s*?$
(.*?)
^\s*?end\s+interface.*?$
/imx
interface_code << remove_empty_head_lines($&) + "\n"
remaining_code = $~.pre_match
remaining_code << $~.post_match
end
#
# Parse global constants or variables in modules
#
const_var_defs = definition_info(before_contains_code)
const_var_defs.each{|defitem|
next if defitem.nodoc
const_or_var_type = "Variable"
const_or_var_progress = "v"
if defitem.include_attr?("parameter")
const_or_var_type = "Constant"
const_or_var_progress = "c"
end
const_or_var = AnyMethod.new(const_or_var_type, defitem.varname)
const_or_var.singleton = false
const_or_var.params = ""
self_comment = find_arguments([defitem.varname], before_contains_code)
const_or_var.comment = "<b><em>" + const_or_var_type + "</em></b> :: <tt></tt>\n"
const_or_var.comment << self_comment if self_comment
progress const_or_var_progress
@stats.num_methods += 1
container.add_method const_or_var
set_visibility(container, defitem.varname, visibility_default, @@public_methods)
if defitem.include_attr?("public")
container.set_visibility_for([defitem.varname], :public)
elsif defitem.include_attr?("private")
container.set_visibility_for([defitem.varname], :private)
end
check_public_methods(const_or_var, container.name)
} if const_var_defs
remaining_lines = remaining_code.split("\n")
# "subroutine" or "function" parts are parsed (new)
#
level_depth = 0
block_searching_flag = nil
block_searching_lines = []
pre_comment = []
procedure_trailing = ""
procedure_name = ""
procedure_params = ""
procedure_prefix = ""
procedure_result_arg = ""
procedure_type = ""
contains_lines = []
contains_flag = nil
remaining_lines.collect!{|line|
if !block_searching_flag
# subroutine
if line =~ /^\s*?
(recursive|pure|elemental)?\s*?
subroutine\s+(\w+)\s*?(\(.*?\))?\s*?(!.*?)?$
/ix
block_searching_flag = :subroutine
block_searching_lines << line
procedure_name = $2.chomp.strip
procedure_params = $3 || ""
procedure_prefix = $1 || ""
procedure_trailing = $4 || "!"
next false
# function
elsif line =~ /^\s*?
(recursive|pure|elemental)?\s*?
(
character\s*?(\([\w\s\=\(\)\*]+?\))?\s+
| type\s*?\([\w\s]+?\)\s+
| integer\s*?(\([\w\s\=\(\)\*]+?\))?\s+
| real\s*?(\([\w\s\=\(\)\*]+?\))?\s+
| double\s+precision\s+
| logical\s*?(\([\w\s\=\(\)\*]+?\))?\s+
| complex\s*?(\([\w\s\=\(\)\*]+?\))?\s+
)?
function\s+(\w+)\s*?
(\(.*?\))?(\s+result\((.*?)\))?\s*?(!.*?)?$
/ix
block_searching_flag = :function
block_searching_lines << line
procedure_prefix = $1 || ""
procedure_type = $2 ? $2.chomp.strip : nil
procedure_name = $8.chomp.strip
procedure_params = $9 || ""
procedure_result_arg = $11 ? $11.chomp.strip : procedure_name
procedure_trailing = $12 || "!"
next false
elsif line =~ /^\s*?!\s?(.*)/
pre_comment << line
next line
else
pre_comment = []
next line
end
end
contains_flag = true if line =~ /^\s*?contains\s*?(!.*?)?$/
block_searching_lines << line
contains_lines << line if contains_flag
level_depth += 1 if block_start?(line)
level_depth -= 1 if block_end?(line)
if level_depth >= 0
next false
end
# "procedure_code" is formatted.
# ":nodoc:" flag is checked.
#
procedure_code = block_searching_lines.join("\n")
procedure_code = remove_empty_head_lines(procedure_code)
if procedure_trailing =~ /^!:nodoc:/
# next loop to search next block
level_depth = 0
block_searching_flag = nil
block_searching_lines = []
pre_comment = []
procedure_trailing = ""
procedure_name = ""
procedure_params = ""
procedure_prefix = ""
procedure_result_arg = ""
procedure_type = ""
contains_lines = []
contains_flag = nil
next false
end
# AnyMethod is created, and added to container
#
subroutine_function = nil
if block_searching_flag == :subroutine
subroutine_prefix = procedure_prefix
subroutine_name = procedure_name
subroutine_params = procedure_params
subroutine_trailing = procedure_trailing
subroutine_code = procedure_code
subroutine_comment = COMMENTS_ARE_UPPER ?
pre_comment.join("\n") + "\n" + subroutine_trailing :
subroutine_trailing + "\n" + subroutine_code.sub(/^.*$\n/i, '')
subroutine = AnyMethod.new("subroutine", subroutine_name)
parse_subprogram(subroutine, subroutine_params,
subroutine_comment, subroutine_code,
before_contains_code, nil, subroutine_prefix)
progress "s"
@stats.num_methods += 1
container.add_method subroutine
subroutine_function = subroutine
elsif block_searching_flag == :function
function_prefix = procedure_prefix
function_type = procedure_type
function_name = procedure_name
function_params_org = procedure_params
function_result_arg = procedure_result_arg
function_trailing = procedure_trailing
function_code_org = procedure_code
function_comment = COMMENTS_ARE_UPPER ?
pre_comment.join("\n") + "\n" + function_trailing :
function_trailing + "\n " + function_code_org.sub(/^.*$\n/i, '')
function_code = "#{function_code_org}"
if function_type
function_code << "\n" + function_type + " :: " + function_result_arg
end
function_params =
function_params_org.sub(/^\(/, "\(#{function_result_arg}, ")
function = AnyMethod.new("function", function_name)
parse_subprogram(function, function_params,
function_comment, function_code,
before_contains_code, true, function_prefix)
# Specific modification due to function
function.params.sub!(/\(\s*?#{function_result_arg}\s*?,\s*?/, "\( ")
function.params << " result(" + function_result_arg + ")"
function.start_collecting_tokens
function.add_token Token.new(1,1).set_text(function_code_org)
progress "f"
@stats.num_methods += 1
container.add_method function
subroutine_function = function
end
# The visibility of procedure is specified
#
set_visibility(container, procedure_name,
visibility_default, @@public_methods)
# The alias for this procedure from external modules
#
check_external_aliases(procedure_name,
subroutine_function.params,
subroutine_function.comment, subroutine_function) if external
check_public_methods(subroutine_function, container.name)
# contains_lines are parsed as private procedures
if contains_flag
parse_program_or_module(container,
contains_lines.join("\n"), :private)
end
# next loop to search next block
level_depth = 0
block_searching_flag = nil
block_searching_lines = []
pre_comment = []
procedure_trailing = ""
procedure_name = ""
procedure_params = ""
procedure_prefix = ""
procedure_result_arg = ""
contains_lines = []
contains_flag = nil
next false
} # End of remaining_lines.collect!{|line|
# Array remains_lines is converted to String remains_code again
#
remaining_code = remaining_lines.join("\n")
#
# Parse interface
#
interface_scope = false
generic_name = ""
interface_code.split("\n").each{ |line|
if /^\s*?
interface(
\s+\w+|
\s+operator\s*?\(.*?\)|
\s+assignment\s*?\(\s*?=\s*?\)
)?
\s*?(!.*?)?$
/ix =~ line
generic_name = $1 ? $1.strip.chomp : nil
interface_trailing = $2 || "!"
interface_scope = true
interface_scope = false if interface_trailing =~ /!:nodoc:/
# if generic_name =~ /operator\s*?\((.*?)\)/i
# operator_name = $1
# if operator_name && !operator_name.empty?
# generic_name = "#{operator_name}"
# end
# end
# if generic_name =~ /assignment\s*?\((.*?)\)/i
# assignment_name = $1
# if assignment_name && !assignment_name.empty?
# generic_name = "#{assignment_name}"
# end
# end
end
if /^\s*?end\s+interface/i =~ line
interface_scope = false
generic_name = nil
end
# internal alias
if interface_scope && /^\s*?module\s+procedure\s+(.*?)(!.*?)?$/i =~ line
procedures = $1.strip.chomp
procedures_trailing = $2 || "!"
next if procedures_trailing =~ /!:nodoc:/
procedures.split(",").each{ |proc|
proc.strip!
proc.chomp!
next if generic_name == proc || !generic_name
old_meth = container.find_symbol(proc, nil, @options.ignore_case)
next if !old_meth
nolink = old_meth.visibility == :private ? true : nil
nolink = nil if @options.show_all
new_meth =
initialize_external_method(generic_name, proc,
old_meth.params, nil,
old_meth.comment,
old_meth.clone.token_stream[0].text,
true, nolink)
new_meth.singleton = old_meth.singleton
progress "i"
@stats.num_methods += 1
container.add_method new_meth
set_visibility(container, generic_name, visibility_default, @@public_methods)
check_public_methods(new_meth, container.name)
}
end
# external aliases
if interface_scope
# subroutine
proc = nil
params = nil
procedures_trailing = nil
if line =~ /^\s*?
(recursive|pure|elemental)?\s*?
subroutine\s+(\w+)\s*?(\(.*?\))?\s*?(!.*?)?$
/ix
proc = $2.chomp.strip
generic_name = proc unless generic_name
params = $3 || ""
procedures_trailing = $4 || "!"
# function
elsif line =~ /^\s*?
(recursive|pure|elemental)?\s*?
(
character\s*?(\([\w\s\=\(\)\*]+?\))?\s+
| type\s*?\([\w\s]+?\)\s+
| integer\s*?(\([\w\s\=\(\)\*]+?\))?\s+
| real\s*?(\([\w\s\=\(\)\*]+?\))?\s+
| double\s+precision\s+
| logical\s*?(\([\w\s\=\(\)\*]+?\))?\s+
| complex\s*?(\([\w\s\=\(\)\*]+?\))?\s+
)?
function\s+(\w+)\s*?
(\(.*?\))?(\s+result\((.*?)\))?\s*?(!.*?)?$
/ix
proc = $8.chomp.strip
generic_name = proc unless generic_name
params = $9 || ""
procedures_trailing = $12 || "!"
else
next
end
next if procedures_trailing =~ /!:nodoc:/
indicated_method = nil
indicated_file = nil
TopLevel.all_files.each do |name, toplevel|
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | true |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/parsers/parse_rb.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/parsers/parse_rb.rb | #!/usr/local/bin/ruby
# Parse a Ruby source file, building a set of objects
# representing the modules, classes, methods,
# requires, and includes we find (these classes
# are defined in code_objects.rb).
# This file contains stuff stolen outright from:
#
# rtags.rb -
# ruby-lex.rb - ruby lexcal analizer
# ruby-token.rb - ruby tokens
# by Keiju ISHITSUKA (Nippon Rational Inc.)
#
require "e2mmap"
require "irb/slex"
require "rdoc/code_objects"
require "rdoc/tokenstream"
require "rdoc/markup/simple_markup/preprocess"
require "rdoc/parsers/parserfactory"
$TOKEN_DEBUG = $DEBUG
# Definitions of all tokens involved in the lexical analysis
module RubyToken
EXPR_BEG = :EXPR_BEG
EXPR_MID = :EXPR_MID
EXPR_END = :EXPR_END
EXPR_ARG = :EXPR_ARG
EXPR_FNAME = :EXPR_FNAME
EXPR_DOT = :EXPR_DOT
EXPR_CLASS = :EXPR_CLASS
class Token
NO_TEXT = "??".freeze
attr :text
def initialize(line_no, char_no)
@line_no = line_no
@char_no = char_no
@text = NO_TEXT
end
# Because we're used in contexts that expect to return a token,
# we set the text string and then return ourselves
def set_text(text)
@text = text
self
end
attr_reader :line_no, :char_no, :text
end
class TkNode < Token
attr :node
end
class TkId < Token
def initialize(line_no, char_no, name)
super(line_no, char_no)
@name = name
end
attr :name
end
class TkKW < TkId
end
class TkVal < Token
def initialize(line_no, char_no, value = nil)
super(line_no, char_no)
set_text(value)
end
end
class TkOp < Token
def name
self.class.op_name
end
end
class TkOPASGN < TkOp
def initialize(line_no, char_no, op)
super(line_no, char_no)
op = TkReading2Token[op] unless op.kind_of?(Symbol)
@op = op
end
attr :op
end
class TkUnknownChar < Token
def initialize(line_no, char_no, id)
super(line_no, char_no)
@name = char_no.chr
end
attr :name
end
class TkError < Token
end
def set_token_position(line, char)
@prev_line_no = line
@prev_char_no = char
end
def Token(token, value = nil)
tk = nil
case token
when String, Symbol
source = token.kind_of?(String) ? TkReading2Token : TkSymbol2Token
if (tk = source[token]).nil?
IRB.fail TkReading2TokenNoKey, token
end
tk = Token(tk[0], value)
else
tk = if (token.ancestors & [TkId, TkVal, TkOPASGN, TkUnknownChar]).empty?
token.new(@prev_line_no, @prev_char_no)
else
token.new(@prev_line_no, @prev_char_no, value)
end
end
tk
end
TokenDefinitions = [
[:TkCLASS, TkKW, "class", EXPR_CLASS],
[:TkMODULE, TkKW, "module", EXPR_BEG],
[:TkDEF, TkKW, "def", EXPR_FNAME],
[:TkUNDEF, TkKW, "undef", EXPR_FNAME],
[:TkBEGIN, TkKW, "begin", EXPR_BEG],
[:TkRESCUE, TkKW, "rescue", EXPR_MID],
[:TkENSURE, TkKW, "ensure", EXPR_BEG],
[:TkEND, TkKW, "end", EXPR_END],
[:TkIF, TkKW, "if", EXPR_BEG, :TkIF_MOD],
[:TkUNLESS, TkKW, "unless", EXPR_BEG, :TkUNLESS_MOD],
[:TkTHEN, TkKW, "then", EXPR_BEG],
[:TkELSIF, TkKW, "elsif", EXPR_BEG],
[:TkELSE, TkKW, "else", EXPR_BEG],
[:TkCASE, TkKW, "case", EXPR_BEG],
[:TkWHEN, TkKW, "when", EXPR_BEG],
[:TkWHILE, TkKW, "while", EXPR_BEG, :TkWHILE_MOD],
[:TkUNTIL, TkKW, "until", EXPR_BEG, :TkUNTIL_MOD],
[:TkFOR, TkKW, "for", EXPR_BEG],
[:TkBREAK, TkKW, "break", EXPR_END],
[:TkNEXT, TkKW, "next", EXPR_END],
[:TkREDO, TkKW, "redo", EXPR_END],
[:TkRETRY, TkKW, "retry", EXPR_END],
[:TkIN, TkKW, "in", EXPR_BEG],
[:TkDO, TkKW, "do", EXPR_BEG],
[:TkRETURN, TkKW, "return", EXPR_MID],
[:TkYIELD, TkKW, "yield", EXPR_END],
[:TkSUPER, TkKW, "super", EXPR_END],
[:TkSELF, TkKW, "self", EXPR_END],
[:TkNIL, TkKW, "nil", EXPR_END],
[:TkTRUE, TkKW, "true", EXPR_END],
[:TkFALSE, TkKW, "false", EXPR_END],
[:TkAND, TkKW, "and", EXPR_BEG],
[:TkOR, TkKW, "or", EXPR_BEG],
[:TkNOT, TkKW, "not", EXPR_BEG],
[:TkIF_MOD, TkKW],
[:TkUNLESS_MOD, TkKW],
[:TkWHILE_MOD, TkKW],
[:TkUNTIL_MOD, TkKW],
[:TkALIAS, TkKW, "alias", EXPR_FNAME],
[:TkDEFINED, TkKW, "defined?", EXPR_END],
[:TklBEGIN, TkKW, "BEGIN", EXPR_END],
[:TklEND, TkKW, "END", EXPR_END],
[:Tk__LINE__, TkKW, "__LINE__", EXPR_END],
[:Tk__FILE__, TkKW, "__FILE__", EXPR_END],
[:TkIDENTIFIER, TkId],
[:TkFID, TkId],
[:TkGVAR, TkId],
[:TkIVAR, TkId],
[:TkCONSTANT, TkId],
[:TkINTEGER, TkVal],
[:TkFLOAT, TkVal],
[:TkSTRING, TkVal],
[:TkXSTRING, TkVal],
[:TkREGEXP, TkVal],
[:TkCOMMENT, TkVal],
[:TkDSTRING, TkNode],
[:TkDXSTRING, TkNode],
[:TkDREGEXP, TkNode],
[:TkNTH_REF, TkId],
[:TkBACK_REF, TkId],
[:TkUPLUS, TkOp, "+@"],
[:TkUMINUS, TkOp, "-@"],
[:TkPOW, TkOp, "**"],
[:TkCMP, TkOp, "<=>"],
[:TkEQ, TkOp, "=="],
[:TkEQQ, TkOp, "==="],
[:TkNEQ, TkOp, "!="],
[:TkGEQ, TkOp, ">="],
[:TkLEQ, TkOp, "<="],
[:TkANDOP, TkOp, "&&"],
[:TkOROP, TkOp, "||"],
[:TkMATCH, TkOp, "=~"],
[:TkNMATCH, TkOp, "!~"],
[:TkDOT2, TkOp, ".."],
[:TkDOT3, TkOp, "..."],
[:TkAREF, TkOp, "[]"],
[:TkASET, TkOp, "[]="],
[:TkLSHFT, TkOp, "<<"],
[:TkRSHFT, TkOp, ">>"],
[:TkCOLON2, TkOp],
[:TkCOLON3, TkOp],
# [:OPASGN, TkOp], # +=, -= etc. #
[:TkASSOC, TkOp, "=>"],
[:TkQUESTION, TkOp, "?"], #?
[:TkCOLON, TkOp, ":"], #:
[:TkfLPAREN], # func( #
[:TkfLBRACK], # func[ #
[:TkfLBRACE], # func{ #
[:TkSTAR], # *arg
[:TkAMPER], # &arg #
[:TkSYMBOL, TkId], # :SYMBOL
[:TkSYMBEG, TkId],
[:TkGT, TkOp, ">"],
[:TkLT, TkOp, "<"],
[:TkPLUS, TkOp, "+"],
[:TkMINUS, TkOp, "-"],
[:TkMULT, TkOp, "*"],
[:TkDIV, TkOp, "/"],
[:TkMOD, TkOp, "%"],
[:TkBITOR, TkOp, "|"],
[:TkBITXOR, TkOp, "^"],
[:TkBITAND, TkOp, "&"],
[:TkBITNOT, TkOp, "~"],
[:TkNOTOP, TkOp, "!"],
[:TkBACKQUOTE, TkOp, "`"],
[:TkASSIGN, Token, "="],
[:TkDOT, Token, "."],
[:TkLPAREN, Token, "("], #(exp)
[:TkLBRACK, Token, "["], #[arry]
[:TkLBRACE, Token, "{"], #{hash}
[:TkRPAREN, Token, ")"],
[:TkRBRACK, Token, "]"],
[:TkRBRACE, Token, "}"],
[:TkCOMMA, Token, ","],
[:TkSEMICOLON, Token, ";"],
[:TkRD_COMMENT],
[:TkSPACE],
[:TkNL],
[:TkEND_OF_SCRIPT],
[:TkBACKSLASH, TkUnknownChar, "\\"],
[:TkAT, TkUnknownChar, "@"],
[:TkDOLLAR, TkUnknownChar, "\$"], #"
]
# {reading => token_class}
# {reading => [token_class, *opt]}
TkReading2Token = {}
TkSymbol2Token = {}
def RubyToken.def_token(token_n, super_token = Token, reading = nil, *opts)
token_n = token_n.id2name unless token_n.kind_of?(String)
if RubyToken.const_defined?(token_n)
IRB.fail AlreadyDefinedToken, token_n
end
token_c = Class.new super_token
RubyToken.const_set token_n, token_c
# token_c.inspect
if reading
if TkReading2Token[reading]
IRB.fail TkReading2TokenDuplicateError, token_n, reading
end
if opts.empty?
TkReading2Token[reading] = [token_c]
else
TkReading2Token[reading] = [token_c].concat(opts)
end
end
TkSymbol2Token[token_n.intern] = token_c
if token_c <= TkOp
token_c.class_eval %{
def self.op_name; "#{reading}"; end
}
end
end
for defs in TokenDefinitions
def_token(*defs)
end
NEWLINE_TOKEN = TkNL.new(0,0)
NEWLINE_TOKEN.set_text("\n")
end
# Lexical analyzer for Ruby source
class RubyLex
######################################################################
#
# Read an input stream character by character. We allow for unlimited
# ungetting of characters just read.
#
# We simplify the implementation greatly by reading the entire input
# into a buffer initially, and then simply traversing it using
# pointers.
#
# We also have to allow for the <i>here document diversion</i>. This
# little gem comes about when the lexer encounters a here
# document. At this point we effectively need to split the input
# stream into two parts: one to read the body of the here document,
# the other to read the rest of the input line where the here
# document was initially encountered. For example, we might have
#
# do_something(<<-A, <<-B)
# stuff
# for
# A
# stuff
# for
# B
#
# When the lexer encounters the <<A, it reads until the end of the
# line, and keeps it around for later. It then reads the body of the
# here document. Once complete, it needs to read the rest of the
# original line, but then skip the here document body.
#
class BufferedReader
attr_reader :line_num
def initialize(content)
if /\t/ =~ content
tab_width = Options.instance.tab_width
content = content.split(/\n/).map do |line|
1 while line.gsub!(/\t+/) { ' ' * (tab_width*$&.length - $`.length % tab_width)} && $~ #`
line
end .join("\n")
end
@content = content
@content << "\n" unless @content[-1,1] == "\n"
@size = @content.size
@offset = 0
@hwm = 0
@line_num = 1
@read_back_offset = 0
@last_newline = 0
@newline_pending = false
end
def column
@offset - @last_newline
end
def getc
return nil if @offset >= @size
ch = @content[@offset, 1]
@offset += 1
@hwm = @offset if @hwm < @offset
if @newline_pending
@line_num += 1
@last_newline = @offset - 1
@newline_pending = false
end
if ch == "\n"
@newline_pending = true
end
ch
end
def getc_already_read
getc
end
def ungetc(ch)
raise "unget past beginning of file" if @offset <= 0
@offset -= 1
if @content[@offset] == ?\n
@newline_pending = false
end
end
def get_read
res = @content[@read_back_offset...@offset]
@read_back_offset = @offset
res
end
def peek(at)
pos = @offset + at
if pos >= @size
nil
else
@content[pos, 1]
end
end
def peek_equal(str)
@content[@offset, str.length] == str
end
def divert_read_from(reserve)
@content[@offset, 0] = reserve
@size = @content.size
end
end
# end of nested class BufferedReader
extend Exception2MessageMapper
def_exception(:AlreadyDefinedToken, "Already defined token(%s)")
def_exception(:TkReading2TokenNoKey, "key nothing(key='%s')")
def_exception(:TkSymbol2TokenNoKey, "key nothing(key='%s')")
def_exception(:TkReading2TokenDuplicateError,
"key duplicate(token_n='%s', key='%s')")
def_exception(:SyntaxError, "%s")
include RubyToken
include IRB
attr_reader :continue
attr_reader :lex_state
def RubyLex.debug?
false
end
def initialize(content)
lex_init
@reader = BufferedReader.new(content)
@exp_line_no = @line_no = 1
@base_char_no = 0
@indent = 0
@ltype = nil
@quoted = nil
@lex_state = EXPR_BEG
@space_seen = false
@continue = false
@line = ""
@skip_space = false
@read_auto_clean_up = false
@exception_on_syntax_error = true
end
attr :skip_space, true
attr :read_auto_clean_up, true
attr :exception_on_syntax_error, true
attr :indent
# io functions
def line_no
@reader.line_num
end
def char_no
@reader.column
end
def get_read
@reader.get_read
end
def getc
@reader.getc
end
def getc_of_rests
@reader.getc_already_read
end
def gets
c = getc or return
l = ""
begin
l.concat c unless c == "\r"
break if c == "\n"
end while c = getc
l
end
def ungetc(c = nil)
@reader.ungetc(c)
end
def peek_equal?(str)
@reader.peek_equal(str)
end
def peek(i = 0)
@reader.peek(i)
end
def lex
until (((tk = token).kind_of?(TkNL) || tk.kind_of?(TkEND_OF_SCRIPT)) &&
!@continue or
tk.nil?)
end
line = get_read
if line == "" and tk.kind_of?(TkEND_OF_SCRIPT) || tk.nil?
nil
else
line
end
end
def token
set_token_position(line_no, char_no)
begin
begin
tk = @OP.match(self)
@space_seen = tk.kind_of?(TkSPACE)
rescue SyntaxError
abort if @exception_on_syntax_error
tk = TkError.new(line_no, char_no)
end
end while @skip_space and tk.kind_of?(TkSPACE)
if @read_auto_clean_up
get_read
end
# throw :eof unless tk
p tk if $DEBUG
tk
end
ENINDENT_CLAUSE = [
"case", "class", "def", "do", "for", "if",
"module", "unless", "until", "while", "begin" #, "when"
]
DEINDENT_CLAUSE = ["end" #, "when"
]
PERCENT_LTYPE = {
"q" => "\'",
"Q" => "\"",
"x" => "\`",
"r" => "/",
"w" => "]"
}
PERCENT_PAREN = {
"{" => "}",
"[" => "]",
"<" => ">",
"(" => ")"
}
Ltype2Token = {
"\'" => TkSTRING,
"\"" => TkSTRING,
"\`" => TkXSTRING,
"/" => TkREGEXP,
"]" => TkDSTRING
}
Ltype2Token.default = TkSTRING
DLtype2Token = {
"\"" => TkDSTRING,
"\`" => TkDXSTRING,
"/" => TkDREGEXP,
}
def lex_init()
@OP = SLex.new
@OP.def_rules("\0", "\004", "\032") do |chars, io|
Token(TkEND_OF_SCRIPT).set_text(chars)
end
@OP.def_rules(" ", "\t", "\f", "\r", "\13") do |chars, io|
@space_seen = TRUE
while (ch = getc) =~ /[ \t\f\r\13]/
chars << ch
end
ungetc
Token(TkSPACE).set_text(chars)
end
@OP.def_rule("#") do
|op, io|
identify_comment
end
@OP.def_rule("=begin", proc{@prev_char_no == 0 && peek(0) =~ /\s/}) do
|op, io|
str = op
@ltype = "="
begin
line = ""
begin
ch = getc
line << ch
end until ch == "\n"
str << line
end until line =~ /^=end/
ungetc
@ltype = nil
if str =~ /\A=begin\s+rdoc/i
str.sub!(/\A=begin.*\n/, '')
str.sub!(/^=end.*/m, '')
Token(TkCOMMENT).set_text(str)
else
Token(TkRD_COMMENT)#.set_text(str)
end
end
@OP.def_rule("\n") do
print "\\n\n" if RubyLex.debug?
case @lex_state
when EXPR_BEG, EXPR_FNAME, EXPR_DOT
@continue = TRUE
else
@continue = FALSE
@lex_state = EXPR_BEG
end
Token(TkNL).set_text("\n")
end
@OP.def_rules("*", "**",
"!", "!=", "!~",
"=", "==", "===",
"=~", "<=>",
"<", "<=",
">", ">=", ">>") do
|op, io|
@lex_state = EXPR_BEG
Token(op).set_text(op)
end
@OP.def_rules("<<") do
|op, io|
tk = nil
if @lex_state != EXPR_END && @lex_state != EXPR_CLASS &&
(@lex_state != EXPR_ARG || @space_seen)
c = peek(0)
if /[-\w_\"\'\`]/ =~ c
tk = identify_here_document
end
end
if !tk
@lex_state = EXPR_BEG
tk = Token(op).set_text(op)
end
tk
end
@OP.def_rules("'", '"') do
|op, io|
identify_string(op)
end
@OP.def_rules("`") do
|op, io|
if @lex_state == EXPR_FNAME
Token(op).set_text(op)
else
identify_string(op)
end
end
@OP.def_rules('?') do
|op, io|
if @lex_state == EXPR_END
@lex_state = EXPR_BEG
Token(TkQUESTION).set_text(op)
else
ch = getc
if @lex_state == EXPR_ARG && ch !~ /\s/
ungetc
@lex_state = EXPR_BEG;
Token(TkQUESTION).set_text(op)
else
str = op
str << ch
if (ch == '\\') #'
str << read_escape
end
@lex_state = EXPR_END
Token(TkINTEGER).set_text(str)
end
end
end
@OP.def_rules("&", "&&", "|", "||") do
|op, io|
@lex_state = EXPR_BEG
Token(op).set_text(op)
end
@OP.def_rules("+=", "-=", "*=", "**=",
"&=", "|=", "^=", "<<=", ">>=", "||=", "&&=") do
|op, io|
@lex_state = EXPR_BEG
op =~ /^(.*)=$/
Token(TkOPASGN, $1).set_text(op)
end
@OP.def_rule("+@", proc{@lex_state == EXPR_FNAME}) do |op, io|
Token(TkUPLUS).set_text(op)
end
@OP.def_rule("-@", proc{@lex_state == EXPR_FNAME}) do |op, io|
Token(TkUMINUS).set_text(op)
end
@OP.def_rules("+", "-") do
|op, io|
catch(:RET) do
if @lex_state == EXPR_ARG
if @space_seen and peek(0) =~ /[0-9]/
throw :RET, identify_number(op)
else
@lex_state = EXPR_BEG
end
elsif @lex_state != EXPR_END and peek(0) =~ /[0-9]/
throw :RET, identify_number(op)
else
@lex_state = EXPR_BEG
end
Token(op).set_text(op)
end
end
@OP.def_rule(".") do
@lex_state = EXPR_BEG
if peek(0) =~ /[0-9]/
ungetc
identify_number("")
else
# for obj.if
@lex_state = EXPR_DOT
Token(TkDOT).set_text(".")
end
end
@OP.def_rules("..", "...") do
|op, io|
@lex_state = EXPR_BEG
Token(op).set_text(op)
end
lex_int2
end
def lex_int2
@OP.def_rules("]", "}", ")") do
|op, io|
@lex_state = EXPR_END
@indent -= 1
Token(op).set_text(op)
end
@OP.def_rule(":") do
if @lex_state == EXPR_END || peek(0) =~ /\s/
@lex_state = EXPR_BEG
tk = Token(TkCOLON)
else
@lex_state = EXPR_FNAME;
tk = Token(TkSYMBEG)
end
tk.set_text(":")
end
@OP.def_rule("::") do
# p @lex_state.id2name, @space_seen
if @lex_state == EXPR_BEG or @lex_state == EXPR_ARG && @space_seen
@lex_state = EXPR_BEG
tk = Token(TkCOLON3)
else
@lex_state = EXPR_DOT
tk = Token(TkCOLON2)
end
tk.set_text("::")
end
@OP.def_rule("/") do
|op, io|
if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
identify_string(op)
elsif peek(0) == '='
getc
@lex_state = EXPR_BEG
Token(TkOPASGN, :/).set_text("/=") #")
elsif @lex_state == EXPR_ARG and @space_seen and peek(0) !~ /\s/
identify_string(op)
else
@lex_state = EXPR_BEG
Token("/").set_text(op)
end
end
@OP.def_rules("^") do
@lex_state = EXPR_BEG
Token("^").set_text("^")
end
# @OP.def_rules("^=") do
# @lex_state = EXPR_BEG
# Token(TkOPASGN, :^)
# end
@OP.def_rules(",", ";") do
|op, io|
@lex_state = EXPR_BEG
Token(op).set_text(op)
end
@OP.def_rule("~") do
@lex_state = EXPR_BEG
Token("~").set_text("~")
end
@OP.def_rule("~@", proc{@lex_state = EXPR_FNAME}) do
@lex_state = EXPR_BEG
Token("~").set_text("~@")
end
@OP.def_rule("(") do
@indent += 1
if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
@lex_state = EXPR_BEG
tk = Token(TkfLPAREN)
else
@lex_state = EXPR_BEG
tk = Token(TkLPAREN)
end
tk.set_text("(")
end
@OP.def_rule("[]", proc{@lex_state == EXPR_FNAME}) do
Token("[]").set_text("[]")
end
@OP.def_rule("[]=", proc{@lex_state == EXPR_FNAME}) do
Token("[]=").set_text("[]=")
end
@OP.def_rule("[") do
@indent += 1
if @lex_state == EXPR_FNAME
t = Token(TkfLBRACK)
else
if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
t = Token(TkLBRACK)
elsif @lex_state == EXPR_ARG && @space_seen
t = Token(TkLBRACK)
else
t = Token(TkfLBRACK)
end
@lex_state = EXPR_BEG
end
t.set_text("[")
end
@OP.def_rule("{") do
@indent += 1
if @lex_state != EXPR_END && @lex_state != EXPR_ARG
t = Token(TkLBRACE)
else
t = Token(TkfLBRACE)
end
@lex_state = EXPR_BEG
t.set_text("{")
end
@OP.def_rule('\\') do #'
if getc == "\n"
@space_seen = true
@continue = true
Token(TkSPACE).set_text("\\\n")
else
ungetc
Token("\\").set_text("\\") #"
end
end
@OP.def_rule('%') do
|op, io|
if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
identify_quotation('%')
elsif peek(0) == '='
getc
Token(TkOPASGN, "%").set_text("%=")
elsif @lex_state == EXPR_ARG and @space_seen and peek(0) !~ /\s/
identify_quotation('%')
else
@lex_state = EXPR_BEG
Token("%").set_text("%")
end
end
@OP.def_rule('$') do #'
identify_gvar
end
@OP.def_rule('@') do
if peek(0) =~ /[@\w_]/
ungetc
identify_identifier
else
Token("@").set_text("@")
end
end
# @OP.def_rule("def", proc{|op, io| /\s/ =~ io.peek(0)}) do
# |op, io|
# @indent += 1
# @lex_state = EXPR_FNAME
# # @lex_state = EXPR_END
# # until @rests[0] == "\n" or @rests[0] == ";"
# # rests.shift
# # end
# end
@OP.def_rule("__END__", proc{@prev_char_no == 0 && peek(0) =~ /[\r\n]/}) do
throw :eof
end
@OP.def_rule("") do
|op, io|
printf "MATCH: start %s: %s\n", op, io.inspect if RubyLex.debug?
if peek(0) =~ /[0-9]/
t = identify_number("")
elsif peek(0) =~ /[\w_]/
t = identify_identifier
end
printf "MATCH: end %s: %s\n", op, io.inspect if RubyLex.debug?
t
end
p @OP if RubyLex.debug?
end
def identify_gvar
@lex_state = EXPR_END
str = "$"
tk = case ch = getc
when /[~_*$?!@\/\\;,=:<>".]/ #"
str << ch
Token(TkGVAR, str)
when "-"
str << "-" << getc
Token(TkGVAR, str)
when "&", "`", "'", "+"
str << ch
Token(TkBACK_REF, str)
when /[1-9]/
str << ch
while (ch = getc) =~ /[0-9]/
str << ch
end
ungetc
Token(TkNTH_REF)
when /\w/
ungetc
ungetc
return identify_identifier
else
ungetc
Token("$")
end
tk.set_text(str)
end
def identify_identifier
token = ""
token.concat getc if peek(0) =~ /[$@]/
token.concat getc if peek(0) == "@"
while (ch = getc) =~ /\w|_/
print ":", ch, ":" if RubyLex.debug?
token.concat ch
end
ungetc
if ch == "!" or ch == "?"
token.concat getc
end
# fix token
# $stderr.puts "identifier - #{token}, state = #@lex_state"
case token
when /^\$/
return Token(TkGVAR, token).set_text(token)
when /^\@/
@lex_state = EXPR_END
return Token(TkIVAR, token).set_text(token)
end
if @lex_state != EXPR_DOT
print token, "\n" if RubyLex.debug?
token_c, *trans = TkReading2Token[token]
if token_c
# reserved word?
if (@lex_state != EXPR_BEG &&
@lex_state != EXPR_FNAME &&
trans[1])
# modifiers
token_c = TkSymbol2Token[trans[1]]
@lex_state = trans[0]
else
if @lex_state != EXPR_FNAME
if ENINDENT_CLAUSE.include?(token)
@indent += 1
elsif DEINDENT_CLAUSE.include?(token)
@indent -= 1
end
@lex_state = trans[0]
else
@lex_state = EXPR_END
end
end
return Token(token_c, token).set_text(token)
end
end
if @lex_state == EXPR_FNAME
@lex_state = EXPR_END
if peek(0) == '='
token.concat getc
end
elsif @lex_state == EXPR_BEG || @lex_state == EXPR_DOT
@lex_state = EXPR_ARG
else
@lex_state = EXPR_END
end
if token[0, 1] =~ /[A-Z]/
return Token(TkCONSTANT, token).set_text(token)
elsif token[token.size - 1, 1] =~ /[!?]/
return Token(TkFID, token).set_text(token)
else
return Token(TkIDENTIFIER, token).set_text(token)
end
end
def identify_here_document
ch = getc
if ch == "-"
ch = getc
indent = true
end
if /['"`]/ =~ ch # '
lt = ch
quoted = ""
while (c = getc) && c != lt
quoted.concat c
end
else
lt = '"'
quoted = ch.dup
while (c = getc) && c =~ /\w/
quoted.concat c
end
ungetc
end
ltback, @ltype = @ltype, lt
reserve = ""
while ch = getc
reserve << ch
if ch == "\\" #"
ch = getc
reserve << ch
elsif ch == "\n"
break
end
end
str = ""
while (l = gets)
l.chomp!
l.strip! if indent
break if l == quoted
str << l.chomp << "\n"
end
@reader.divert_read_from(reserve)
@ltype = ltback
@lex_state = EXPR_END
Token(Ltype2Token[lt], str).set_text(str.dump)
end
def identify_quotation(initial_char)
ch = getc
if lt = PERCENT_LTYPE[ch]
initial_char += ch
ch = getc
elsif ch =~ /\W/
lt = "\""
else
RubyLex.fail SyntaxError, "unknown type of %string ('#{ch}')"
end
# if ch !~ /\W/
# ungetc
# next
# end
#@ltype = lt
@quoted = ch unless @quoted = PERCENT_PAREN[ch]
identify_string(lt, @quoted, ch, initial_char)
end
def identify_number(start)
str = start.dup
if start == "+" or start == "-" or start == ""
start = getc
str << start
end
@lex_state = EXPR_END
if start == "0"
if peek(0) == "x"
ch = getc
str << ch
match = /[0-9a-f_]/
else
match = /[0-7_]/
end
while ch = getc
if ch !~ match
ungetc
break
else
str << ch
end
end
return Token(TkINTEGER).set_text(str)
end
type = TkINTEGER
allow_point = TRUE
allow_e = TRUE
while ch = getc
case ch
when /[0-9_]/
str << ch
when allow_point && "."
type = TkFLOAT
if peek(0) !~ /[0-9]/
ungetc
break
end
str << ch
allow_point = false
when allow_e && "e", allow_e && "E"
str << ch
type = TkFLOAT
if peek(0) =~ /[+-]/
str << getc
end
allow_e = false
allow_point = false
else
ungetc
break
end
end
Token(type).set_text(str)
end
def identify_string(ltype, quoted = ltype, opener=nil, initial_char = nil)
@ltype = ltype
@quoted = quoted
subtype = nil
str = ""
str << initial_char if initial_char
str << (opener||quoted)
nest = 0
begin
while ch = getc
str << ch
if @quoted == ch
if nest == 0
break
else
nest -= 1
end
elsif opener == ch
nest += 1
elsif @ltype != "'" && @ltype != "]" and ch == "#"
ch = getc
if ch == "{"
subtype = true
str << ch << skip_inner_expression
else
ungetc(ch)
end
elsif ch == '\\' #'
str << read_escape
end
end
if @ltype == "/"
if peek(0) =~ /i|o|n|e|s/
str << getc
end
end
if subtype
Token(DLtype2Token[ltype], str)
else
Token(Ltype2Token[ltype], str)
end.set_text(str)
ensure
@ltype = nil
@quoted = nil
@lex_state = EXPR_END
end
end
def skip_inner_expression
res = ""
nest = 0
while (ch = getc)
res << ch
if ch == '}'
break if nest.zero?
nest -= 1
elsif ch == '{'
nest += 1
end
end
res
end
def identify_comment
@ltype = "#"
comment = "#"
while ch = getc
if ch == "\\"
ch = getc
if ch == "\n"
ch = " "
else
comment << "\\"
end
else
if ch == "\n"
@ltype = nil
ungetc
break
end
end
comment << ch
end
return Token(TkCOMMENT).set_text(comment)
end
def read_escape
res = ""
case ch = getc
when /[0-7]/
ungetc ch
3.times do
case ch = getc
when /[0-7]/
when nil
break
else
ungetc
break
end
res << ch
end
when "x"
res << ch
2.times do
case ch = getc
when /[0-9a-fA-F]/
when nil
break
else
ungetc
break
end
res << ch
end
when "M"
res << ch
if (ch = getc) != '-'
ungetc
else
res << ch
if (ch = getc) == "\\" #"
res << ch
res << read_escape
else
res << ch
end
end
when "C", "c" #, "^"
res << ch
if ch == "C" and (ch = getc) != "-"
ungetc
else
res << ch
if (ch = getc) == "\\" #"
res << ch
res << read_escape
else
res << ch
end
end
else
res << ch
end
res
end
end
# Extract code elements from a source file, returning a TopLevel
# object containing the constituent file elements.
#
# This file is based on rtags
module RDoc
GENERAL_MODIFIERS = [ 'nodoc' ].freeze
CLASS_MODIFIERS = GENERAL_MODIFIERS
ATTR_MODIFIERS = GENERAL_MODIFIERS
CONSTANT_MODIFIERS = GENERAL_MODIFIERS
METHOD_MODIFIERS = GENERAL_MODIFIERS +
[ 'arg', 'args', 'yield', 'yields', 'notnew', 'not-new', 'not_new', 'doc' ]
class RubyParser
include RubyToken
include TokenStream
extend ParserFactory
parse_files_matching(/\.rbw?$/)
def initialize(top_level, file_name, content, options, stats)
@options = options
@stats = stats
@size = 0
@token_listeners = nil
@input_file_name = file_name
@scanner = RubyLex.new(content)
@scanner.exception_on_syntax_error = false
@top_level = top_level
@progress = $stderr unless options.quiet
end
def scan
@tokens = []
@unget_read = []
@read = []
catch(:eof) do
catch(:enddoc) do
begin
parse_toplevel_statements(@top_level)
rescue Exception => e
$stderr.puts "\n\n"
$stderr.puts "RDoc failure in #@input_file_name at or around " +
"line #{@scanner.line_no} column #{@scanner.char_no}"
$stderr.puts
$stderr.puts "Before reporting this, could you check that the file"
$stderr.puts "you're documenting compiles cleanly--RDoc is not a"
$stderr.puts "full Ruby parser, and gets confused easily if fed"
$stderr.puts "invalid programs."
$stderr.puts
$stderr.puts "The internal error was:\n\n"
e.set_backtrace(e.backtrace[0,4])
raise
end
end
end
@top_level
end
private
def make_message(msg)
prefix = "\n" + @input_file_name + ":"
if @scanner
prefix << "#{@scanner.line_no}:#{@scanner.char_no}: "
end
return prefix + msg
end
def warn(msg)
return if @options.quiet
msg = make_message msg
$stderr.puts msg
end
def error(msg)
msg = make_message msg
$stderr.puts msg
exit(1)
end
def progress(char)
unless @options.quiet
@progress.print(char)
@progress.flush
end
end
def add_token_listener(obj)
@token_listeners ||= []
@token_listeners << obj
end
def remove_token_listener(obj)
@token_listeners.delete(obj)
end
def get_tk
tk = nil
if @tokens.empty?
tk = @scanner.token
@read.push @scanner.get_read
puts "get_tk1 => #{tk.inspect}" if $TOKEN_DEBUG
else
@read.push @unget_read.shift
tk = @tokens.shift
puts "get_tk2 => #{tk.inspect}" if $TOKEN_DEBUG
end
if tk.kind_of?(TkSYMBEG)
set_token_position(tk.line_no, tk.char_no)
tk1 = get_tk
if tk1.kind_of?(TkId) || tk1.kind_of?(TkOp)
tk = Token(TkSYMBOL).set_text(":" + tk1.name)
# remove the identifier we just read (we're about to
# replace it with a symbol)
@token_listeners.each do |obj|
obj.pop_token
end if @token_listeners
else
warn("':' not followed by identifier or operator")
tk = tk1
end
end
# inform any listeners of our shiny new token
@token_listeners.each do |obj|
obj.add_token(tk)
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | true |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/parsers/parserfactory.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/parsers/parserfactory.rb | require "rdoc/parsers/parse_simple"
module RDoc
# A parser is simple a class that implements
#
# #initialize(file_name, body, options)
#
# and
#
# #scan
#
# The initialize method takes a file name to be used, the body of the
# file, and an RDoc::Options object. The scan method is then called
# to return an appropriately parsed TopLevel code object.
#
# The ParseFactory is used to redirect to the correct parser given a filename
# extension. This magic works because individual parsers have to register
# themselves with us as they are loaded in. The do this using the following
# incantation
#
#
# require "rdoc/parsers/parsefactory"
#
# module RDoc
#
# class XyzParser
# extend ParseFactory <<<<
# parse_files_matching /\.xyz$/ <<<<
#
# def initialize(file_name, body, options)
# ...
# end
#
# def scan
# ...
# end
# end
# end
#
# Just to make life interesting, if we suspect a plain text file, we
# also look for a shebang line just in case it's a potential
# shell script
module ParserFactory
@@parsers = []
Parsers = Struct.new(:regexp, :parser)
# Record the fact that a particular class parses files that
# match a given extension
def parse_files_matching(regexp)
@@parsers.unshift Parsers.new(regexp, self)
end
# Return a parser that can handle a particular extension
def ParserFactory.can_parse(file_name)
@@parsers.find {|p| p.regexp.match(file_name) }
end
# Alias an extension to another extension. After this call,
# files ending "new_ext" will be parsed using the same parser
# as "old_ext"
def ParserFactory.alias_extension(old_ext, new_ext)
parser = ParserFactory.can_parse("xxx.#{old_ext}")
return false unless parser
@@parsers.unshift Parsers.new(Regexp.new("\\.#{new_ext}$"), parser.parser)
true
end
# Find the correct parser for a particular file name. Return a
# SimpleParser for ones that we don't know
def ParserFactory.parser_for(top_level, file_name, body, options, stats)
# If no extension, look for shebang
if file_name !~ /\.\w+$/ && body =~ %r{\A#!(.+)}
shebang = $1
case shebang
when %r{env\s+ruby}, %r{/ruby}
file_name = "dummy.rb"
end
end
parser_description = can_parse(file_name)
if parser_description
parser = parser_description.parser
else
parser = SimpleParser
end
parser.new(top_level, file_name, body, options, stats)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/parsers/parse_simple.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/parsers/parse_simple.rb | # Parse a non-source file. We basically take the whole thing
# as one big comment. If the first character in the file
# is '#', we strip leading pound signs.
require "rdoc/code_objects"
require "rdoc/markup/simple_markup/preprocess"
module RDoc
# See rdoc/parsers/parse_c.rb
class SimpleParser
# prepare to parse a plain file
def initialize(top_level, file_name, body, options, stats)
preprocess = SM::PreProcess.new(file_name, options.rdoc_include)
preprocess.handle(body) do |directive, param|
$stderr.puts "Unrecognized directive '#{directive}' in #{file_name}"
end
@body = body
@options = options
@top_level = top_level
end
# Extract the file contents and attach them to the toplevel as a
# comment
def scan
# @body.gsub(/^(\s\n)+/, '')
@top_level.comment = remove_private_comments(@body)
@top_level
end
def remove_private_comments(comment)
comment.gsub(/^--.*?^\+\+/m, '').sub(/^--.*/m, '')
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/parsers/parse_c.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/parsers/parse_c.rb | # Classes and modules built in to the interpreter. We need
# these to define superclasses of user objects
require "rdoc/code_objects"
require "rdoc/parsers/parserfactory"
require "rdoc/options"
require "rdoc/rdoc"
module RDoc
##
# Ruby's built-in classes.
KNOWN_CLASSES = {
"rb_cObject" => "Object",
"rb_cArray" => "Array",
"rb_cBignum" => "Bignum",
"rb_cClass" => "Class",
"rb_cDir" => "Dir",
"rb_cData" => "Data",
"rb_cFalseClass" => "FalseClass",
"rb_cFile" => "File",
"rb_cFixnum" => "Fixnum",
"rb_cFloat" => "Float",
"rb_cHash" => "Hash",
"rb_cInteger" => "Integer",
"rb_cIO" => "IO",
"rb_cModule" => "Module",
"rb_cNilClass" => "NilClass",
"rb_cNumeric" => "Numeric",
"rb_cProc" => "Proc",
"rb_cRange" => "Range",
"rb_cRegexp" => "Regexp",
"rb_cString" => "String",
"rb_cSymbol" => "Symbol",
"rb_cThread" => "Thread",
"rb_cTime" => "Time",
"rb_cTrueClass" => "TrueClass",
"rb_cStruct" => "Struct",
"rb_eException" => "Exception",
"rb_eStandardError" => "StandardError",
"rb_eSystemExit" => "SystemExit",
"rb_eInterrupt" => "Interrupt",
"rb_eSignal" => "Signal",
"rb_eFatal" => "Fatal",
"rb_eArgError" => "ArgError",
"rb_eEOFError" => "EOFError",
"rb_eIndexError" => "IndexError",
"rb_eRangeError" => "RangeError",
"rb_eIOError" => "IOError",
"rb_eRuntimeError" => "RuntimeError",
"rb_eSecurityError" => "SecurityError",
"rb_eSystemCallError" => "SystemCallError",
"rb_eTypeError" => "TypeError",
"rb_eZeroDivError" => "ZeroDivError",
"rb_eNotImpError" => "NotImpError",
"rb_eNoMemError" => "NoMemError",
"rb_eFloatDomainError" => "FloatDomainError",
"rb_eScriptError" => "ScriptError",
"rb_eNameError" => "NameError",
"rb_eSyntaxError" => "SyntaxError",
"rb_eLoadError" => "LoadError",
"rb_mKernel" => "Kernel",
"rb_mComparable" => "Comparable",
"rb_mEnumerable" => "Enumerable",
"rb_mPrecision" => "Precision",
"rb_mErrno" => "Errno",
"rb_mFileTest" => "FileTest",
"rb_mGC" => "GC",
"rb_mMath" => "Math",
"rb_mProcess" => "Process"
}
##
# We attempt to parse C extension files. Basically we look for
# the standard patterns that you find in extensions: <tt>rb_define_class,
# rb_define_method</tt> and so on. We also try to find the corresponding
# C source for the methods and extract comments, but if we fail
# we don't worry too much.
#
# The comments associated with a Ruby method are extracted from the C
# comment block associated with the routine that _implements_ that
# method, that is to say the method whose name is given in the
# <tt>rb_define_method</tt> call. For example, you might write:
#
# /*
# * Returns a new array that is a one-dimensional flattening of this
# * array (recursively). That is, for every element that is an array,
# * extract its elements into the new array.
# *
# * s = [ 1, 2, 3 ] #=> [1, 2, 3]
# * t = [ 4, 5, 6, [7, 8] ] #=> [4, 5, 6, [7, 8]]
# * a = [ s, t, 9, 10 ] #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]
# * a.flatten #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# */
# static VALUE
# rb_ary_flatten(ary)
# VALUE ary;
# {
# ary = rb_obj_dup(ary);
# rb_ary_flatten_bang(ary);
# return ary;
# }
#
# ...
#
# void
# Init_Array()
# {
# ...
# rb_define_method(rb_cArray, "flatten", rb_ary_flatten, 0);
#
# Here RDoc will determine from the rb_define_method line that there's a
# method called "flatten" in class Array, and will look for the implementation
# in the method rb_ary_flatten. It will then use the comment from that
# method in the HTML output. This method must be in the same source file
# as the rb_define_method.
#
# C classes can be diagrammed (see /tc/dl/ruby/ruby/error.c), and RDoc
# integrates C and Ruby source into one tree
#
# The comment blocks may include special directives:
#
# [Document-class: <i>name</i>]
# This comment block is documentation for the given class. Use this
# when the <tt>Init_xxx</tt> method is not named after the class.
#
# [Document-method: <i>name</i>]
# This comment documents the named method. Use when RDoc cannot
# automatically find the method from it's declaration
#
# [call-seq: <i>text up to an empty line</i>]
# Because C source doesn't give descriptive names to Ruby-level parameters,
# you need to document the calling sequence explicitly
#
# In addition, RDoc assumes by default that the C method implementing a
# Ruby function is in the same source file as the rb_define_method call.
# If this isn't the case, add the comment
#
# rb_define_method(....); // in: filename
#
# As an example, we might have an extension that defines multiple classes
# in its Init_xxx method. We could document them using
#
#
# /*
# * Document-class: MyClass
# *
# * Encapsulate the writing and reading of the configuration
# * file. ...
# */
#
# /*
# * Document-method: read_value
# *
# * call-seq:
# * cfg.read_value(key) -> value
# * cfg.read_value(key} { |key| } -> value
# *
# * Return the value corresponding to +key+ from the configuration.
# * In the second form, if the key isn't found, invoke the
# * block and return its value.
# */
#
class C_Parser
attr_accessor :progress
extend ParserFactory
parse_files_matching(/\.(?:([CcHh])\1?|c([+xp])\2|y)\z/)
@@known_bodies = {}
# prepare to parse a C file
def initialize(top_level, file_name, body, options, stats)
@known_classes = KNOWN_CLASSES.dup
@body = handle_tab_width(handle_ifdefs_in(body))
@options = options
@stats = stats
@top_level = top_level
@classes = Hash.new
@file_dir = File.dirname(file_name)
@progress = $stderr unless options.quiet
end
# Extract the classes/modules and methods from a C file
# and return the corresponding top-level object
def scan
remove_commented_out_lines
do_classes
do_constants
do_methods
do_includes
do_aliases
@top_level
end
#######
private
#######
def progress(char)
unless @options.quiet
@progress.print(char)
@progress.flush
end
end
def warn(msg)
$stderr.puts
$stderr.puts msg
$stderr.flush
end
def remove_private_comments(comment)
comment.gsub!(/\/?\*--(.*?)\/?\*\+\+/m, '')
comment.sub!(/\/?\*--.*/m, '')
end
##
# removes lines that are commented out that might otherwise get picked up
# when scanning for classes and methods
def remove_commented_out_lines
@body.gsub!(%r{//.*rb_define_}, '//')
end
def handle_class_module(var_name, class_mod, class_name, parent, in_module)
progress(class_mod[0, 1])
parent_name = @known_classes[parent] || parent
if in_module
enclosure = @classes[in_module]
unless enclosure
if enclosure = @known_classes[in_module]
handle_class_module(in_module, (/^rb_m/ =~ in_module ? "module" : "class"),
enclosure, nil, nil)
enclosure = @classes[in_module]
end
end
unless enclosure
warn("Enclosing class/module '#{in_module}' for " +
"#{class_mod} #{class_name} not known")
return
end
else
enclosure = @top_level
end
if class_mod == "class"
cm = enclosure.add_class(NormalClass, class_name, parent_name)
@stats.num_classes += 1
else
cm = enclosure.add_module(NormalModule, class_name)
@stats.num_modules += 1
end
cm.record_location(enclosure.toplevel)
find_class_comment(cm.full_name, cm)
@classes[var_name] = cm
@known_classes[var_name] = cm.full_name
end
##
# Look for class or module documentation above Init_+class_name+(void),
# in a Document-class +class_name+ (or module) comment or above an
# rb_define_class (or module). If a comment is supplied above a matching
# Init_ and a rb_define_class the Init_ comment is used.
#
# /*
# * This is a comment for Foo
# */
# Init_Foo(void) {
# VALUE cFoo = rb_define_class("Foo", rb_cObject);
# }
#
# /*
# * Document-class: Foo
# * This is a comment for Foo
# */
# Init_foo(void) {
# VALUE cFoo = rb_define_class("Foo", rb_cObject);
# }
#
# /*
# * This is a comment for Foo
# */
# VALUE cFoo = rb_define_class("Foo", rb_cObject);
def find_class_comment(class_name, class_meth)
comment = nil
if @body =~ %r{((?>/\*.*?\*/\s+))
(static\s+)?void\s+Init_#{class_name}\s*(?:_\(\s*)?\(\s*(?:void\s*)?\)}xmi
comment = $1
elsif @body =~ %r{Document-(class|module):\s#{class_name}\s*?\n((?>.*?\*/))}m
comment = $2
else
if @body =~ /rb_define_(class|module)/m then
class_name = class_name.split("::").last
comments = []
@body.split(/(\/\*.*?\*\/)\s*?\n/m).each_with_index do |chunk, index|
comments[index] = chunk
if chunk =~ /rb_define_(class|module).*?"(#{class_name})"/m then
comment = comments[index-1]
break
end
end
end
end
class_meth.comment = mangle_comment(comment) if comment
end
############################################################
def do_classes
@body.scan(/(\w+)\s* = \s*rb_define_module\s*\(\s*"(\w+)"\s*\)/mx) do
|var_name, class_name|
handle_class_module(var_name, "module", class_name, nil, nil)
end
# The '.' lets us handle SWIG-generated files
@body.scan(/([\w\.]+)\s* = \s*rb_define_class\s*
\(
\s*"(\w+)",
\s*(\w+)\s*
\)/mx) do
|var_name, class_name, parent|
handle_class_module(var_name, "class", class_name, parent, nil)
end
@body.scan(/(\w+)\s*=\s*boot_defclass\s*\(\s*"(\w+?)",\s*(\w+?)\s*\)/) do
|var_name, class_name, parent|
parent = nil if parent == "0"
handle_class_module(var_name, "class", class_name, parent, nil)
end
@body.scan(/(\w+)\s* = \s*rb_define_module_under\s*
\(
\s*(\w+),
\s*"(\w+)"
\s*\)/mx) do
|var_name, in_module, class_name|
handle_class_module(var_name, "module", class_name, nil, in_module)
end
@body.scan(/([\w\.]+)\s* = \s*rb_define_class_under\s*
\(
\s*(\w+),
\s*"(\w+)",
\s*(\w+)\s*
\s*\)/mx) do
|var_name, in_module, class_name, parent|
handle_class_module(var_name, "class", class_name, parent, in_module)
end
end
###########################################################
def do_constants
@body.scan(%r{\Wrb_define_
(
variable |
readonly_variable |
const |
global_const |
)
\s*\(
(?:\s*(\w+),)?
\s*"(\w+)",
\s*(.*?)\s*\)\s*;
}xm) do
|type, var_name, const_name, definition|
var_name = "rb_cObject" if !var_name or var_name == "rb_mKernel"
handle_constants(type, var_name, const_name, definition)
end
end
############################################################
def do_methods
@body.scan(%r{rb_define_
(
singleton_method |
method |
module_function |
private_method
)
\s*\(\s*([\w\.]+),
\s*"([^"]+)",
\s*(?:RUBY_METHOD_FUNC\(|VALUEFUNC\()?(\w+)\)?,
\s*(-?\w+)\s*\)
(?:;\s*/[*/]\s+in\s+(\w+?\.[cy]))?
}xm) do
|type, var_name, meth_name, meth_body, param_count, source_file|
#"
# Ignore top-object and weird struct.c dynamic stuff
next if var_name == "ruby_top_self"
next if var_name == "nstr"
next if var_name == "envtbl"
next if var_name == "argf" # it'd be nice to handle this one
var_name = "rb_cObject" if var_name == "rb_mKernel"
handle_method(type, var_name, meth_name,
meth_body, param_count, source_file)
end
@body.scan(%r{rb_define_attr\(
\s*([\w\.]+),
\s*"([^"]+)",
\s*(\d+),
\s*(\d+)\s*\);
}xm) do #"
|var_name, attr_name, attr_reader, attr_writer|
#var_name = "rb_cObject" if var_name == "rb_mKernel"
handle_attr(var_name, attr_name,
attr_reader.to_i != 0,
attr_writer.to_i != 0)
end
@body.scan(%r{rb_define_global_function\s*\(
\s*"([^"]+)",
\s*(?:RUBY_METHOD_FUNC\(|VALUEFUNC\()?(\w+)\)?,
\s*(-?\w+)\s*\)
(?:;\s*/[*/]\s+in\s+(\w+?\.[cy]))?
}xm) do #"
|meth_name, meth_body, param_count, source_file|
handle_method("method", "rb_mKernel", meth_name,
meth_body, param_count, source_file)
end
@body.scan(/define_filetest_function\s*\(
\s*"([^"]+)",
\s*(?:RUBY_METHOD_FUNC\(|VALUEFUNC\()?(\w+)\)?,
\s*(-?\w+)\s*\)/xm) do #"
|meth_name, meth_body, param_count|
handle_method("method", "rb_mFileTest", meth_name, meth_body, param_count)
handle_method("singleton_method", "rb_cFile", meth_name, meth_body, param_count)
end
end
############################################################
def do_aliases
@body.scan(%r{rb_define_alias\s*\(\s*(\w+),\s*"([^"]+)",\s*"([^"]+)"\s*\)}m) do
|var_name, new_name, old_name|
@stats.num_methods += 1
class_name = @known_classes[var_name] || var_name
class_obj = find_class(var_name, class_name)
class_obj.add_alias(Alias.new("", old_name, new_name, ""))
end
end
##
# Adds constant comments. By providing some_value: at the start ofthe
# comment you can override the C value of the comment to give a friendly
# definition.
#
# /* 300: The perfect score in bowling */
# rb_define_const(cFoo, "PERFECT", INT2FIX(300);
#
# Will override +INT2FIX(300)+ with the value +300+ in the output RDoc.
# Values may include quotes and escaped colons (\:).
def handle_constants(type, var_name, const_name, definition)
#@stats.num_constants += 1
class_name = @known_classes[var_name]
return unless class_name
class_obj = find_class(var_name, class_name)
unless class_obj
warn("Enclosing class/module '#{const_name}' for not known")
return
end
comment = find_const_comment(type, const_name)
# In the case of rb_define_const, the definition and comment are in
# "/* definition: comment */" form. The literal ':' and '\' characters
# can be escaped with a backslash.
if type.downcase == 'const' then
elements = mangle_comment(comment).split(':')
if elements.nil? or elements.empty? then
con = Constant.new(const_name, definition, mangle_comment(comment))
else
new_definition = elements[0..-2].join(':')
if new_definition.empty? then # Default to literal C definition
new_definition = definition
else
new_definition.gsub!("\:", ":")
new_definition.gsub!("\\", '\\')
end
new_definition.sub!(/\A(\s+)/, '')
new_comment = $1.nil? ? elements.last : "#{$1}#{elements.last.lstrip}"
con = Constant.new(const_name, new_definition,
mangle_comment(new_comment))
end
else
con = Constant.new(const_name, definition, mangle_comment(comment))
end
class_obj.add_constant(con)
end
##
# Finds a comment matching +type+ and +const_name+ either above the
# comment or in the matching Document- section.
def find_const_comment(type, const_name)
if @body =~ %r{((?>^\s*/\*.*?\*/\s+))
rb_define_#{type}\((?:\s*(\w+),)?\s*"#{const_name}"\s*,.*?\)\s*;}xmi
$1
elsif @body =~ %r{Document-(?:const|global|variable):\s#{const_name}\s*?\n((?>.*?\*/))}m
$1
else
''
end
end
###########################################################
def handle_attr(var_name, attr_name, reader, writer)
rw = ''
if reader
#@stats.num_methods += 1
rw << 'R'
end
if writer
#@stats.num_methods += 1
rw << 'W'
end
class_name = @known_classes[var_name]
return unless class_name
class_obj = find_class(var_name, class_name)
if class_obj
comment = find_attr_comment(attr_name)
unless comment.empty?
comment = mangle_comment(comment)
end
att = Attr.new('', attr_name, rw, comment)
class_obj.add_attribute(att)
end
end
###########################################################
def find_attr_comment(attr_name)
if @body =~ %r{((?>/\*.*?\*/\s+))
rb_define_attr\((?:\s*(\w+),)?\s*"#{attr_name}"\s*,.*?\)\s*;}xmi
$1
elsif @body =~ %r{Document-attr:\s#{attr_name}\s*?\n((?>.*?\*/))}m
$1
else
''
end
end
###########################################################
def handle_method(type, var_name, meth_name,
meth_body, param_count, source_file = nil)
progress(".")
@stats.num_methods += 1
class_name = @known_classes[var_name]
return unless class_name
class_obj = find_class(var_name, class_name)
if class_obj
if meth_name == "initialize"
meth_name = "new"
type = "singleton_method"
end
meth_obj = AnyMethod.new("", meth_name)
meth_obj.singleton =
%w{singleton_method module_function}.include?(type)
p_count = (Integer(param_count) rescue -1)
if p_count < 0
meth_obj.params = "(...)"
elsif p_count == 0
meth_obj.params = "()"
else
meth_obj.params = "(" +
(1..p_count).map{|i| "p#{i}"}.join(", ") +
")"
end
if source_file
file_name = File.join(@file_dir, source_file)
body = (@@known_bodies[source_file] ||= File.read(file_name))
else
body = @body
end
if find_body(meth_body, meth_obj, body) and meth_obj.document_self
class_obj.add_method(meth_obj)
end
end
end
############################################################
# Find the C code corresponding to a Ruby method
def find_body(meth_name, meth_obj, body, quiet = false)
case body
when %r{((?>/\*.*?\*/\s*))(?:static\s+)?VALUE\s+#{meth_name}
\s*(\(.*?\)).*?^}xm
comment, params = $1, $2
body_text = $&
remove_private_comments(comment) if comment
# see if we can find the whole body
re = Regexp.escape(body_text) + '[^(]*^\{.*?^\}'
if Regexp.new(re, Regexp::MULTILINE).match(body)
body_text = $&
end
# The comment block may have been overridden with a
# 'Document-method' block. This happens in the interpreter
# when multiple methods are vectored through to the same
# C method but those methods are logically distinct (for
# example Kernel.hash and Kernel.object_id share the same
# implementation
override_comment = find_override_comment(meth_obj.name)
comment = override_comment if override_comment
find_modifiers(comment, meth_obj) if comment
# meth_obj.params = params
meth_obj.start_collecting_tokens
meth_obj.add_token(RubyToken::Token.new(1,1).set_text(body_text))
meth_obj.comment = mangle_comment(comment)
when %r{((?>/\*.*?\*/\s*))^\s*\#\s*define\s+#{meth_name}\s+(\w+)}m
comment = $1
find_body($2, meth_obj, body, true)
find_modifiers(comment, meth_obj)
meth_obj.comment = mangle_comment(comment) + meth_obj.comment
when %r{^\s*\#\s*define\s+#{meth_name}\s+(\w+)}m
unless find_body($1, meth_obj, body, true)
warn "No definition for #{meth_name}" unless quiet
return false
end
else
# No body, but might still have an override comment
comment = find_override_comment(meth_obj.name)
if comment
find_modifiers(comment, meth_obj)
meth_obj.comment = mangle_comment(comment)
else
warn "No definition for #{meth_name}" unless quiet
return false
end
end
true
end
##
# If the comment block contains a section that looks like:
#
# call-seq:
# Array.new
# Array.new(10)
#
# use it for the parameters.
def find_modifiers(comment, meth_obj)
if comment.sub!(/:nodoc:\s*^\s*\*?\s*$/m, '') or
comment.sub!(/\A\/\*\s*:nodoc:\s*\*\/\Z/, '')
meth_obj.document_self = false
end
if comment.sub!(/call-seq:(.*?)^\s*\*?\s*$/m, '') or
comment.sub!(/\A\/\*\s*call-seq:(.*?)\*\/\Z/, '')
seq = $1
seq.gsub!(/^\s*\*\s*/, '')
meth_obj.call_seq = seq
end
end
############################################################
def find_override_comment(meth_name)
name = Regexp.escape(meth_name)
if @body =~ %r{Document-method:\s#{name}\s*?\n((?>.*?\*/))}m
$1
end
end
##
# Look for includes of the form:
#
# rb_include_module(rb_cArray, rb_mEnumerable);
def do_includes
@body.scan(/rb_include_module\s*\(\s*(\w+?),\s*(\w+?)\s*\)/) do |c,m|
if cls = @classes[c]
m = @known_classes[m] || m
cls.add_include(Include.new(m, ""))
end
end
end
##
# Remove the /*'s and leading asterisks from C comments
def mangle_comment(comment)
comment.sub!(%r{/\*+}) { " " * $&.length }
comment.sub!(%r{\*+/}) { " " * $&.length }
comment.gsub!(/^[ \t]*\*/m) { " " * $&.length }
comment
end
def find_class(raw_name, name)
unless @classes[raw_name]
if raw_name =~ /^rb_m/
@classes[raw_name] = @top_level.add_module(NormalModule, name)
else
@classes[raw_name] = @top_level.add_class(NormalClass, name, nil)
end
end
@classes[raw_name]
end
def handle_tab_width(body)
if /\t/ =~ body
tab_width = Options.instance.tab_width
body.split(/\n/).map do |line|
1 while line.gsub!(/\t+/) { ' ' * (tab_width*$&.length - $`.length % tab_width)} && $~ #`
line
end .join("\n")
else
body
end
end
##
# Removes #ifdefs that would otherwise confuse us
def handle_ifdefs_in(body)
body.gsub(/^#ifdef HAVE_PROTOTYPES.*?#else.*?\n(.*?)#endif.*?\n/m) { $1 }
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/markup/simple_markup.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/markup/simple_markup.rb | # = Introduction
#
# SimpleMarkup parses plain text documents and attempts to decompose
# them into their constituent parts. Some of these parts are high-level:
# paragraphs, chunks of verbatim text, list entries and the like. Other
# parts happen at the character level: a piece of bold text, a word in
# code font. This markup is similar in spirit to that used on WikiWiki
# webs, where folks create web pages using a simple set of formatting
# rules.
#
# SimpleMarkup itself does no output formatting: this is left to a
# different set of classes.
#
# SimpleMarkup is extendable at runtime: you can add new markup
# elements to be recognised in the documents that SimpleMarkup parses.
#
# SimpleMarkup is intended to be the basis for a family of tools which
# share the common requirement that simple, plain-text should be
# rendered in a variety of different output formats and media. It is
# envisaged that SimpleMarkup could be the basis for formating RDoc
# style comment blocks, Wiki entries, and online FAQs.
#
# = Basic Formatting
#
# * SimpleMarkup looks for a document's natural left margin. This is
# used as the initial margin for the document.
#
# * Consecutive lines starting at this margin are considered to be a
# paragraph.
#
# * If a paragraph starts with a "*", "-", or with "<digit>.", then it is
# taken to be the start of a list. The margin in increased to be the
# first non-space following the list start flag. Subsequent lines
# should be indented to this new margin until the list ends. For
# example:
#
# * this is a list with three paragraphs in
# the first item. This is the first paragraph.
#
# And this is the second paragraph.
#
# 1. This is an indented, numbered list.
# 2. This is the second item in that list
#
# This is the third conventional paragraph in the
# first list item.
#
# * This is the second item in the original list
#
# * You can also construct labeled lists, sometimes called description
# or definition lists. Do this by putting the label in square brackets
# and indenting the list body:
#
# [cat] a small furry mammal
# that seems to sleep a lot
#
# [ant] a little insect that is known
# to enjoy picnics
#
# A minor variation on labeled lists uses two colons to separate the
# label from the list body:
#
# cat:: a small furry mammal
# that seems to sleep a lot
#
# ant:: a little insect that is known
# to enjoy picnics
#
# This latter style guarantees that the list bodies' left margins are
# aligned: think of them as a two column table.
#
# * Any line that starts to the right of the current margin is treated
# as verbatim text. This is useful for code listings. The example of a
# list above is also verbatim text.
#
# * A line starting with an equals sign (=) is treated as a
# heading. Level one headings have one equals sign, level two headings
# have two,and so on.
#
# * A line starting with three or more hyphens (at the current indent)
# generates a horizontal rule. THe more hyphens, the thicker the rule
# (within reason, and if supported by the output device)
#
# * You can use markup within text (except verbatim) to change the
# appearance of parts of that text. Out of the box, SimpleMarkup
# supports word-based and general markup.
#
# Word-based markup uses flag characters around individual words:
#
# [\*word*] displays word in a *bold* font
# [\_word_] displays word in an _emphasized_ font
# [\+word+] displays word in a +code+ font
#
# General markup affects text between a start delimiter and and end
# delimiter. Not surprisingly, these delimiters look like HTML markup.
#
# [\<b>text...</b>] displays word in a *bold* font
# [\<em>text...</em>] displays word in an _emphasized_ font
# [\<i>text...</i>] displays word in an _emphasized_ font
# [\<tt>text...</tt>] displays word in a +code+ font
#
# Unlike conventional Wiki markup, general markup can cross line
# boundaries. You can turn off the interpretation of markup by
# preceding the first character with a backslash, so \\\<b>bold
# text</b> and \\\*bold* produce \<b>bold text</b> and \*bold
# respectively.
#
# = Using SimpleMarkup
#
# For information on using SimpleMarkup programatically,
# see SM::SimpleMarkup.
#
# Author:: Dave Thomas, dave@pragmaticprogrammer.com
# Version:: 0.0
# License:: Ruby license
require 'rdoc/markup/simple_markup/fragments'
require 'rdoc/markup/simple_markup/lines.rb'
module SM #:nodoc:
# == Synopsis
#
# This code converts <tt>input_string</tt>, which is in the format
# described in markup/simple_markup.rb, to HTML. The conversion
# takes place in the +convert+ method, so you can use the same
# SimpleMarkup object to convert multiple input strings.
#
# require 'rdoc/markup/simple_markup'
# require 'rdoc/markup/simple_markup/to_html'
#
# p = SM::SimpleMarkup.new
# h = SM::ToHtml.new
#
# puts p.convert(input_string, h)
#
# You can extend the SimpleMarkup parser to recognise new markup
# sequences, and to add special processing for text that matches a
# regular epxression. Here we make WikiWords significant to the parser,
# and also make the sequences {word} and \<no>text...</no> signify
# strike-through text. When then subclass the HTML output class to deal
# with these:
#
# require 'rdoc/markup/simple_markup'
# require 'rdoc/markup/simple_markup/to_html'
#
# class WikiHtml < SM::ToHtml
# def handle_special_WIKIWORD(special)
# "<font color=red>" + special.text + "</font>"
# end
# end
#
# p = SM::SimpleMarkup.new
# p.add_word_pair("{", "}", :STRIKE)
# p.add_html("no", :STRIKE)
#
# p.add_special(/\b([A-Z][a-z]+[A-Z]\w+)/, :WIKIWORD)
#
# h = WikiHtml.new
# h.add_tag(:STRIKE, "<strike>", "</strike>")
#
# puts "<body>" + p.convert(ARGF.read, h) + "</body>"
#
# == Output Formatters
#
# _missing_
#
#
class SimpleMarkup
SPACE = ?\s
# List entries look like:
# * text
# 1. text
# [label] text
# label:: text
#
# Flag it as a list entry, and
# work out the indent for subsequent lines
SIMPLE_LIST_RE = /^(
( \* (?# bullet)
|- (?# bullet)
|\d+\. (?# numbered )
|[A-Za-z]\. (?# alphabetically numbered )
)
\s+
)\S/x
LABEL_LIST_RE = /^(
( \[.*?\] (?# labeled )
|\S.*:: (?# note )
)(?:\s+|$)
)/x
##
# take a block of text and use various heuristics to determine
# it's structure (paragraphs, lists, and so on). Invoke an
# event handler as we identify significant chunks.
#
def initialize
@am = AttributeManager.new
@output = nil
end
##
# Add to the sequences used to add formatting to an individual word
# (such as *bold*). Matching entries will generate attibutes
# that the output formatters can recognize by their +name+
def add_word_pair(start, stop, name)
@am.add_word_pair(start, stop, name)
end
##
# Add to the sequences recognized as general markup
#
def add_html(tag, name)
@am.add_html(tag, name)
end
##
# Add to other inline sequences. For example, we could add
# WikiWords using something like:
#
# parser.add_special(/\b([A-Z][a-z]+[A-Z]\w+)/, :WIKIWORD)
#
# Each wiki word will be presented to the output formatter
# via the accept_special method
#
def add_special(pattern, name)
@am.add_special(pattern, name)
end
# We take a string, split it into lines, work out the type of
# each line, and from there deduce groups of lines (for example
# all lines in a paragraph). We then invoke the output formatter
# using a Visitor to display the result
def convert(str, op)
@lines = Lines.new(str.split(/\r?\n/).collect { |aLine|
Line.new(aLine) })
return "" if @lines.empty?
@lines.normalize
assign_types_to_lines
group = group_lines
# call the output formatter to handle the result
# group.to_a.each {|i| p i}
group.accept(@am, op)
end
#######
private
#######
##
# Look through the text at line indentation. We flag each line as being
# Blank, a paragraph, a list element, or verbatim text
#
def assign_types_to_lines(margin = 0, level = 0)
while line = @lines.next
if line.isBlank?
line.stamp(Line::BLANK, level)
next
end
# if a line contains non-blanks before the margin, then it must belong
# to an outer level
text = line.text
for i in 0...margin
if text[i] != SPACE
@lines.unget
return
end
end
active_line = text[margin..-1]
# Rules (horizontal lines) look like
#
# --- (three or more hyphens)
#
# The more hyphens, the thicker the rule
#
if /^(---+)\s*$/ =~ active_line
line.stamp(Line::RULE, level, $1.length-2)
next
end
# Then look for list entries. First the ones that have to have
# text following them (* xxx, - xxx, and dd. xxx)
if SIMPLE_LIST_RE =~ active_line
offset = margin + $1.length
prefix = $2
prefix_length = prefix.length
flag = case prefix
when "*","-" then ListBase::BULLET
when /^\d/ then ListBase::NUMBER
when /^[A-Z]/ then ListBase::UPPERALPHA
when /^[a-z]/ then ListBase::LOWERALPHA
else raise "Invalid List Type: #{self.inspect}"
end
line.stamp(Line::LIST, level+1, prefix, flag)
text[margin, prefix_length] = " " * prefix_length
assign_types_to_lines(offset, level + 1)
next
end
if LABEL_LIST_RE =~ active_line
offset = margin + $1.length
prefix = $2
prefix_length = prefix.length
next if handled_labeled_list(line, level, margin, offset, prefix)
end
# Headings look like
# = Main heading
# == Second level
# === Third
#
# Headings reset the level to 0
if active_line[0] == ?= and active_line =~ /^(=+)\s*(.*)/
prefix_length = $1.length
prefix_length = 6 if prefix_length > 6
line.stamp(Line::HEADING, 0, prefix_length)
line.strip_leading(margin + prefix_length)
next
end
# If the character's a space, then we have verbatim text,
# otherwise
if active_line[0] == SPACE
line.strip_leading(margin) if margin > 0
line.stamp(Line::VERBATIM, level)
else
line.stamp(Line::PARAGRAPH, level)
end
end
end
# Handle labeled list entries, We have a special case
# to deal with. Because the labels can be long, they force
# the remaining block of text over the to right:
#
# this is a long label that I wrote:: and here is the
# block of text with
# a silly margin
#
# So we allow the special case. If the label is followed
# by nothing, and if the following line is indented, then
# we take the indent of that line as the new margin
#
# this is a long label that I wrote::
# here is a more reasonably indented block which
# will ab attached to the label.
#
def handled_labeled_list(line, level, margin, offset, prefix)
prefix_length = prefix.length
text = line.text
flag = nil
case prefix
when /^\[/
flag = ListBase::LABELED
prefix = prefix[1, prefix.length-2]
when /:$/
flag = ListBase::NOTE
prefix.chop!
else raise "Invalid List Type: #{self.inspect}"
end
# body is on the next line
if text.length <= offset
original_line = line
line = @lines.next
return(false) unless line
text = line.text
for i in 0..margin
if text[i] != SPACE
@lines.unget
return false
end
end
i = margin
i += 1 while text[i] == SPACE
if i >= text.length
@lines.unget
return false
else
offset = i
prefix_length = 0
@lines.delete(original_line)
end
end
line.stamp(Line::LIST, level+1, prefix, flag)
text[margin, prefix_length] = " " * prefix_length
assign_types_to_lines(offset, level + 1)
return true
end
# Return a block consisting of fragments which are
# paragraphs, list entries or verbatim text. We merge consecutive
# lines of the same type and level together. We are also slightly
# tricky with lists: the lines following a list introduction
# look like paragraph lines at the next level, and we remap them
# into list entries instead
def group_lines
@lines.rewind
inList = false
wantedType = wantedLevel = nil
block = LineCollection.new
group = nil
while line = @lines.next
if line.level == wantedLevel and line.type == wantedType
group.add_text(line.text)
else
group = block.fragment_for(line)
block.add(group)
if line.type == Line::LIST
wantedType = Line::PARAGRAPH
else
wantedType = line.type
end
wantedLevel = line.type == Line::HEADING ? line.param : line.level
end
end
block.normalize
block
end
## for debugging, we allow access to our line contents as text
def content
@lines.as_text
end
public :content
## for debugging, return the list of line types
def get_line_types
@lines.line_types
end
public :get_line_types
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/markup/test/AllTests.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/markup/test/AllTests.rb | require 'TestParse.rb'
require 'TestInline.rb'
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/markup/test/TestInline.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/markup/test/TestInline.rb | require "test/unit"
$:.unshift "../../.."
require "rdoc/markup/simple_markup/inline"
class TestInline < Test::Unit::TestCase
def setup
@am = SM::AttributeManager.new
@bold_on = @am.changed_attribute_by_name([], [:BOLD])
@bold_off = @am.changed_attribute_by_name([:BOLD], [])
@tt_on = @am.changed_attribute_by_name([], [:TT])
@tt_off = @am.changed_attribute_by_name([:TT], [])
@em_on = @am.changed_attribute_by_name([], [:EM])
@em_off = @am.changed_attribute_by_name([:EM], [])
@bold_em_on = @am.changed_attribute_by_name([], [:BOLD] | [:EM])
@bold_em_off = @am.changed_attribute_by_name([:BOLD] | [:EM], [])
@em_then_bold = @am.changed_attribute_by_name([:EM], [:EM] | [:BOLD])
@em_to_bold = @am.changed_attribute_by_name([:EM], [:BOLD])
@am.add_word_pair("{", "}", :WOMBAT)
@wombat_on = @am.changed_attribute_by_name([], [:WOMBAT])
@wombat_off = @am.changed_attribute_by_name([:WOMBAT], [])
end
def crossref(text)
[ @am.changed_attribute_by_name([], [:CROSSREF] | [:_SPECIAL_]),
SM::Special.new(33, text),
@am.changed_attribute_by_name([:CROSSREF] | [:_SPECIAL_], [])
]
end
def test_special
# class names, variable names, file names, or instance variables
@am.add_special(/(
\b([A-Z]\w+(::\w+)*)
| \#\w+[!?=]?
| \b\w+([_\/\.]+\w+)+[!?=]?
)/x,
:CROSSREF)
assert_equal(["cat"], @am.flow("cat"))
assert_equal(["cat ", crossref("#fred"), " dog"].flatten,
@am.flow("cat #fred dog"))
assert_equal([crossref("#fred"), " dog"].flatten,
@am.flow("#fred dog"))
assert_equal(["cat ", crossref("#fred")].flatten, @am.flow("cat #fred"))
end
def test_basic
assert_equal(["cat"], @am.flow("cat"))
assert_equal(["cat ", @bold_on, "and", @bold_off, " dog"],
@am.flow("cat *and* dog"))
assert_equal(["cat ", @bold_on, "AND", @bold_off, " dog"],
@am.flow("cat *AND* dog"))
assert_equal(["cat ", @em_on, "And", @em_off, " dog"],
@am.flow("cat _And_ dog"))
assert_equal(["cat *and dog*"], @am.flow("cat *and dog*"))
assert_equal(["*cat and* dog"], @am.flow("*cat and* dog"))
assert_equal(["cat *and ", @bold_on, "dog", @bold_off],
@am.flow("cat *and *dog*"))
assert_equal(["cat ", @em_on, "and", @em_off, " dog"],
@am.flow("cat _and_ dog"))
assert_equal(["cat_and_dog"],
@am.flow("cat_and_dog"))
assert_equal(["cat ", @tt_on, "and", @tt_off, " dog"],
@am.flow("cat +and+ dog"))
assert_equal(["cat ", @bold_on, "a_b_c", @bold_off, " dog"],
@am.flow("cat *a_b_c* dog"))
assert_equal(["cat __ dog"],
@am.flow("cat __ dog"))
assert_equal(["cat ", @em_on, "_", @em_off, " dog"],
@am.flow("cat ___ dog"))
end
def test_combined
assert_equal(["cat ", @em_on, "and", @em_off, " ", @bold_on, "dog", @bold_off],
@am.flow("cat _and_ *dog*"))
assert_equal(["cat ", @em_on, "a__nd", @em_off, " ", @bold_on, "dog", @bold_off],
@am.flow("cat _a__nd_ *dog*"))
end
def test_html_like
assert_equal(["cat ", @tt_on, "dog", @tt_off], @am.flow("cat <tt>dog</Tt>"))
assert_equal(["cat ", @em_on, "and", @em_off, " ", @bold_on, "dog", @bold_off],
@am.flow("cat <i>and</i> <B>dog</b>"))
assert_equal(["cat ", @em_on, "and ", @em_then_bold, "dog", @bold_em_off],
@am.flow("cat <i>and <B>dog</B></I>"))
assert_equal(["cat ", @em_on, "and ", @em_to_bold, "dog", @bold_off],
@am.flow("cat <i>and </i><b>dog</b>"))
assert_equal(["cat ", @em_on, "and ", @em_to_bold, "dog", @bold_off],
@am.flow("cat <i>and <b></i>dog</b>"))
assert_equal([@tt_on, "cat", @tt_off, " ", @em_on, "and ", @em_to_bold, "dog", @bold_off],
@am.flow("<tt>cat</tt> <i>and <b></i>dog</b>"))
assert_equal(["cat ", @em_on, "and ", @em_then_bold, "dog", @bold_em_off],
@am.flow("cat <i>and <b>dog</b></i>"))
assert_equal(["cat ", @bold_em_on, "and", @bold_em_off, " dog"],
@am.flow("cat <i><b>and</b></i> dog"))
end
def test_protect
assert_equal(['cat \\ dog'], @am.flow('cat \\ dog'))
assert_equal(["cat <tt>dog</Tt>"], @am.flow("cat \\<tt>dog</Tt>"))
assert_equal(["cat ", @em_on, "and", @em_off, " <B>dog</b>"],
@am.flow("cat <i>and</i> \\<B>dog</b>"))
assert_equal(["*word* or <b>text</b>"], @am.flow("\\*word* or \\<b>text</b>"))
assert_equal(["_cat_", @em_on, "dog", @em_off],
@am.flow("\\_cat_<i>dog</i>"))
end
def test_adding
assert_equal(["cat ", @wombat_on, "and", @wombat_off, " dog" ],
@am.flow("cat {and} dog"))
# assert_equal(["cat {and} dog" ], @am.flow("cat \\{and} dog"))
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/markup/test/TestParse.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/markup/test/TestParse.rb | require 'test/unit'
$:.unshift "../../.."
require 'rdoc/markup/simple_markup'
include SM
class TestParse < Test::Unit::TestCase
class MockOutput
def start_accepting
@res = []
end
def end_accepting
@res
end
def accept_paragraph(am, fragment)
@res << fragment.to_s
end
def accept_verbatim(am, fragment)
@res << fragment.to_s
end
def accept_list_start(am, fragment)
@res << fragment.to_s
end
def accept_list_end(am, fragment)
@res << fragment.to_s
end
def accept_list_item(am, fragment)
@res << fragment.to_s
end
def accept_blank_line(am, fragment)
@res << fragment.to_s
end
def accept_heading(am, fragment)
@res << fragment.to_s
end
def accept_rule(am, fragment)
@res << fragment.to_s
end
end
def basic_conv(str)
sm = SimpleMarkup.new
mock = MockOutput.new
sm.convert(str, mock)
sm.content
end
def line_types(str, expected)
p = SimpleMarkup.new
mock = MockOutput.new
p.convert(str, mock)
assert_equal(expected, p.get_line_types.map{|type| type.to_s[0,1]}.join(''))
end
def line_groups(str, expected)
p = SimpleMarkup.new
mock = MockOutput.new
block = p.convert(str, mock)
if block != expected
rows = (0...([expected.size, block.size].max)).collect{|i|
[expected[i]||"nil", block[i]||"nil"]
}
printf "\n\n%35s %35s\n", "Expected", "Got"
rows.each {|e,g| printf "%35s %35s\n", e.dump, g.dump }
end
assert_equal(expected, block)
end
def test_tabs
str = "hello\n dave"
assert_equal(str, basic_conv(str))
str = "hello\n\tdave"
assert_equal("hello\n dave", basic_conv(str))
str = "hello\n \tdave"
assert_equal("hello\n dave", basic_conv(str))
str = "hello\n \tdave"
assert_equal("hello\n dave", basic_conv(str))
str = "hello\n \tdave"
assert_equal("hello\n dave", basic_conv(str))
str = "hello\n \tdave"
assert_equal("hello\n dave", basic_conv(str))
str = "hello\n \tdave"
assert_equal("hello\n dave", basic_conv(str))
str = "hello\n \tdave"
assert_equal("hello\n dave", basic_conv(str))
str = "hello\n \tdave"
assert_equal("hello\n dave", basic_conv(str))
str = "hello\n \tdave"
assert_equal("hello\n dave", basic_conv(str))
str = ".\t\t."
assert_equal(". .", basic_conv(str))
end
def test_whitespace
assert_equal("hello", basic_conv("hello"))
assert_equal("hello", basic_conv(" hello "))
assert_equal("hello", basic_conv(" \t \t hello\t\t"))
assert_equal("1\n 2\n 3", basic_conv("1\n 2\n 3"))
assert_equal("1\n 2\n 3", basic_conv(" 1\n 2\n 3"))
assert_equal("1\n 2\n 3\n1\n 2", basic_conv("1\n 2\n 3\n1\n 2"))
assert_equal("1\n 2\n 3\n1\n 2", basic_conv(" 1\n 2\n 3\n 1\n 2"))
assert_equal("1\n 2\n\n 3", basic_conv(" 1\n 2\n\n 3"))
end
def test_types
str = "now is the time"
line_types(str, 'P')
str = "now is the time\nfor all good men"
line_types(str, 'PP')
str = "now is the time\n code\nfor all good men"
line_types(str, 'PVP')
str = "now is the time\n code\n more code\nfor all good men"
line_types(str, 'PVVP')
str = "now is\n---\nthe time"
line_types(str, 'PRP')
str = %{\
now is
* l1
* l2
the time}
line_types(str, 'PLLP')
str = %{\
now is
* l1
l1+
* l2
the time}
line_types(str, 'PLPLP')
str = %{\
now is
* l1
* l1.1
* l2
the time}
line_types(str, 'PLLLP')
str = %{\
now is
* l1
* l1.1
text
code
code
text
* l2
the time}
line_types(str, 'PLLPVVBPLP')
str = %{\
now is
1. l1
* l1.1
2. l2
the time}
line_types(str, 'PLLLP')
str = %{\
now is
[cat] l1
* l1.1
[dog] l2
the time}
line_types(str, 'PLLLP')
str = %{\
now is
[cat] l1
continuation
[dog] l2
the time}
line_types(str, 'PLPLP')
end
def test_groups
str = "now is the time"
line_groups(str, ["L0: Paragraph\nnow is the time"] )
str = "now is the time\nfor all good men"
line_groups(str, ["L0: Paragraph\nnow is the time for all good men"] )
str = %{\
now is the time
code _line_ here
for all good men}
line_groups(str,
[ "L0: Paragraph\nnow is the time",
"L0: Verbatim\n code _line_ here\n",
"L0: Paragraph\nfor all good men"
] )
str = "now is the time\n code\n more code\nfor all good men"
line_groups(str,
[ "L0: Paragraph\nnow is the time",
"L0: Verbatim\n code\n more code\n",
"L0: Paragraph\nfor all good men"
] )
str = %{\
now is
* l1
* l2
the time}
line_groups(str,
[ "L0: Paragraph\nnow is",
"L1: ListStart\n",
"L1: ListItem\nl1",
"L1: ListItem\nl2",
"L1: ListEnd\n",
"L0: Paragraph\nthe time"
])
str = %{\
now is
* l1
l1+
* l2
the time}
line_groups(str,
[ "L0: Paragraph\nnow is",
"L1: ListStart\n",
"L1: ListItem\nl1 l1+",
"L1: ListItem\nl2",
"L1: ListEnd\n",
"L0: Paragraph\nthe time"
])
str = %{\
now is
* l1
* l1.1
* l2
the time}
line_groups(str,
[ "L0: Paragraph\nnow is",
"L1: ListStart\n",
"L1: ListItem\nl1",
"L2: ListStart\n",
"L2: ListItem\nl1.1",
"L2: ListEnd\n",
"L1: ListItem\nl2",
"L1: ListEnd\n",
"L0: Paragraph\nthe time"
])
str = %{\
now is
* l1
* l1.1
text
code
code
text
* l2
the time}
line_groups(str,
[ "L0: Paragraph\nnow is",
"L1: ListStart\n",
"L1: ListItem\nl1",
"L2: ListStart\n",
"L2: ListItem\nl1.1 text",
"L2: Verbatim\n code\n code\n",
"L2: Paragraph\ntext",
"L2: ListEnd\n",
"L1: ListItem\nl2",
"L1: ListEnd\n",
"L0: Paragraph\nthe time"
])
str = %{\
now is
1. l1
* l1.1
2. l2
the time}
line_groups(str,
[ "L0: Paragraph\nnow is",
"L1: ListStart\n",
"L1: ListItem\nl1",
"L2: ListStart\n",
"L2: ListItem\nl1.1",
"L2: ListEnd\n",
"L1: ListItem\nl2",
"L1: ListEnd\n",
"L0: Paragraph\nthe time"
])
str = %{\
now is
[cat] l1
* l1.1
[dog] l2
the time}
line_groups(str,
[ "L0: Paragraph\nnow is",
"L1: ListStart\n",
"L1: ListItem\nl1",
"L2: ListStart\n",
"L2: ListItem\nl1.1",
"L2: ListEnd\n",
"L1: ListItem\nl2",
"L1: ListEnd\n",
"L0: Paragraph\nthe time"
])
str = %{\
now is
[cat] l1
continuation
[dog] l2
the time}
line_groups(str,
[ "L0: Paragraph\nnow is",
"L1: ListStart\n",
"L1: ListItem\nl1 continuation",
"L1: ListItem\nl2",
"L1: ListEnd\n",
"L0: Paragraph\nthe time"
])
end
def test_verbatim_merge
str = %{\
now is
code
the time}
line_groups(str,
[ "L0: Paragraph\nnow is",
"L0: Verbatim\n code\n",
"L0: Paragraph\nthe time"
])
str = %{\
now is
code
code1
the time}
line_groups(str,
[ "L0: Paragraph\nnow is",
"L0: Verbatim\n code\n code1\n",
"L0: Paragraph\nthe time"
])
str = %{\
now is
code
code1
the time}
line_groups(str,
[ "L0: Paragraph\nnow is",
"L0: Verbatim\n code\n\n code1\n",
"L0: Paragraph\nthe time"
])
str = %{\
now is
code
code1
the time}
line_groups(str,
[ "L0: Paragraph\nnow is",
"L0: Verbatim\n code\n\n code1\n",
"L0: Paragraph\nthe time"
])
str = %{\
now is
code
code1
code2
the time}
line_groups(str,
[ "L0: Paragraph\nnow is",
"L0: Verbatim\n code\n\n code1\n\n code2\n",
"L0: Paragraph\nthe time"
])
# Folds multiple blank lines
str = %{\
now is
code
code1
the time}
line_groups(str,
[ "L0: Paragraph\nnow is",
"L0: Verbatim\n code\n\n code1\n",
"L0: Paragraph\nthe time"
])
end
def test_list_split
str = %{\
now is
* l1
1. n1
2. n2
* l2
the time}
line_groups(str,
[ "L0: Paragraph\nnow is",
"L1: ListStart\n",
"L1: ListItem\nl1",
"L1: ListEnd\n",
"L1: ListStart\n",
"L1: ListItem\nn1",
"L1: ListItem\nn2",
"L1: ListEnd\n",
"L1: ListStart\n",
"L1: ListItem\nl2",
"L1: ListEnd\n",
"L0: Paragraph\nthe time"
])
end
def test_headings
str = "= heading one"
line_groups(str,
[ "L0: Heading\nheading one"
])
str = "=== heading three"
line_groups(str,
[ "L0: Heading\nheading three"
])
str = "text\n === heading three"
line_groups(str,
[ "L0: Paragraph\ntext",
"L0: Verbatim\n === heading three\n"
])
str = "text\n code\n === heading three"
line_groups(str,
[ "L0: Paragraph\ntext",
"L0: Verbatim\n code\n === heading three\n"
])
str = "text\n code\n=== heading three"
line_groups(str,
[ "L0: Paragraph\ntext",
"L0: Verbatim\n code\n",
"L0: Heading\nheading three"
])
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/markup/simple_markup/inline.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/markup/simple_markup/inline.rb | module SM
# We manage a set of attributes. Each attribute has a symbol name
# and a bit value
class Attribute
SPECIAL = 1
@@name_to_bitmap = { :_SPECIAL_ => SPECIAL }
@@next_bitmap = 2
def Attribute.bitmap_for(name)
bitmap = @@name_to_bitmap[name]
if !bitmap
bitmap = @@next_bitmap
@@next_bitmap <<= 1
@@name_to_bitmap[name] = bitmap
end
bitmap
end
def Attribute.as_string(bitmap)
return "none" if bitmap.zero?
res = []
@@name_to_bitmap.each do |name, bit|
res << name if (bitmap & bit) != 0
end
res.join(",")
end
def Attribute.each_name_of(bitmap)
@@name_to_bitmap.each do |name, bit|
next if bit == SPECIAL
yield name.to_s if (bitmap & bit) != 0
end
end
end
# An AttrChanger records a change in attributes. It contains
# a bitmap of the attributes to turn on, and a bitmap of those to
# turn off
AttrChanger = Struct.new(:turn_on, :turn_off)
class AttrChanger
def to_s
"Attr: +#{Attribute.as_string(@turn_on)}/-#{Attribute.as_string(@turn_on)}"
end
end
# An array of attributes which parallels the characters in a string
class AttrSpan
def initialize(length)
@attrs = Array.new(length, 0)
end
def set_attrs(start, length, bits)
for i in start ... (start+length)
@attrs[i] |= bits
end
end
def [](n)
@attrs[n]
end
end
##
# Hold details of a special sequence
class Special
attr_reader :type
attr_accessor :text
def initialize(type, text)
@type, @text = type, text
end
def ==(o)
self.text == o.text && self.type == o.type
end
def to_s
"Special: type=#{type}, text=#{text.dump}"
end
end
class AttributeManager
NULL = "\000".freeze
##
# We work by substituting non-printing characters in to the
# text. For now I'm assuming that I can substitute
# a character in the range 0..8 for a 7 bit character
# without damaging the encoded string, but this might
# be optimistic
#
A_PROTECT = 004
PROTECT_ATTR = A_PROTECT.chr
# This maps delimiters that occur around words (such as
# *bold* or +tt+) where the start and end delimiters
# and the same. This lets us optimize the regexp
MATCHING_WORD_PAIRS = {}
# And this is used when the delimiters aren't the same. In this
# case the hash maps a pattern to the attribute character
WORD_PAIR_MAP = {}
# This maps HTML tags to the corresponding attribute char
HTML_TAGS = {}
# And this maps _special_ sequences to a name. A special sequence
# is something like a WikiWord
SPECIAL = {}
# Return an attribute object with the given turn_on
# and turn_off bits set
def attribute(turn_on, turn_off)
AttrChanger.new(turn_on, turn_off)
end
def change_attribute(current, new)
diff = current ^ new
attribute(new & diff, current & diff)
end
def changed_attribute_by_name(current_set, new_set)
current = new = 0
current_set.each {|name| current |= Attribute.bitmap_for(name) }
new_set.each {|name| new |= Attribute.bitmap_for(name) }
change_attribute(current, new)
end
def copy_string(start_pos, end_pos)
res = @str[start_pos...end_pos]
res.gsub!(/\000/, '')
res
end
# Map attributes like <b>text</b>to the sequence \001\002<char>\001\003<char>,
# where <char> is a per-attribute specific character
def convert_attrs(str, attrs)
# first do matching ones
tags = MATCHING_WORD_PAIRS.keys.join("")
re = "(^|\\W)([#{tags}])([A-Za-z_]+?)\\2(\\W|\$)"
# re = "(^|\\W)([#{tags}])(\\S+?)\\2(\\W|\$)"
1 while str.gsub!(Regexp.new(re)) {
attr = MATCHING_WORD_PAIRS[$2];
attrs.set_attrs($`.length + $1.length + $2.length, $3.length, attr)
$1 + NULL*$2.length + $3 + NULL*$2.length + $4
}
# then non-matching
unless WORD_PAIR_MAP.empty?
WORD_PAIR_MAP.each do |regexp, attr|
str.gsub!(regexp) {
attrs.set_attrs($`.length + $1.length, $2.length, attr)
NULL*$1.length + $2 + NULL*$3.length
}
end
end
end
def convert_html(str, attrs)
tags = HTML_TAGS.keys.join("|")
re = "<(#{tags})>(.*?)</\\1>"
1 while str.gsub!(Regexp.new(re, Regexp::IGNORECASE)) {
attr = HTML_TAGS[$1.downcase]
html_length = $1.length + 2
seq = NULL * html_length
attrs.set_attrs($`.length + html_length, $2.length, attr)
seq + $2 + seq + NULL
}
end
def convert_specials(str, attrs)
unless SPECIAL.empty?
SPECIAL.each do |regexp, attr|
str.scan(regexp) do
attrs.set_attrs($`.length, $&.length, attr | Attribute::SPECIAL)
end
end
end
end
# A \ in front of a character that would normally be
# processed turns off processing. We do this by turning
# \< into <#{PROTECT}
PROTECTABLE = [ "<" << "\\" ] #"
def mask_protected_sequences
protect_pattern = Regexp.new("\\\\([#{Regexp.escape(PROTECTABLE.join(''))}])")
@str.gsub!(protect_pattern, "\\1#{PROTECT_ATTR}")
end
def unmask_protected_sequences
@str.gsub!(/(.)#{PROTECT_ATTR}/, "\\1\000")
end
def initialize
add_word_pair("*", "*", :BOLD)
add_word_pair("_", "_", :EM)
add_word_pair("+", "+", :TT)
add_html("em", :EM)
add_html("i", :EM)
add_html("b", :BOLD)
add_html("tt", :TT)
add_html("code", :TT)
add_special(/<!--(.*?)-->/, :COMMENT)
end
def add_word_pair(start, stop, name)
raise "Word flags may not start '<'" if start[0] == ?<
bitmap = Attribute.bitmap_for(name)
if start == stop
MATCHING_WORD_PAIRS[start] = bitmap
else
pattern = Regexp.new("(" + Regexp.escape(start) + ")" +
# "([A-Za-z]+)" +
"(\\S+)" +
"(" + Regexp.escape(stop) +")")
WORD_PAIR_MAP[pattern] = bitmap
end
PROTECTABLE << start[0,1]
PROTECTABLE.uniq!
end
def add_html(tag, name)
HTML_TAGS[tag.downcase] = Attribute.bitmap_for(name)
end
def add_special(pattern, name)
SPECIAL[pattern] = Attribute.bitmap_for(name)
end
def flow(str)
@str = str
puts("Before flow, str='#{@str.dump}'") if $DEBUG
mask_protected_sequences
@attrs = AttrSpan.new(@str.length)
puts("After protecting, str='#{@str.dump}'") if $DEBUG
convert_attrs(@str, @attrs)
convert_html(@str, @attrs)
convert_specials(str, @attrs)
unmask_protected_sequences
puts("After flow, str='#{@str.dump}'") if $DEBUG
return split_into_flow
end
def display_attributes
puts
puts @str.tr(NULL, "!")
bit = 1
16.times do |bno|
line = ""
@str.length.times do |i|
if (@attrs[i] & bit) == 0
line << " "
else
if bno.zero?
line << "S"
else
line << ("%d" % (bno+1))
end
end
end
puts(line) unless line =~ /^ *$/
bit <<= 1
end
end
def split_into_flow
display_attributes if $DEBUG
res = []
current_attr = 0
str = ""
str_len = @str.length
# skip leading invisible text
i = 0
i += 1 while i < str_len and @str[i].zero?
start_pos = i
# then scan the string, chunking it on attribute changes
while i < str_len
new_attr = @attrs[i]
if new_attr != current_attr
if i > start_pos
res << copy_string(start_pos, i)
start_pos = i
end
res << change_attribute(current_attr, new_attr)
current_attr = new_attr
if (current_attr & Attribute::SPECIAL) != 0
i += 1 while i < str_len and (@attrs[i] & Attribute::SPECIAL) != 0
res << Special.new(current_attr, copy_string(start_pos, i))
start_pos = i
next
end
end
# move on, skipping any invisible characters
begin
i += 1
end while i < str_len and @str[i].zero?
end
# tidy up trailing text
if start_pos < str_len
res << copy_string(start_pos, str_len)
end
# and reset to all attributes off
res << change_attribute(current_attr, 0) if current_attr != 0
return res
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/markup/simple_markup/lines.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/markup/simple_markup/lines.rb | ##########################################################################
#
# We store the lines we're working on as objects of class Line.
# These contain the text of the line, along with a flag indicating the
# line type, and an indentation level
module SM
class Line
INFINITY = 9999
BLANK = :BLANK
HEADING = :HEADING
LIST = :LIST
RULE = :RULE
PARAGRAPH = :PARAGRAPH
VERBATIM = :VERBATIM
# line type
attr_accessor :type
# The indentation nesting level
attr_accessor :level
# The contents
attr_accessor :text
# A prefix or parameter. For LIST lines, this is
# the text that introduced the list item (the label)
attr_accessor :param
# A flag. For list lines, this is the type of the list
attr_accessor :flag
# the number of leading spaces
attr_accessor :leading_spaces
# true if this line has been deleted from the list of lines
attr_accessor :deleted
def initialize(text)
@text = text.dup
@deleted = false
# expand tabs
1 while @text.gsub!(/\t+/) { ' ' * (8*$&.length - $`.length % 8)} && $~ #`
# Strip trailing whitespace
@text.sub!(/\s+$/, '')
# and look for leading whitespace
if @text.length > 0
@text =~ /^(\s*)/
@leading_spaces = $1.length
else
@leading_spaces = INFINITY
end
end
# Return true if this line is blank
def isBlank?
@text.length.zero?
end
# stamp a line with a type, a level, a prefix, and a flag
def stamp(type, level, param="", flag=nil)
@type, @level, @param, @flag = type, level, param, flag
end
##
# Strip off the leading margin
#
def strip_leading(size)
if @text.size > size
@text[0,size] = ""
else
@text = ""
end
end
def to_s
"#@type#@level: #@text"
end
end
###############################################################################
#
# A container for all the lines
#
class Lines
include Enumerable
attr_reader :lines # for debugging
def initialize(lines)
@lines = lines
rewind
end
def empty?
@lines.size.zero?
end
def each
@lines.each do |line|
yield line unless line.deleted
end
end
# def [](index)
# @lines[index]
# end
def rewind
@nextline = 0
end
def next
begin
res = @lines[@nextline]
@nextline += 1 if @nextline < @lines.size
end while res and res.deleted and @nextline < @lines.size
res
end
def unget
@nextline -= 1
end
def delete(a_line)
a_line.deleted = true
end
def normalize
margin = @lines.collect{|l| l.leading_spaces}.min
margin = 0 if margin == Line::INFINITY
@lines.each {|line| line.strip_leading(margin) } if margin > 0
end
def as_text
@lines.map {|l| l.text}.join("\n")
end
def line_types
@lines.map {|l| l.type }
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/markup/simple_markup/to_html.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/markup/simple_markup/to_html.rb | require 'rdoc/markup/simple_markup/fragments'
require 'rdoc/markup/simple_markup/inline'
require 'cgi'
module SM
class ToHtml
LIST_TYPE_TO_HTML = {
ListBase::BULLET => [ "<ul>", "</ul>" ],
ListBase::NUMBER => [ "<ol>", "</ol>" ],
ListBase::UPPERALPHA => [ "<ol>", "</ol>" ],
ListBase::LOWERALPHA => [ "<ol>", "</ol>" ],
ListBase::LABELED => [ "<dl>", "</dl>" ],
ListBase::NOTE => [ "<table>", "</table>" ],
}
InlineTag = Struct.new(:bit, :on, :off)
def initialize
init_tags
end
##
# Set up the standard mapping of attributes to HTML tags
#
def init_tags
@attr_tags = [
InlineTag.new(SM::Attribute.bitmap_for(:BOLD), "<b>", "</b>"),
InlineTag.new(SM::Attribute.bitmap_for(:TT), "<tt>", "</tt>"),
InlineTag.new(SM::Attribute.bitmap_for(:EM), "<em>", "</em>"),
]
end
##
# Add a new set of HTML tags for an attribute. We allow
# separate start and end tags for flexibility
#
def add_tag(name, start, stop)
@attr_tags << InlineTag.new(SM::Attribute.bitmap_for(name), start, stop)
end
##
# Given an HTML tag, decorate it with class information
# and the like if required. This is a no-op in the base
# class, but is overridden in HTML output classes that
# implement style sheets
def annotate(tag)
tag
end
##
# Here's the client side of the visitor pattern
def start_accepting
@res = ""
@in_list_entry = []
end
def end_accepting
@res
end
def accept_paragraph(am, fragment)
@res << annotate("<p>") + "\n"
@res << wrap(convert_flow(am.flow(fragment.txt)))
@res << annotate("</p>") + "\n"
end
def accept_verbatim(am, fragment)
@res << annotate("<pre>") + "\n"
@res << CGI.escapeHTML(fragment.txt)
@res << annotate("</pre>") << "\n"
end
def accept_rule(am, fragment)
size = fragment.param
size = 10 if size > 10
@res << "<hr size=\"#{size}\"></hr>"
end
def accept_list_start(am, fragment)
@res << html_list_name(fragment.type, true) <<"\n"
@in_list_entry.push false
end
def accept_list_end(am, fragment)
if tag = @in_list_entry.pop
@res << annotate(tag) << "\n"
end
@res << html_list_name(fragment.type, false) <<"\n"
end
def accept_list_item(am, fragment)
if tag = @in_list_entry.last
@res << annotate(tag) << "\n"
end
@res << list_item_start(am, fragment)
@res << wrap(convert_flow(am.flow(fragment.txt))) << "\n"
@in_list_entry[-1] = list_end_for(fragment.type)
end
def accept_blank_line(am, fragment)
# @res << annotate("<p />") << "\n"
end
def accept_heading(am, fragment)
@res << convert_heading(fragment.head_level, am.flow(fragment.txt))
end
# This is a higher speed (if messier) version of wrap
def wrap(txt, line_len = 76)
res = ""
sp = 0
ep = txt.length
while sp < ep
# scan back for a space
p = sp + line_len - 1
if p >= ep
p = ep
else
while p > sp and txt[p] != ?\s
p -= 1
end
if p <= sp
p = sp + line_len
while p < ep and txt[p] != ?\s
p += 1
end
end
end
res << txt[sp...p] << "\n"
sp = p
sp += 1 while sp < ep and txt[sp] == ?\s
end
res
end
#######################################################################
private
#######################################################################
def on_tags(res, item)
attr_mask = item.turn_on
return if attr_mask.zero?
@attr_tags.each do |tag|
if attr_mask & tag.bit != 0
res << annotate(tag.on)
end
end
end
def off_tags(res, item)
attr_mask = item.turn_off
return if attr_mask.zero?
@attr_tags.reverse_each do |tag|
if attr_mask & tag.bit != 0
res << annotate(tag.off)
end
end
end
def convert_flow(flow)
res = ""
flow.each do |item|
case item
when String
res << convert_string(item)
when AttrChanger
off_tags(res, item)
on_tags(res, item)
when Special
res << convert_special(item)
else
raise "Unknown flow element: #{item.inspect}"
end
end
res
end
# some of these patterns are taken from SmartyPants...
def convert_string(item)
CGI.escapeHTML(item).
# convert -- to em-dash, (-- to en-dash)
gsub(/---?/, '—'). #gsub(/--/, '–').
# convert ... to elipsis (and make sure .... becomes .<elipsis>)
gsub(/\.\.\.\./, '.…').gsub(/\.\.\./, '…').
# convert single closing quote
gsub(%r{([^ \t\r\n\[\{\(])\'}) { "#$1’" }.
gsub(%r{\'(?=\W|s\b)}) { "’" }.
# convert single opening quote
gsub(/'/, '‘').
# convert double closing quote
gsub(%r{([^ \t\r\n\[\{\(])\'(?=\W)}) { "#$1”" }.
# convert double opening quote
gsub(/'/, '“').
# convert copyright
gsub(/\(c\)/, '©').
# convert and registered trademark
gsub(/\(r\)/, '®')
end
def convert_special(special)
handled = false
Attribute.each_name_of(special.type) do |name|
method_name = "handle_special_#{name}"
if self.respond_to? method_name
special.text = send(method_name, special)
handled = true
end
end
raise "Unhandled special: #{special}" unless handled
special.text
end
def convert_heading(level, flow)
res =
annotate("<h#{level}>") +
convert_flow(flow) +
annotate("</h#{level}>\n")
end
def html_list_name(list_type, is_open_tag)
tags = LIST_TYPE_TO_HTML[list_type] || raise("Invalid list type: #{list_type.inspect}")
annotate(tags[ is_open_tag ? 0 : 1])
end
def list_item_start(am, fragment)
case fragment.type
when ListBase::BULLET, ListBase::NUMBER
annotate("<li>")
when ListBase::UPPERALPHA
annotate("<li type=\"A\">")
when ListBase::LOWERALPHA
annotate("<li type=\"a\">")
when ListBase::LABELED
annotate("<dt>") +
convert_flow(am.flow(fragment.param)) +
annotate("</dt>") +
annotate("<dd>")
when ListBase::NOTE
annotate("<tr>") +
annotate("<td valign=\"top\">") +
convert_flow(am.flow(fragment.param)) +
annotate("</td>") +
annotate("<td>")
else
raise "Invalid list type"
end
end
def list_end_for(fragment_type)
case fragment_type
when ListBase::BULLET, ListBase::NUMBER, ListBase::UPPERALPHA, ListBase::LOWERALPHA
"</li>"
when ListBase::LABELED
"</dd>"
when ListBase::NOTE
"</td></tr>"
else
raise "Invalid list type"
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rdoc/markup/simple_markup/preprocess.rb | tools/jruby-1.5.1/lib/ruby/1.8/rdoc/markup/simple_markup/preprocess.rb | module SM
##
# Handle common directives that can occur in a block of text:
#
# : include : filename
#
class PreProcess
def initialize(input_file_name, include_path)
@input_file_name = input_file_name
@include_path = include_path
end
# Look for common options in a chunk of text. Options that
# we don't handle are passed back to our caller
# as |directive, param|
def handle(text)
text.gsub!(/^([ \t#]*):(\w+):\s*(.+)?\n/) do
prefix = $1
directive = $2.downcase
param = $3
case directive
when "include"
filename = param.split[0]
include_file(filename, prefix)
else
yield(directive, param)
end
end
end
#######
private
#######
# Include a file, indenting it correctly
def include_file(name, indent)
if (full_name = find_include_file(name))
content = File.open(full_name) {|f| f.read}
# strip leading '#'s, but only if all lines start with them
if content =~ /^[^#]/
content.gsub(/^/, indent)
else
content.gsub(/^#?/, indent)
end
else
$stderr.puts "Couldn't find file to include: '#{name}'"
''
end
end
# Look for the given file in the directory containing the current
# file, and then in each of the directories specified in the
# RDOC_INCLUDE path
def find_include_file(name)
to_search = [ File.dirname(@input_file_name) ].concat @include_path
to_search.each do |dir|
full_name = File.join(dir, name)
stat = File.stat(full_name) rescue next
return full_name if stat.readable?
end
nil
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.