summaryrefslogtreecommitdiff
path: root/ruby_1_9_3/lib
diff options
context:
space:
mode:
Diffstat (limited to 'ruby_1_9_3/lib')
-rw-r--r--ruby_1_9_3/lib/English.rb155
-rw-r--r--ruby_1_9_3/lib/README91
-rw-r--r--ruby_1_9_3/lib/abbrev.rb102
-rw-r--r--ruby_1_9_3/lib/base64.rb91
-rw-r--r--ruby_1_9_3/lib/benchmark.rb569
-rw-r--r--ruby_1_9_3/lib/cgi.rb273
-rw-r--r--ruby_1_9_3/lib/cgi/cookie.rb164
-rw-r--r--ruby_1_9_3/lib/cgi/core.rb838
-rw-r--r--ruby_1_9_3/lib/cgi/html.rb1021
-rw-r--r--ruby_1_9_3/lib/cgi/session.rb531
-rw-r--r--ruby_1_9_3/lib/cgi/session/pstore.rb111
-rw-r--r--ruby_1_9_3/lib/cgi/util.rb194
-rw-r--r--ruby_1_9_3/lib/cmath.rb402
-rw-r--r--ruby_1_9_3/lib/complex.rb28
-rw-r--r--ruby_1_9_3/lib/csv.rb2356
-rw-r--r--ruby_1_9_3/lib/debug.rb907
-rw-r--r--ruby_1_9_3/lib/delegate.rb392
-rw-r--r--ruby_1_9_3/lib/drb.rb2
-rw-r--r--ruby_1_9_3/lib/drb/acl.rb250
-rw-r--r--ruby_1_9_3/lib/drb/drb.rb1774
-rw-r--r--ruby_1_9_3/lib/drb/eq.rb14
-rw-r--r--ruby_1_9_3/lib/drb/extserv.rb71
-rw-r--r--ruby_1_9_3/lib/drb/extservm.rb93
-rw-r--r--ruby_1_9_3/lib/drb/gw.rb122
-rw-r--r--ruby_1_9_3/lib/drb/invokemethod.rb34
-rw-r--r--ruby_1_9_3/lib/drb/observer.rb22
-rw-r--r--ruby_1_9_3/lib/drb/ssl.rb194
-rw-r--r--ruby_1_9_3/lib/drb/timeridconv.rb91
-rw-r--r--ruby_1_9_3/lib/drb/unix.rb108
-rw-r--r--ruby_1_9_3/lib/e2mmap.rb172
-rw-r--r--ruby_1_9_3/lib/erb.rb988
-rw-r--r--ruby_1_9_3/lib/fileutils.rb1706
-rw-r--r--ruby_1_9_3/lib/find.rb77
-rw-r--r--ruby_1_9_3/lib/forwardable.rb285
-rw-r--r--ruby_1_9_3/lib/getoptlong.rb612
-rw-r--r--ruby_1_9_3/lib/gserver.rb309
-rw-r--r--ruby_1_9_3/lib/ipaddr.rb924
-rw-r--r--ruby_1_9_3/lib/irb.rb352
-rw-r--r--ruby_1_9_3/lib/irb/cmd/chws.rb32
-rw-r--r--ruby_1_9_3/lib/irb/cmd/fork.rb38
-rw-r--r--ruby_1_9_3/lib/irb/cmd/help.rb39
-rw-r--r--ruby_1_9_3/lib/irb/cmd/load.rb66
-rw-r--r--ruby_1_9_3/lib/irb/cmd/nop.rb38
-rw-r--r--ruby_1_9_3/lib/irb/cmd/pushws.rb38
-rw-r--r--ruby_1_9_3/lib/irb/cmd/subirb.rb40
-rw-r--r--ruby_1_9_3/lib/irb/completion.rb233
-rw-r--r--ruby_1_9_3/lib/irb/context.rb295
-rw-r--r--ruby_1_9_3/lib/irb/ext/change-ws.rb61
-rw-r--r--ruby_1_9_3/lib/irb/ext/history.rb109
-rw-r--r--ruby_1_9_3/lib/irb/ext/loader.rb119
-rw-r--r--ruby_1_9_3/lib/irb/ext/math-mode.rb36
-rw-r--r--ruby_1_9_3/lib/irb/ext/multi-irb.rb242
-rw-r--r--ruby_1_9_3/lib/irb/ext/save-history.rb97
-rw-r--r--ruby_1_9_3/lib/irb/ext/tracer.rb60
-rw-r--r--ruby_1_9_3/lib/irb/ext/use-loader.rb64
-rw-r--r--ruby_1_9_3/lib/irb/ext/workspaces.rb55
-rw-r--r--ruby_1_9_3/lib/irb/extend-command.rb268
-rw-r--r--ruby_1_9_3/lib/irb/frame.rb66
-rw-r--r--ruby_1_9_3/lib/irb/help.rb35
-rw-r--r--ruby_1_9_3/lib/irb/init.rb305
-rw-r--r--ruby_1_9_3/lib/irb/input-method.rb142
-rw-r--r--ruby_1_9_3/lib/irb/inspector.rb109
-rw-r--r--ruby_1_9_3/lib/irb/lc/error.rb29
-rw-r--r--ruby_1_9_3/lib/irb/lc/help-message40
-rw-r--r--ruby_1_9_3/lib/irb/lc/ja/encoding_aliases.rb8
-rw-r--r--ruby_1_9_3/lib/irb/lc/ja/error.rb27
-rw-r--r--ruby_1_9_3/lib/irb/lc/ja/help-message41
-rw-r--r--ruby_1_9_3/lib/irb/locale.rb182
-rw-r--r--ruby_1_9_3/lib/irb/magic-file.rb37
-rw-r--r--ruby_1_9_3/lib/irb/notifier.rb144
-rw-r--r--ruby_1_9_3/lib/irb/output-method.rb69
-rw-r--r--ruby_1_9_3/lib/irb/ruby-lex.rb1187
-rw-r--r--ruby_1_9_3/lib/irb/ruby-token.rb265
-rw-r--r--ruby_1_9_3/lib/irb/slex.rb282
-rw-r--r--ruby_1_9_3/lib/irb/src_encoding.rb4
-rw-r--r--ruby_1_9_3/lib/irb/version.rb15
-rw-r--r--ruby_1_9_3/lib/irb/workspace.rb108
-rw-r--r--ruby_1_9_3/lib/irb/ws-for-case-2.rb14
-rw-r--r--ruby_1_9_3/lib/irb/xmp.rb97
-rw-r--r--ruby_1_9_3/lib/logger.rb801
-rw-r--r--ruby_1_9_3/lib/mathn.rb324
-rw-r--r--ruby_1_9_3/lib/matrix.rb1866
-rw-r--r--ruby_1_9_3/lib/matrix/eigenvalue_decomposition.rb886
-rw-r--r--ruby_1_9_3/lib/matrix/lup_decomposition.rb218
-rw-r--r--ruby_1_9_3/lib/minitest/README.txt269
-rw-r--r--ruby_1_9_3/lib/minitest/autorun.rb18
-rw-r--r--ruby_1_9_3/lib/minitest/benchmark.rb372
-rw-r--r--ruby_1_9_3/lib/minitest/mock.rb106
-rw-r--r--ruby_1_9_3/lib/minitest/pride.rb99
-rw-r--r--ruby_1_9_3/lib/minitest/spec.rb519
-rw-r--r--ruby_1_9_3/lib/minitest/unit.rb1169
-rw-r--r--ruby_1_9_3/lib/mkmf.rb2334
-rw-r--r--ruby_1_9_3/lib/monitor.rb300
-rw-r--r--ruby_1_9_3/lib/mutex_m.rb95
-rw-r--r--ruby_1_9_3/lib/net/.document8
-rw-r--r--ruby_1_9_3/lib/net/ftp.rb1043
-rw-r--r--ruby_1_9_3/lib/net/http.rb2825
-rw-r--r--ruby_1_9_3/lib/net/https.rb22
-rw-r--r--ruby_1_9_3/lib/net/imap.rb3676
-rw-r--r--ruby_1_9_3/lib/net/pop.rb1021
-rw-r--r--ruby_1_9_3/lib/net/protocol.rb404
-rw-r--r--ruby_1_9_3/lib/net/smtp.rb1057
-rw-r--r--ruby_1_9_3/lib/net/telnet.rb764
-rw-r--r--ruby_1_9_3/lib/observer.rb202
-rw-r--r--ruby_1_9_3/lib/open-uri.rb840
-rw-r--r--ruby_1_9_3/lib/open3.rb729
-rw-r--r--ruby_1_9_3/lib/optparse.rb1937
-rw-r--r--ruby_1_9_3/lib/optparse/date.rb17
-rw-r--r--ruby_1_9_3/lib/optparse/shellwords.rb6
-rw-r--r--ruby_1_9_3/lib/optparse/time.rb10
-rw-r--r--ruby_1_9_3/lib/optparse/uri.rb6
-rw-r--r--ruby_1_9_3/lib/optparse/version.rb70
-rw-r--r--ruby_1_9_3/lib/ostruct.rb236
-rw-r--r--ruby_1_9_3/lib/pp.rb524
-rw-r--r--ruby_1_9_3/lib/prettyprint.rb395
-rw-r--r--ruby_1_9_3/lib/prime.rb509
-rw-r--r--ruby_1_9_3/lib/profile.rb10
-rw-r--r--ruby_1_9_3/lib/profiler.rb59
-rw-r--r--ruby_1_9_3/lib/pstore.rb532
-rw-r--r--ruby_1_9_3/lib/racc/parser.rb443
-rw-r--r--ruby_1_9_3/lib/rake.rb69
-rw-r--r--ruby_1_9_3/lib/rake/alt_system.rb109
-rw-r--r--ruby_1_9_3/lib/rake/application.rb595
-rw-r--r--ruby_1_9_3/lib/rake/classic_namespace.rb11
-rw-r--r--ruby_1_9_3/lib/rake/clean.rb32
-rw-r--r--ruby_1_9_3/lib/rake/cloneable.rb25
-rw-r--r--ruby_1_9_3/lib/rake/contrib/compositepublisher.rb21
-rw-r--r--ruby_1_9_3/lib/rake/contrib/ftptools.rb150
-rw-r--r--ruby_1_9_3/lib/rake/contrib/publisher.rb73
-rw-r--r--ruby_1_9_3/lib/rake/contrib/rubyforgepublisher.rb16
-rw-r--r--ruby_1_9_3/lib/rake/contrib/sshpublisher.rb50
-rw-r--r--ruby_1_9_3/lib/rake/contrib/sys.rb191
-rw-r--r--ruby_1_9_3/lib/rake/default_loader.rb10
-rw-r--r--ruby_1_9_3/lib/rake/dsl_definition.rb176
-rw-r--r--ruby_1_9_3/lib/rake/early_time.rb18
-rw-r--r--ruby_1_9_3/lib/rake/ext/core.rb27
-rw-r--r--ruby_1_9_3/lib/rake/ext/module.rb39
-rw-r--r--ruby_1_9_3/lib/rake/ext/string.rb167
-rw-r--r--ruby_1_9_3/lib/rake/ext/time.rb14
-rw-r--r--ruby_1_9_3/lib/rake/file_creation_task.rb24
-rw-r--r--ruby_1_9_3/lib/rake/file_list.rb403
-rw-r--r--ruby_1_9_3/lib/rake/file_task.rb47
-rw-r--r--ruby_1_9_3/lib/rake/file_utils.rb114
-rw-r--r--ruby_1_9_3/lib/rake/file_utils_ext.rb145
-rw-r--r--ruby_1_9_3/lib/rake/gempackagetask.rb15
-rw-r--r--ruby_1_9_3/lib/rake/invocation_chain.rb51
-rw-r--r--ruby_1_9_3/lib/rake/invocation_exception_mixin.rb16
-rw-r--r--ruby_1_9_3/lib/rake/lib/project.rake21
-rw-r--r--ruby_1_9_3/lib/rake/loaders/makefile.rb40
-rw-r--r--ruby_1_9_3/lib/rake/multi_task.rb16
-rw-r--r--ruby_1_9_3/lib/rake/name_space.rb25
-rw-r--r--ruby_1_9_3/lib/rake/packagetask.rb185
-rw-r--r--ruby_1_9_3/lib/rake/pathmap.rb1
-rw-r--r--ruby_1_9_3/lib/rake/pseudo_status.rb24
-rw-r--r--ruby_1_9_3/lib/rake/rake_module.rb29
-rw-r--r--ruby_1_9_3/lib/rake/rake_test_loader.rb22
-rw-r--r--ruby_1_9_3/lib/rake/rdoctask.rb234
-rwxr-xr-xruby_1_9_3/lib/rake/ruby182_test_unit_fix.rb25
-rw-r--r--ruby_1_9_3/lib/rake/rule_recursion_overflow_error.rb20
-rw-r--r--ruby_1_9_3/lib/rake/runtest.rb21
-rw-r--r--ruby_1_9_3/lib/rake/task.rb327
-rw-r--r--ruby_1_9_3/lib/rake/task_argument_error.rb7
-rw-r--r--ruby_1_9_3/lib/rake/task_arguments.rb78
-rw-r--r--ruby_1_9_3/lib/rake/task_manager.rb307
-rw-r--r--ruby_1_9_3/lib/rake/tasklib.rb22
-rw-r--r--ruby_1_9_3/lib/rake/testtask.rb191
-rw-r--r--ruby_1_9_3/lib/rake/version.rb8
-rw-r--r--ruby_1_9_3/lib/rake/win32.rb55
-rw-r--r--ruby_1_9_3/lib/rational.rb23
-rw-r--r--ruby_1_9_3/lib/rbconfig/.document1
-rw-r--r--ruby_1_9_3/lib/rbconfig/datadir.rb13
-rw-r--r--ruby_1_9_3/lib/rbconfig/obsolete.rb5
-rw-r--r--ruby_1_9_3/lib/rdoc.rb147
-rw-r--r--ruby_1_9_3/lib/rdoc/alias.rb113
-rw-r--r--ruby_1_9_3/lib/rdoc/anon_class.rb12
-rw-r--r--ruby_1_9_3/lib/rdoc/any_method.rb207
-rw-r--r--ruby_1_9_3/lib/rdoc/attr.rb136
-rw-r--r--ruby_1_9_3/lib/rdoc/class_module.rb582
-rw-r--r--ruby_1_9_3/lib/rdoc/code_object.rb307
-rw-r--r--ruby_1_9_3/lib/rdoc/code_objects.rb23
-rw-r--r--ruby_1_9_3/lib/rdoc/constant.rb86
-rw-r--r--ruby_1_9_3/lib/rdoc/context.rb1191
-rw-r--r--ruby_1_9_3/lib/rdoc/cross_reference.rb173
-rw-r--r--ruby_1_9_3/lib/rdoc/encoding.rb92
-rw-r--r--ruby_1_9_3/lib/rdoc/erbio.rb37
-rw-r--r--ruby_1_9_3/lib/rdoc/generator.rb40
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/darkfish.rb390
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/markup.rb208
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/ri.rb86
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/.document0
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/classpage.rhtml321
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/filepage.rhtml124
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/brick.pngbin452 -> 0 bytes
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/brick_link.pngbin764 -> 0 bytes
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/bug.pngbin774 -> 0 bytes
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/bullet_black.pngbin211 -> 0 bytes
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/bullet_toggle_minus.pngbin207 -> 0 bytes
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/bullet_toggle_plus.pngbin209 -> 0 bytes
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/date.pngbin626 -> 0 bytes
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/find.pngbin659 -> 0 bytes
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/loadingAnimation.gifbin5886 -> 0 bytes
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/macFFBgHack.pngbin207 -> 0 bytes
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/package.pngbin853 -> 0 bytes
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/page_green.pngbin621 -> 0 bytes
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/page_white_text.pngbin342 -> 0 bytes
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/page_white_width.pngbin309 -> 0 bytes
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/plugin.pngbin591 -> 0 bytes
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/ruby.pngbin592 -> 0 bytes
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/tag_green.pngbin613 -> 0 bytes
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/wrench.pngbin610 -> 0 bytes
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/wrench_orange.pngbin584 -> 0 bytes
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/zoom.pngbin692 -> 0 bytes
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/index.rhtml64
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/js/darkfish.js118
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/js/jquery.js32
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/js/quicksearch.js114
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/js/thickbox-compressed.js10
-rw-r--r--ruby_1_9_3/lib/rdoc/generator/template/darkfish/rdoc.css763
-rw-r--r--ruby_1_9_3/lib/rdoc/ghost_method.rb8
-rw-r--r--ruby_1_9_3/lib/rdoc/include.rb100
-rw-r--r--ruby_1_9_3/lib/rdoc/known_classes.rb72
-rw-r--r--ruby_1_9_3/lib/rdoc/markup.rb652
-rw-r--r--ruby_1_9_3/lib/rdoc/markup/attribute_manager.rb335
-rw-r--r--ruby_1_9_3/lib/rdoc/markup/blank_line.rb27
-rw-r--r--ruby_1_9_3/lib/rdoc/markup/document.rb127
-rw-r--r--ruby_1_9_3/lib/rdoc/markup/formatter.rb169
-rw-r--r--ruby_1_9_3/lib/rdoc/markup/formatter_test_case.rb699
-rw-r--r--ruby_1_9_3/lib/rdoc/markup/heading.rb20
-rw-r--r--ruby_1_9_3/lib/rdoc/markup/indented_paragraph.rb33
-rw-r--r--ruby_1_9_3/lib/rdoc/markup/inline.rb144
-rw-r--r--ruby_1_9_3/lib/rdoc/markup/list.rb81
-rw-r--r--ruby_1_9_3/lib/rdoc/markup/list_item.rb86
-rw-r--r--ruby_1_9_3/lib/rdoc/markup/paragraph.rb14
-rw-r--r--ruby_1_9_3/lib/rdoc/markup/parser.rb497
-rw-r--r--ruby_1_9_3/lib/rdoc/markup/pre_process.rb227
-rw-r--r--ruby_1_9_3/lib/rdoc/markup/raw.rb69
-rw-r--r--ruby_1_9_3/lib/rdoc/markup/rule.rb20
-rw-r--r--ruby_1_9_3/lib/rdoc/markup/text_formatter_test_case.rb116
-rw-r--r--ruby_1_9_3/lib/rdoc/markup/to_ansi.rb84
-rw-r--r--ruby_1_9_3/lib/rdoc/markup/to_bs.rb80
-rw-r--r--ruby_1_9_3/lib/rdoc/markup/to_html.rb324
-rw-r--r--ruby_1_9_3/lib/rdoc/markup/to_html_crossref.rb120
-rw-r--r--ruby_1_9_3/lib/rdoc/markup/to_rdoc.rb301
-rw-r--r--ruby_1_9_3/lib/rdoc/markup/to_test.rb72
-rw-r--r--ruby_1_9_3/lib/rdoc/markup/to_tt_only.rb114
-rw-r--r--ruby_1_9_3/lib/rdoc/markup/verbatim.rb45
-rw-r--r--ruby_1_9_3/lib/rdoc/meta_method.rb8
-rw-r--r--ruby_1_9_3/lib/rdoc/method_attr.rb355
-rw-r--r--ruby_1_9_3/lib/rdoc/normal_class.rb71
-rw-r--r--ruby_1_9_3/lib/rdoc/normal_module.rb66
-rw-r--r--ruby_1_9_3/lib/rdoc/options.rb770
-rw-r--r--ruby_1_9_3/lib/rdoc/parser.rb208
-rw-r--r--ruby_1_9_3/lib/rdoc/parser/c.rb1047
-rw-r--r--ruby_1_9_3/lib/rdoc/parser/ruby.rb1782
-rw-r--r--ruby_1_9_3/lib/rdoc/parser/ruby_tools.rb162
-rw-r--r--ruby_1_9_3/lib/rdoc/parser/simple.rb49
-rw-r--r--ruby_1_9_3/lib/rdoc/rdoc.rb520
-rw-r--r--ruby_1_9_3/lib/rdoc/require.rb53
-rw-r--r--ruby_1_9_3/lib/rdoc/ri.rb18
-rw-r--r--ruby_1_9_3/lib/rdoc/ri/driver.rb1178
-rw-r--r--ruby_1_9_3/lib/rdoc/ri/formatter.rb5
-rw-r--r--ruby_1_9_3/lib/rdoc/ri/paths.rb128
-rw-r--r--ruby_1_9_3/lib/rdoc/ri/store.rb358
-rw-r--r--ruby_1_9_3/lib/rdoc/ruby_lex.rb1297
-rw-r--r--ruby_1_9_3/lib/rdoc/ruby_token.rb416
-rw-r--r--ruby_1_9_3/lib/rdoc/rubygems_hook.rb220
-rw-r--r--ruby_1_9_3/lib/rdoc/single_class.rb23
-rw-r--r--ruby_1_9_3/lib/rdoc/stats.rb438
-rw-r--r--ruby_1_9_3/lib/rdoc/stats/normal.rb48
-rw-r--r--ruby_1_9_3/lib/rdoc/stats/quiet.rb59
-rw-r--r--ruby_1_9_3/lib/rdoc/stats/verbose.rb45
-rw-r--r--ruby_1_9_3/lib/rdoc/task.rb326
-rw-r--r--ruby_1_9_3/lib/rdoc/text.rb302
-rw-r--r--ruby_1_9_3/lib/rdoc/token_stream.rb50
-rw-r--r--ruby_1_9_3/lib/rdoc/top_level.rb474
-rw-r--r--ruby_1_9_3/lib/resolv-replace.rb74
-rw-r--r--ruby_1_9_3/lib/resolv.rb2363
-rw-r--r--ruby_1_9_3/lib/rexml/attlistdecl.rb62
-rw-r--r--ruby_1_9_3/lib/rexml/attribute.rb188
-rw-r--r--ruby_1_9_3/lib/rexml/cdata.rb67
-rw-r--r--ruby_1_9_3/lib/rexml/child.rb96
-rw-r--r--ruby_1_9_3/lib/rexml/comment.rb80
-rw-r--r--ruby_1_9_3/lib/rexml/doctype.rb269
-rw-r--r--ruby_1_9_3/lib/rexml/document.rb248
-rw-r--r--ruby_1_9_3/lib/rexml/dtd/attlistdecl.rb10
-rw-r--r--ruby_1_9_3/lib/rexml/dtd/dtd.rb51
-rw-r--r--ruby_1_9_3/lib/rexml/dtd/elementdecl.rb17
-rw-r--r--ruby_1_9_3/lib/rexml/dtd/entitydecl.rb56
-rw-r--r--ruby_1_9_3/lib/rexml/dtd/notationdecl.rb39
-rw-r--r--ruby_1_9_3/lib/rexml/element.rb1245
-rw-r--r--ruby_1_9_3/lib/rexml/encoding.rb62
-rw-r--r--ruby_1_9_3/lib/rexml/entity.rb166
-rw-r--r--ruby_1_9_3/lib/rexml/formatters/default.rb111
-rw-r--r--ruby_1_9_3/lib/rexml/formatters/pretty.rb141
-rw-r--r--ruby_1_9_3/lib/rexml/formatters/transitive.rb57
-rw-r--r--ruby_1_9_3/lib/rexml/functions.rb394
-rw-r--r--ruby_1_9_3/lib/rexml/instruction.rb70
-rw-r--r--ruby_1_9_3/lib/rexml/light/node.rb195
-rw-r--r--ruby_1_9_3/lib/rexml/namespace.rb47
-rw-r--r--ruby_1_9_3/lib/rexml/node.rb75
-rw-r--r--ruby_1_9_3/lib/rexml/output.rb24
-rw-r--r--ruby_1_9_3/lib/rexml/parent.rb167
-rw-r--r--ruby_1_9_3/lib/rexml/parseexception.rb51
-rw-r--r--ruby_1_9_3/lib/rexml/parsers/baseparser.rb518
-rw-r--r--ruby_1_9_3/lib/rexml/parsers/lightparser.rb58
-rw-r--r--ruby_1_9_3/lib/rexml/parsers/pullparser.rb196
-rw-r--r--ruby_1_9_3/lib/rexml/parsers/sax2parser.rb247
-rw-r--r--ruby_1_9_3/lib/rexml/parsers/streamparser.rb46
-rw-r--r--ruby_1_9_3/lib/rexml/parsers/treeparser.rb100
-rw-r--r--ruby_1_9_3/lib/rexml/parsers/ultralightparser.rb56
-rw-r--r--ruby_1_9_3/lib/rexml/parsers/xpathparser.rb697
-rw-r--r--ruby_1_9_3/lib/rexml/quickpath.rb265
-rw-r--r--ruby_1_9_3/lib/rexml/rexml.rb43
-rw-r--r--ruby_1_9_3/lib/rexml/sax2listener.rb97
-rw-r--r--ruby_1_9_3/lib/rexml/source.rb267
-rw-r--r--ruby_1_9_3/lib/rexml/streamlistener.rb92
-rw-r--r--ruby_1_9_3/lib/rexml/syncenumerator.rb32
-rw-r--r--ruby_1_9_3/lib/rexml/text.rb415
-rw-r--r--ruby_1_9_3/lib/rexml/undefinednamespaceexception.rb8
-rw-r--r--ruby_1_9_3/lib/rexml/validation/relaxng.rb559
-rw-r--r--ruby_1_9_3/lib/rexml/validation/validation.rb155
-rw-r--r--ruby_1_9_3/lib/rexml/validation/validationexception.rb9
-rw-r--r--ruby_1_9_3/lib/rexml/xmldecl.rb119
-rw-r--r--ruby_1_9_3/lib/rexml/xmltokens.rb18
-rw-r--r--ruby_1_9_3/lib/rexml/xpath.rb80
-rw-r--r--ruby_1_9_3/lib/rexml/xpath_parser.rb803
-rw-r--r--ruby_1_9_3/lib/rinda/rinda.rb283
-rw-r--r--ruby_1_9_3/lib/rinda/ring.rb271
-rw-r--r--ruby_1_9_3/lib/rinda/tuplespace.rb642
-rw-r--r--ruby_1_9_3/lib/rss.rb91
-rw-r--r--ruby_1_9_3/lib/rss/0.9.rb428
-rw-r--r--ruby_1_9_3/lib/rss/1.0.rb452
-rw-r--r--ruby_1_9_3/lib/rss/2.0.rb111
-rw-r--r--ruby_1_9_3/lib/rss/atom.rb756
-rw-r--r--ruby_1_9_3/lib/rss/content.rb31
-rw-r--r--ruby_1_9_3/lib/rss/content/1.0.rb9
-rw-r--r--ruby_1_9_3/lib/rss/content/2.0.rb11
-rw-r--r--ruby_1_9_3/lib/rss/converter.rb170
-rw-r--r--ruby_1_9_3/lib/rss/dublincore.rb161
-rw-r--r--ruby_1_9_3/lib/rss/dublincore/1.0.rb12
-rw-r--r--ruby_1_9_3/lib/rss/dublincore/2.0.rb12
-rw-r--r--ruby_1_9_3/lib/rss/dublincore/atom.rb16
-rw-r--r--ruby_1_9_3/lib/rss/image.rb193
-rw-r--r--ruby_1_9_3/lib/rss/itunes.rb410
-rw-r--r--ruby_1_9_3/lib/rss/maker.rb54
-rw-r--r--ruby_1_9_3/lib/rss/maker/0.9.rb508
-rw-r--r--ruby_1_9_3/lib/rss/maker/1.0.rb435
-rw-r--r--ruby_1_9_3/lib/rss/maker/2.0.rb223
-rw-r--r--ruby_1_9_3/lib/rss/maker/atom.rb172
-rw-r--r--ruby_1_9_3/lib/rss/maker/base.rb944
-rw-r--r--ruby_1_9_3/lib/rss/maker/content.rb21
-rw-r--r--ruby_1_9_3/lib/rss/maker/dublincore.rb121
-rw-r--r--ruby_1_9_3/lib/rss/maker/entry.rb163
-rw-r--r--ruby_1_9_3/lib/rss/maker/feed.rb426
-rw-r--r--ruby_1_9_3/lib/rss/maker/image.rb111
-rw-r--r--ruby_1_9_3/lib/rss/maker/itunes.rb242
-rw-r--r--ruby_1_9_3/lib/rss/maker/slash.rb33
-rw-r--r--ruby_1_9_3/lib/rss/maker/syndication.rb18
-rw-r--r--ruby_1_9_3/lib/rss/maker/taxonomy.rb118
-rw-r--r--ruby_1_9_3/lib/rss/maker/trackback.rb61
-rw-r--r--ruby_1_9_3/lib/rss/parser.rb568
-rw-r--r--ruby_1_9_3/lib/rss/rexmlparser.rb54
-rw-r--r--ruby_1_9_3/lib/rss/rss.rb1342
-rw-r--r--ruby_1_9_3/lib/rss/slash.rb49
-rw-r--r--ruby_1_9_3/lib/rss/syndication.rb67
-rw-r--r--ruby_1_9_3/lib/rss/taxonomy.rb145
-rw-r--r--ruby_1_9_3/lib/rss/trackback.rb288
-rw-r--r--ruby_1_9_3/lib/rss/utils.rb111
-rw-r--r--ruby_1_9_3/lib/rss/xml-stylesheet.rb105
-rw-r--r--ruby_1_9_3/lib/rss/xml.rb71
-rw-r--r--ruby_1_9_3/lib/rss/xmlparser.rb93
-rw-r--r--ruby_1_9_3/lib/rss/xmlscanner.rb121
-rw-r--r--ruby_1_9_3/lib/rubygems.rb1305
-rw-r--r--ruby_1_9_3/lib/rubygems/builder.rb99
-rw-r--r--ruby_1_9_3/lib/rubygems/command.rb536
-rw-r--r--ruby_1_9_3/lib/rubygems/command_manager.rb194
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/build_command.rb59
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/cert_command.rb86
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/check_command.rb65
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/cleanup_command.rb100
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/contents_command.rb101
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/dependency_command.rb160
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/environment_command.rb130
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/fetch_command.rb78
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/generate_index_command.rb124
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/help_command.rb167
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/install_command.rb165
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/list_command.rb35
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/lock_command.rb110
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/outdated_command.rb30
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/owner_command.rb76
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/pristine_command.rb110
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/push_command.rb60
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/query_command.rb263
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/rdoc_command.rb91
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/search_command.rb31
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/server_command.rb86
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/setup_command.rb358
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/sources_command.rb136
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/specification_command.rb131
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/stale_command.rb28
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/uninstall_command.rb94
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/unpack_command.rb160
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/update_command.rb232
-rw-r--r--ruby_1_9_3/lib/rubygems/commands/which_command.rb82
-rw-r--r--ruby_1_9_3/lib/rubygems/config_file.rb375
-rw-r--r--ruby_1_9_3/lib/rubygems/custom_require.rb69
-rw-r--r--ruby_1_9_3/lib/rubygems/defaults.rb124
-rw-r--r--ruby_1_9_3/lib/rubygems/dependency.rb260
-rw-r--r--ruby_1_9_3/lib/rubygems/dependency_installer.rb304
-rw-r--r--ruby_1_9_3/lib/rubygems/dependency_list.rb252
-rw-r--r--ruby_1_9_3/lib/rubygems/deprecate.rb70
-rw-r--r--ruby_1_9_3/lib/rubygems/doc_manager.rb243
-rw-r--r--ruby_1_9_3/lib/rubygems/errors.rb35
-rw-r--r--ruby_1_9_3/lib/rubygems/exceptions.rb91
-rw-r--r--ruby_1_9_3/lib/rubygems/ext.rb18
-rw-r--r--ruby_1_9_3/lib/rubygems/ext/builder.rb56
-rw-r--r--ruby_1_9_3/lib/rubygems/ext/configure_builder.rb25
-rw-r--r--ruby_1_9_3/lib/rubygems/ext/ext_conf_builder.rb24
-rw-r--r--ruby_1_9_3/lib/rubygems/ext/rake_builder.rb39
-rw-r--r--ruby_1_9_3/lib/rubygems/format.rb82
-rw-r--r--ruby_1_9_3/lib/rubygems/gem_openssl.rb90
-rw-r--r--ruby_1_9_3/lib/rubygems/gem_path_searcher.rb172
-rw-r--r--ruby_1_9_3/lib/rubygems/gem_runner.rb86
-rw-r--r--ruby_1_9_3/lib/rubygems/gemcutter_utilities.rb82
-rw-r--r--ruby_1_9_3/lib/rubygems/indexer.rb644
-rw-r--r--ruby_1_9_3/lib/rubygems/install_update_options.rb128
-rw-r--r--ruby_1_9_3/lib/rubygems/installer.rb626
-rw-r--r--ruby_1_9_3/lib/rubygems/installer_test_case.rb144
-rw-r--r--ruby_1_9_3/lib/rubygems/local_remote_options.rb148
-rw-r--r--ruby_1_9_3/lib/rubygems/mock_gem_ui.rb71
-rw-r--r--ruby_1_9_3/lib/rubygems/old_format.rb153
-rw-r--r--ruby_1_9_3/lib/rubygems/package.rb83
-rw-r--r--ruby_1_9_3/lib/rubygems/package/f_sync_dir.rb23
-rw-r--r--ruby_1_9_3/lib/rubygems/package/tar_header.rb266
-rw-r--r--ruby_1_9_3/lib/rubygems/package/tar_input.rb235
-rw-r--r--ruby_1_9_3/lib/rubygems/package/tar_output.rb146
-rw-r--r--ruby_1_9_3/lib/rubygems/package/tar_reader.rb106
-rw-r--r--ruby_1_9_3/lib/rubygems/package/tar_reader/entry.rb145
-rw-r--r--ruby_1_9_3/lib/rubygems/package/tar_test_case.rb137
-rw-r--r--ruby_1_9_3/lib/rubygems/package/tar_writer.rb241
-rw-r--r--ruby_1_9_3/lib/rubygems/package_task.rb126
-rw-r--r--ruby_1_9_3/lib/rubygems/path_support.rb70
-rw-r--r--ruby_1_9_3/lib/rubygems/platform.rb194
-rw-r--r--ruby_1_9_3/lib/rubygems/psych_additions.rb18
-rw-r--r--ruby_1_9_3/lib/rubygems/psych_tree.rb54
-rw-r--r--ruby_1_9_3/lib/rubygems/remote_fetcher.rb507
-rw-r--r--ruby_1_9_3/lib/rubygems/require_paths_builder.rb18
-rw-r--r--ruby_1_9_3/lib/rubygems/requirement.rb204
-rw-r--r--ruby_1_9_3/lib/rubygems/security.rb826
-rw-r--r--ruby_1_9_3/lib/rubygems/server.rb832
-rw-r--r--ruby_1_9_3/lib/rubygems/source_index.rb406
-rw-r--r--ruby_1_9_3/lib/rubygems/spec_fetcher.rb297
-rw-r--r--ruby_1_9_3/lib/rubygems/specification.rb2171
-rw-r--r--ruby_1_9_3/lib/rubygems/ssl_certs/ca-bundle.pem3366
-rw-r--r--ruby_1_9_3/lib/rubygems/syck_hack.rb145
-rw-r--r--ruby_1_9_3/lib/rubygems/test_case.rb870
-rw-r--r--ruby_1_9_3/lib/rubygems/test_utilities.rb160
-rw-r--r--ruby_1_9_3/lib/rubygems/text.rb65
-rw-r--r--ruby_1_9_3/lib/rubygems/uninstaller.rb271
-rw-r--r--ruby_1_9_3/lib/rubygems/user_interaction.rb562
-rw-r--r--ruby_1_9_3/lib/rubygems/validator.rb169
-rw-r--r--ruby_1_9_3/lib/rubygems/version.rb329
-rw-r--r--ruby_1_9_3/lib/rubygems/version_option.rb65
-rw-r--r--ruby_1_9_3/lib/scanf.rb771
-rw-r--r--ruby_1_9_3/lib/securerandom.rb265
-rwxr-xr-xruby_1_9_3/lib/set.rb1352
-rw-r--r--ruby_1_9_3/lib/shell.rb300
-rw-r--r--ruby_1_9_3/lib/shell/builtin-command.rb160
-rw-r--r--ruby_1_9_3/lib/shell/command-processor.rb593
-rw-r--r--ruby_1_9_3/lib/shell/error.rb25
-rw-r--r--ruby_1_9_3/lib/shell/filter.rb109
-rw-r--r--ruby_1_9_3/lib/shell/process-controller.rb319
-rw-r--r--ruby_1_9_3/lib/shell/system-command.rb159
-rw-r--r--ruby_1_9_3/lib/shell/version.rb15
-rw-r--r--ruby_1_9_3/lib/shellwords.rb151
-rw-r--r--ruby_1_9_3/lib/singleton.rb172
-rw-r--r--ruby_1_9_3/lib/sync.rb321
-rw-r--r--ruby_1_9_3/lib/tempfile.rb359
-rw-r--r--ruby_1_9_3/lib/test/unit.rb640
-rw-r--r--ruby_1_9_3/lib/test/unit/assertions.rb324
-rw-r--r--ruby_1_9_3/lib/test/unit/parallel.rb161
-rw-r--r--ruby_1_9_3/lib/test/unit/testcase.rb25
-rw-r--r--ruby_1_9_3/lib/thread.rb361
-rw-r--r--ruby_1_9_3/lib/thwait.rb142
-rw-r--r--ruby_1_9_3/lib/time.rb541
-rw-r--r--ruby_1_9_3/lib/timeout.rb105
-rw-r--r--ruby_1_9_3/lib/tmpdir.rb143
-rw-r--r--ruby_1_9_3/lib/tracer.rb298
-rw-r--r--ruby_1_9_3/lib/tsort.rb242
-rw-r--r--ruby_1_9_3/lib/ubygems.rb10
-rw-r--r--ruby_1_9_3/lib/un.rb348
-rw-r--r--ruby_1_9_3/lib/uri.rb111
-rw-r--r--ruby_1_9_3/lib/uri/common.rb1001
-rw-r--r--ruby_1_9_3/lib/uri/ftp.rb262
-rw-r--r--ruby_1_9_3/lib/uri/generic.rb1599
-rw-r--r--ruby_1_9_3/lib/uri/http.rb106
-rw-r--r--ruby_1_9_3/lib/uri/https.rb22
-rw-r--r--ruby_1_9_3/lib/uri/ldap.rb260
-rw-r--r--ruby_1_9_3/lib/uri/ldaps.rb20
-rw-r--r--ruby_1_9_3/lib/uri/mailto.rb280
-rw-r--r--ruby_1_9_3/lib/weakref.rb94
-rw-r--r--ruby_1_9_3/lib/webrick.rb227
-rw-r--r--ruby_1_9_3/lib/webrick/accesslog.rb151
-rw-r--r--ruby_1_9_3/lib/webrick/cgi.rb260
-rw-r--r--ruby_1_9_3/lib/webrick/compat.rb35
-rw-r--r--ruby_1_9_3/lib/webrick/config.rb121
-rw-r--r--ruby_1_9_3/lib/webrick/cookie.rb110
-rw-r--r--ruby_1_9_3/lib/webrick/htmlutils.rb28
-rw-r--r--ruby_1_9_3/lib/webrick/httpauth.rb95
-rw-r--r--ruby_1_9_3/lib/webrick/httpauth/authenticator.rb112
-rw-r--r--ruby_1_9_3/lib/webrick/httpauth/basicauth.rb108
-rw-r--r--ruby_1_9_3/lib/webrick/httpauth/digestauth.rb392
-rw-r--r--ruby_1_9_3/lib/webrick/httpauth/htdigest.rb128
-rw-r--r--ruby_1_9_3/lib/webrick/httpauth/htgroup.rb93
-rw-r--r--ruby_1_9_3/lib/webrick/httpauth/htpasswd.rb121
-rw-r--r--ruby_1_9_3/lib/webrick/httpauth/userdb.rb52
-rw-r--r--ruby_1_9_3/lib/webrick/httpproxy.rb305
-rw-r--r--ruby_1_9_3/lib/webrick/httprequest.rb461
-rw-r--r--ruby_1_9_3/lib/webrick/httpresponse.rb399
-rw-r--r--ruby_1_9_3/lib/webrick/https.rb64
-rw-r--r--ruby_1_9_3/lib/webrick/httpserver.rb264
-rw-r--r--ruby_1_9_3/lib/webrick/httpservlet.rb22
-rw-r--r--ruby_1_9_3/lib/webrick/httpservlet/abstract.rb153
-rw-r--r--ruby_1_9_3/lib/webrick/httpservlet/cgi_runner.rb46
-rw-r--r--ruby_1_9_3/lib/webrick/httpservlet/cgihandler.rb108
-rw-r--r--ruby_1_9_3/lib/webrick/httpservlet/erbhandler.rb87
-rw-r--r--ruby_1_9_3/lib/webrick/httpservlet/filehandler.rb470
-rw-r--r--ruby_1_9_3/lib/webrick/httpservlet/prochandler.rb33
-rw-r--r--ruby_1_9_3/lib/webrick/httpstatus.rb184
-rw-r--r--ruby_1_9_3/lib/webrick/httputils.rb392
-rw-r--r--ruby_1_9_3/lib/webrick/httpversion.rb49
-rw-r--r--ruby_1_9_3/lib/webrick/log.rb136
-rw-r--r--ruby_1_9_3/lib/webrick/server.rb218
-rw-r--r--ruby_1_9_3/lib/webrick/ssl.rb127
-rw-r--r--ruby_1_9_3/lib/webrick/utils.rb241
-rw-r--r--ruby_1_9_3/lib/webrick/version.rb13
-rw-r--r--ruby_1_9_3/lib/xmlrpc/README.rdoc300
-rw-r--r--ruby_1_9_3/lib/xmlrpc/README.txt31
-rw-r--r--ruby_1_9_3/lib/xmlrpc/base64.rb81
-rw-r--r--ruby_1_9_3/lib/xmlrpc/client.rb625
-rw-r--r--ruby_1_9_3/lib/xmlrpc/config.rb40
-rw-r--r--ruby_1_9_3/lib/xmlrpc/create.rb289
-rw-r--r--ruby_1_9_3/lib/xmlrpc/datetime.rb142
-rw-r--r--ruby_1_9_3/lib/xmlrpc/httpserver.rb178
-rw-r--r--ruby_1_9_3/lib/xmlrpc/marshal.rb76
-rw-r--r--ruby_1_9_3/lib/xmlrpc/parser.rb812
-rw-r--r--ruby_1_9_3/lib/xmlrpc/server.rb778
-rw-r--r--ruby_1_9_3/lib/xmlrpc/utils.rb165
-rw-r--r--ruby_1_9_3/lib/yaml.rb76
-rw-r--r--ruby_1_9_3/lib/yaml/dbm.rb214
-rw-r--r--ruby_1_9_3/lib/yaml/store.rb86
552 files changed, 0 insertions, 139970 deletions
diff --git a/ruby_1_9_3/lib/English.rb b/ruby_1_9_3/lib/English.rb
deleted file mode 100644
index 4fd53c5ec6..0000000000
--- a/ruby_1_9_3/lib/English.rb
+++ /dev/null
@@ -1,155 +0,0 @@
-# Include the English library file in a Ruby script, and you can
-# reference the global variables such as \VAR{\$\_} using less
-# cryptic names, listed in the following table.% \vref{tab:english}.
-#
-# Without 'English':
-#
-# $\ = ' -- '
-# "waterbuffalo" =~ /buff/
-# print $", $', $$, "\n"
-#
-# With English:
-#
-# require "English"
-#
-# $OUTPUT_FIELD_SEPARATOR = ' -- '
-# "waterbuffalo" =~ /buff/
-# print $LOADED_FEATURES, $POSTMATCH, $PID, "\n"
-
-
-# The exception object passed to +raise+.
-alias $ERROR_INFO $!
-
-# The stack backtrace generated by the last
-# exception. <tt>See Kernel.caller</tt> for details. Thread local.
-alias $ERROR_POSITION $@
-
-# The default separator pattern used by <tt>String.split</tt>. May be
-# set from the command line using the <tt>-F</tt> flag.
-alias $FS $;
-
-# The default separator pattern used by <tt>String.split</tt>. May be
-# set from the command line using the <tt>-F</tt> flag.
-alias $FIELD_SEPARATOR $;
-
-# The separator string output between the parameters to methods such
-# as <tt>Kernel.print</tt> and <tt>Array.join</tt>. Defaults to +nil+,
-# which adds no text.
-alias $OFS $,
-
-# The separator string output between the parameters to methods such
-# as <tt>Kernel.print</tt> and <tt>Array.join</tt>. Defaults to +nil+,
-# which adds no text.
-alias $OUTPUT_FIELD_SEPARATOR $,
-
-# The input record separator (newline by default). This is the value
-# that routines such as <tt>Kernel.gets</tt> use to determine record
-# boundaries. If set to +nil+, +gets+ will read the entire file.
-alias $RS $/
-
-# The input record separator (newline by default). This is the value
-# that routines such as <tt>Kernel.gets</tt> use to determine record
-# boundaries. If set to +nil+, +gets+ will read the entire file.
-alias $INPUT_RECORD_SEPARATOR $/
-
-# The string appended to the output of every call to methods such as
-# <tt>Kernel.print</tt> and <tt>IO.write</tt>. The default value is
-# +nil+.
-alias $ORS $\
-
-# The string appended to the output of every call to methods such as
-# <tt>Kernel.print</tt> and <tt>IO.write</tt>. The default value is
-# +nil+.
-alias $OUTPUT_RECORD_SEPARATOR $\
-
-# The number of the last line read from the current input file.
-alias $INPUT_LINE_NUMBER $.
-
-# The number of the last line read from the current input file.
-alias $NR $.
-
-# The last line read by <tt>Kernel.gets</tt> or
-# <tt>Kernel.readline</tt>. Many string-related functions in the
-# +Kernel+ module operate on <tt>$_</tt> by default. The variable is
-# local to the current scope. Thread local.
-alias $LAST_READ_LINE $_
-
-# The destination of output for <tt>Kernel.print</tt>
-# and <tt>Kernel.printf</tt>. The default value is
-# <tt>$stdout</tt>.
-alias $DEFAULT_OUTPUT $>
-
-# An object that provides access to the concatenation
-# of the contents of all the files
-# given as command-line arguments, or <tt>$stdin</tt>
-# (in the case where there are no
-# arguments). <tt>$<</tt> supports methods similar to a
-# +File+ object:
-# +inmode+, +close+,
-# <tt>closed?</tt>, +each+,
-# <tt>each_byte</tt>, <tt>each_line</tt>,
-# +eof+, <tt>eof?</tt>, +file+,
-# +filename+, +fileno+,
-# +getc+, +gets+, +lineno+,
-# <tt>lineno=</tt>, +path+,
-# +pos+, <tt>pos=</tt>,
-# +read+, +readchar+,
-# +readline+, +readlines+,
-# +rewind+, +seek+, +skip+,
-# +tell+, <tt>to_a</tt>, <tt>to_i</tt>,
-# <tt>to_io</tt>, <tt>to_s</tt>, along with the
-# methods in +Enumerable+. The method +file+
-# returns a +File+ object for the file currently
-# being read. This may change as <tt>$<</tt> reads
-# through the files on the command line. Read only.
-alias $DEFAULT_INPUT $<
-
-# The process number of the program being executed. Read only.
-alias $PID $$
-
-# The process number of the program being executed. Read only.
-alias $PROCESS_ID $$
-
-# The exit status of the last child process to terminate. Read
-# only. Thread local.
-alias $CHILD_STATUS $?
-
-# A +MatchData+ object that encapsulates the results of a successful
-# pattern match. The variables <tt>$&</tt>, <tt>$`</tt>, <tt>$'</tt>,
-# and <tt>$1</tt> to <tt>$9</tt> are all derived from
-# <tt>$~</tt>. Assigning to <tt>$~</tt> changes the values of these
-# derived variables. This variable is local to the current
-# scope. Thread local.
-alias $LAST_MATCH_INFO $~
-
-# If set to any value apart from +nil+ or +false+, all pattern matches
-# will be case insensitive, string comparisons will ignore case, and
-# string hash values will be case insensitive. Deprecated
-alias $IGNORECASE $=
-
-# An array of strings containing the command-line
-# options from the invocation of the program. Options
-# used by the Ruby interpreter will have been
-# removed. Read only. Also known simply as +ARGV+.
-alias $ARGV $*
-
-# The string matched by the last successful pattern
-# match. This variable is local to the current
-# scope. Read only. Thread local.
-alias $MATCH $&
-
-# The string preceding the match in the last
-# successful pattern match. This variable is local to
-# the current scope. Read only. Thread local.
-alias $PREMATCH $`
-
-# The string following the match in the last
-# successful pattern match. This variable is local to
-# the current scope. Read only. Thread local.
-alias $POSTMATCH $'
-
-# The contents of the highest-numbered group matched in the last
-# successful pattern match. Thus, in <tt>"cat" =~ /(c|a)(t|z)/</tt>,
-# <tt>$+</tt> will be set to "t". This variable is local to the
-# current scope. Read only. Thread local.
-alias $LAST_PAREN_MATCH $+
diff --git a/ruby_1_9_3/lib/README b/ruby_1_9_3/lib/README
deleted file mode 100644
index cfe7145307..0000000000
--- a/ruby_1_9_3/lib/README
+++ /dev/null
@@ -1,91 +0,0 @@
-English.rb lets Perl'ish global variables have English names
-README this file
-abbrev.rb abbreviation calculator
-base64.rb Base64 de- and encoder
-benchmark.rb a benchmark utility
-cgi.rb CGI support library
-cgi/session.rb CGI session class
-cmath.rb math support for complex numbers
-complex.rb includes cmath and set complex arithemtic as default (obsolete)
-csv.rb CSV parser/generator
-debug.rb ruby debugger
-delegate.rb delegates messages to other object
-drb.rb distributed Ruby
-e2mmap.rb exception utilities
-erb.rb tiny eRuby library
-fileutils.rb file utilities
-find.rb traverses directory tree
-forwardable.rb explicit delegation library
-gauntlet_rubygems.rb Gem package validator
-getoptlong.rb GNU getoptlong compatible
-gserver.rb general TCP server
-ipaddr.rb defines the IPAddr class
-irb.rb interactive ruby
-logger.rb simple logging utility
-mathn.rb extended math operation (obsolete)
-matrix.rb matrix calculation library
-minitest/unit minimal drop-in replacement for test-unit
-mkmf.rb Makefile maker
-monitor.rb exclusive region monitor for thread
-mutex_m.rb mutex mixin
-net/ftp.rb ftp access
-net/http.rb HTTP access
-net/https.rb HTTPS access
-net/imap.rb IMAP4 access
-net/pop.rb POP3 access
-net/protocol.rb abstract class for net library (DO NOT USE)
-net/smtp.rb SMTP access
-net/telnet.rb telnet library
-observer.rb observer desing pattern library (provides Observable)
-open-uri.rb easy-to-use network interface using URI and Net
-open3.rb opens subprocess connection stdin/stdout/stderr
-optparse.rb command line option analysis
-ostruct.rb python style object
-pathname.rb Object-Oriented Pathname Class
-pp.rb pretty print objects
-prettyprint.rb pretty printing algorithm
-prime.rb prime numbers and factorization
-profile.rb runs ruby profiler
-profiler.rb ruby profiler module
-pstore.rb persistent object strage using marshal
-racc/parser.rb racc (Ruby yACC) runtime
-rake.rb Ruby Make
-rational.rb rational number support (obsolete)
-rdoc source-code documentation tool
-resolv-replace.rb replace Socket DNS by resolve.rb
-resolv.rb DNS resolver in Ruby
-rexml an XML parser for Ruby, in Ruby
-rinda/rinda.rb Linda distributed computing paradigm for drb
-rinda/ring.rb RingServer for tuplespace
-rinda/tuplespace.rb tuplespace for drb
-rss.rb RSS parser/generator
-rubygems Ruby package management system
-scanf.rb scanf for Ruby
-securerandom.rb Secure random number generator interface
-set.rb defines the Set class
-shell.rb runs commands and does pipeline operations like shell
-shellwords.rb split into words like shell
-singleton.rb singleton design pattern library
-sync.rb 2 phase lock
-tempfile.rb temporary file with automatic removal
-test/unit Ruby Unit Testing Framework
-thread.rb thread support
-thwait.rb thread syncronization class
-time.rb RFC2822, RFC2616, ISO8601 style time formatting/parsing
-timeout.rb provides timeout
-tmpdir.rb retrieve temporary directory path
-tracer.rb execution tracer
-tsort.rb topological sorting
-ubygems.rb command line shortcut for RubyGems
-un.rb Utilities to replace common UNIX commands in Makefiles etc
-uri.rb URI support
-uri/ftp.rb ftp scheme support
-uri/http.rb http scheme support
-uri/https.rb https scheme support
-uri/ldap.rb ldap scheme support
-uri/ldaps.rb ldaps scheme support
-uri/mailto.rb mailto scheme support
-weakref.rb weak reference class
-webrick.rb WEB server toolkit
-xmlrpc XML-RPC implementation
-yaml.rb YAML implementation
diff --git a/ruby_1_9_3/lib/abbrev.rb b/ruby_1_9_3/lib/abbrev.rb
deleted file mode 100644
index aa7e33a65d..0000000000
--- a/ruby_1_9_3/lib/abbrev.rb
+++ /dev/null
@@ -1,102 +0,0 @@
-#!/usr/bin/env ruby
-#--
-# Copyright (c) 2001,2003 Akinori MUSHA <knu@iDaemons.org>
-#
-# All rights reserved. You can redistribute and/or modify it under
-# the same terms as Ruby.
-#
-# $Idaemons: /home/cvs/rb/abbrev.rb,v 1.2 2001/05/30 09:37:45 knu Exp $
-# $RoughId: abbrev.rb,v 1.4 2003/10/14 19:45:42 knu Exp $
-# $Id$
-#++
-
-# Calculate the set of unique abbreviations for a given set of strings.
-#
-# require 'abbrev'
-# require 'pp'
-#
-# pp Abbrev::abbrev(['ruby', 'rules']).sort
-#
-# <i>Generates:</i>
-#
-# [["rub", "ruby"],
-# ["ruby", "ruby"],
-# ["rul", "rules"],
-# ["rule", "rules"],
-# ["rules", "rules"]]
-#
-# Also adds an +abbrev+ method to class +Array+.
-
-module Abbrev
-
- # Given a set of strings, calculate the set of unambiguous
- # abbreviations for those strings, and return a hash where the keys
- # are all the possible abbreviations and the values are the full
- # strings. Thus, given input of "car" and "cone", the keys pointing
- # to "car" would be "ca" and "car", while those pointing to "cone"
- # would be "co", "con", and "cone".
- #
- # The optional +pattern+ parameter is a pattern or a string. Only
- # those input strings matching the pattern, or begging the string,
- # are considered for inclusion in the output hash
-
- def abbrev(words, pattern = nil)
- table = {}
- seen = Hash.new(0)
-
- if pattern.is_a?(String)
- pattern = /^#{Regexp.quote(pattern)}/ # regard as a prefix
- end
-
- words.each do |word|
- next if (abbrev = word).empty?
- while (len = abbrev.rindex(/[\w\W]\z/)) > 0
- abbrev = word[0,len]
-
- next if pattern && pattern !~ abbrev
-
- case seen[abbrev] += 1
- when 1
- table[abbrev] = word
- when 2
- table.delete(abbrev)
- else
- break
- end
- end
- end
-
- words.each do |word|
- next if pattern && pattern !~ word
-
- table[word] = word
- end
-
- table
- end
-
- module_function :abbrev
-end
-
-class Array
- # Calculates the set of unambiguous abbreviations for the strings in
- # +self+. If passed a pattern or a string, only the strings matching
- # the pattern or starting with the string are considered.
- #
- # %w{ car cone }.abbrev #=> { "ca" => "car", "car" => "car",
- # "co" => "cone", "con" => cone",
- # "cone" => "cone" }
- def abbrev(pattern = nil)
- Abbrev::abbrev(self, pattern)
- end
-end
-
-if $0 == __FILE__
- while line = gets
- hash = line.split.abbrev
-
- hash.sort.each do |k, v|
- puts "#{k} => #{v}"
- end
- end
-end
diff --git a/ruby_1_9_3/lib/base64.rb b/ruby_1_9_3/lib/base64.rb
deleted file mode 100644
index a240b730b4..0000000000
--- a/ruby_1_9_3/lib/base64.rb
+++ /dev/null
@@ -1,91 +0,0 @@
-#
-# = base64.rb: methods for base64-encoding and -decoding strings
-#
-
-# The Base64 module provides for the encoding (#encode64, #strict_encode64,
-# #urlsafe_encode64) and decoding (#decode64, #strict_decode64,
-# #urlsafe_decode64) of binary data using a Base64 representation.
-#
-# == Example
-#
-# A simple encoding and decoding.
-#
-# require "base64"
-#
-# enc = Base64.encode64('Send reinforcements')
-# # -> "U2VuZCByZWluZm9yY2VtZW50cw==\n"
-# plain = Base64.decode64(enc)
-# # -> "Send reinforcements"
-#
-# The purpose of using base64 to encode data is that it translates any
-# binary data into purely printable characters.
-
-module Base64
- module_function
-
- # Returns the Base64-encoded version of +bin+.
- # This method complies with RFC 2045.
- # Line feeds are added to every 60 encoded charactors.
- #
- # require 'base64'
- # Base64.encode64("Now is the time for all good coders\nto learn Ruby")
- #
- # <i>Generates:</i>
- #
- # Tm93IGlzIHRoZSB0aW1lIGZvciBhbGwgZ29vZCBjb2RlcnMKdG8gbGVhcm4g
- # UnVieQ==
- def encode64(bin)
- [bin].pack("m")
- end
-
- # Returns the Base64-decoded version of +str+.
- # This method complies with RFC 2045.
- # Characters outside the base alphabet are ignored.
- #
- # require 'base64'
- # str = 'VGhpcyBpcyBsaW5lIG9uZQpUaGlzIG' +
- # 'lzIGxpbmUgdHdvClRoaXMgaXMgbGlu' +
- # 'ZSB0aHJlZQpBbmQgc28gb24uLi4K'
- # puts Base64.decode64(str)
- #
- # <i>Generates:</i>
- #
- # This is line one
- # This is line two
- # This is line three
- # And so on...
- def decode64(str)
- str.unpack("m").first
- end
-
- # Returns the Base64-encoded version of +bin+.
- # This method complies with RFC 4648.
- # No line feeds are added.
- def strict_encode64(bin)
- [bin].pack("m0")
- end
-
- # Returns the Base64-decoded version of +str+.
- # This method complies with RFC 4648.
- # ArgumentError is raised if +str+ is incorrectly padded or contains
- # non-alphabet characters. Note that CR or LF are also rejected.
- def strict_decode64(str)
- str.unpack("m0").first
- end
-
- # Returns the Base64-encoded version of +bin+.
- # This method complies with ``Base 64 Encoding with URL and Filename Safe
- # Alphabet'' in RFC 4648.
- # The alphabet uses '-' instead of '+' and '_' instead of '/'.
- def urlsafe_encode64(bin)
- strict_encode64(bin).tr("+/", "-_")
- end
-
- # Returns the Base64-decoded version of +str+.
- # This method complies with ``Base 64 Encoding with URL and Filename Safe
- # Alphabet'' in RFC 4648.
- # The alphabet uses '-' instead of '+' and '_' instead of '/'.
- def urlsafe_decode64(str)
- strict_decode64(str.tr("-_", "+/"))
- end
-end
diff --git a/ruby_1_9_3/lib/benchmark.rb b/ruby_1_9_3/lib/benchmark.rb
deleted file mode 100644
index 6a00da1359..0000000000
--- a/ruby_1_9_3/lib/benchmark.rb
+++ /dev/null
@@ -1,569 +0,0 @@
-#--
-# benchmark.rb - a performance benchmarking library
-#
-# $Id$
-#
-# Created by Gotoken (gotoken@notwork.org).
-#
-# Documentation by Gotoken (original RD), Lyle Johnson (RDoc conversion), and
-# Gavin Sinclair (editing).
-#++
-#
-# == Overview
-#
-# The Benchmark module provides methods for benchmarking Ruby code, giving
-# detailed reports on the time taken for each task.
-#
-
-# The Benchmark module provides methods to measure and report the time
-# used to execute Ruby code.
-#
-# * Measure the time to construct the string given by the expression
-# <tt>"a"*1_000_000</tt>:
-#
-# require 'benchmark'
-#
-# puts Benchmark.measure { "a"*1_000_000 }
-#
-# On my machine (FreeBSD 3.2 on P5, 100MHz) this generates:
-#
-# 1.166667 0.050000 1.216667 ( 0.571355)
-#
-# This report shows the user CPU time, system CPU time, the sum of
-# the user and system CPU times, and the elapsed real time. The unit
-# of time is seconds.
-#
-# * Do some experiments sequentially using the #bm method:
-#
-# require 'benchmark'
-#
-# n = 50000
-# Benchmark.bm do |x|
-# x.report { for i in 1..n; a = "1"; end }
-# x.report { n.times do ; a = "1"; end }
-# x.report { 1.upto(n) do ; a = "1"; end }
-# end
-#
-# The result:
-#
-# user system total real
-# 1.033333 0.016667 1.016667 ( 0.492106)
-# 1.483333 0.000000 1.483333 ( 0.694605)
-# 1.516667 0.000000 1.516667 ( 0.711077)
-#
-# * Continuing the previous example, put a label in each report:
-#
-# require 'benchmark'
-#
-# n = 50000
-# Benchmark.bm(7) do |x|
-# x.report("for:") { for i in 1..n; a = "1"; end }
-# x.report("times:") { n.times do ; a = "1"; end }
-# x.report("upto:") { 1.upto(n) do ; a = "1"; end }
-# end
-#
-# The result:
-#
-# user system total real
-# for: 1.050000 0.000000 1.050000 ( 0.503462)
-# times: 1.533333 0.016667 1.550000 ( 0.735473)
-# upto: 1.500000 0.016667 1.516667 ( 0.711239)
-#
-#
-# * The times for some benchmarks depend on the order in which items
-# are run. These differences are due to the cost of memory
-# allocation and garbage collection. To avoid these discrepancies,
-# the #bmbm method is provided. For example, to compare ways to
-# sort an array of floats:
-#
-# require 'benchmark'
-#
-# array = (1..1000000).map { rand }
-#
-# Benchmark.bmbm do |x|
-# x.report("sort!") { array.dup.sort! }
-# x.report("sort") { array.dup.sort }
-# end
-#
-# The result:
-#
-# Rehearsal -----------------------------------------
-# sort! 11.928000 0.010000 11.938000 ( 12.756000)
-# sort 13.048000 0.020000 13.068000 ( 13.857000)
-# ------------------------------- total: 25.006000sec
-#
-# user system total real
-# sort! 12.959000 0.010000 12.969000 ( 13.793000)
-# sort 12.007000 0.000000 12.007000 ( 12.791000)
-#
-#
-# * Report statistics of sequential experiments with unique labels,
-# using the #benchmark method:
-#
-# require 'benchmark'
-# include Benchmark # we need the CAPTION and FORMAT constants
-#
-# n = 50000
-# Benchmark.benchmark(CAPTION, 7, FORMAT, ">total:", ">avg:") do |x|
-# tf = x.report("for:") { for i in 1..n; a = "1"; end }
-# tt = x.report("times:") { n.times do ; a = "1"; end }
-# tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end }
-# [tf+tt+tu, (tf+tt+tu)/3]
-# end
-#
-# The result:
-#
-# user system total real
-# for: 1.016667 0.016667 1.033333 ( 0.485749)
-# times: 1.450000 0.016667 1.466667 ( 0.681367)
-# upto: 1.533333 0.000000 1.533333 ( 0.722166)
-# >total: 4.000000 0.033333 4.033333 ( 1.889282)
-# >avg: 1.333333 0.011111 1.344444 ( 0.629761)
-
-module Benchmark
-
- BENCHMARK_VERSION = "2002-04-25" #:nodoc"
-
- # Invokes the block with a <tt>Benchmark::Report</tt> object, which
- # may be used to collect and report on the results of individual
- # benchmark tests. Reserves <i>label_width</i> leading spaces for
- # labels on each line. Prints _caption_ at the top of the
- # report, and uses _format_ to format each line.
- # Returns an array of Benchmark::Tms objects.
- #
- # If the block returns an array of
- # <tt>Benchmark::Tms</tt> objects, these will be used to format
- # additional lines of output. If _label_ parameters are
- # given, these are used to label these extra lines.
- #
- # _Note_: Other methods provide a simpler interface to this one, and are
- # suitable for nearly all benchmarking requirements. See the examples in
- # Benchmark, and the #bm and #bmbm methods.
- #
- # Example:
- #
- # require 'benchmark'
- # include Benchmark # we need the CAPTION and FORMAT constants
- #
- # n = 50000
- # Benchmark.benchmark(CAPTION, 7, FORMAT, ">total:", ">avg:") do |x|
- # tf = x.report("for:") { for i in 1..n; a = "1"; end }
- # tt = x.report("times:") { n.times do ; a = "1"; end }
- # tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end }
- # [tf+tt+tu, (tf+tt+tu)/3]
- # end
- #
- # <i>Generates:</i>
- #
- # user system total real
- # for: 1.016667 0.016667 1.033333 ( 0.485749)
- # times: 1.450000 0.016667 1.466667 ( 0.681367)
- # upto: 1.533333 0.000000 1.533333 ( 0.722166)
- # >total: 4.000000 0.033333 4.033333 ( 1.889282)
- # >avg: 1.333333 0.011111 1.344444 ( 0.629761)
- #
-
- def benchmark(caption = "", label_width = nil, format = nil, *labels) # :yield: report
- sync = STDOUT.sync
- STDOUT.sync = true
- label_width ||= 0
- label_width += 1
- format ||= FORMAT
- print ' '*label_width + caption
- report = Report.new(label_width, format)
- results = yield(report)
- Array === results and results.grep(Tms).each {|t|
- print((labels.shift || t.label || "").ljust(label_width), t.format(format))
- }
- report.list
- ensure
- STDOUT.sync = sync unless sync.nil?
- end
-
-
- # A simple interface to the #benchmark method, #bm is generates sequential reports
- # with labels. The parameters have the same meaning as for #benchmark.
- #
- # require 'benchmark'
- #
- # n = 50000
- # Benchmark.bm(7) do |x|
- # x.report("for:") { for i in 1..n; a = "1"; end }
- # x.report("times:") { n.times do ; a = "1"; end }
- # x.report("upto:") { 1.upto(n) do ; a = "1"; end }
- # end
- #
- # <i>Generates:</i>
- #
- # user system total real
- # for: 1.050000 0.000000 1.050000 ( 0.503462)
- # times: 1.533333 0.016667 1.550000 ( 0.735473)
- # upto: 1.500000 0.016667 1.516667 ( 0.711239)
- #
-
- def bm(label_width = 0, *labels, &blk) # :yield: report
- benchmark(CAPTION, label_width, FORMAT, *labels, &blk)
- end
-
-
- # Sometimes benchmark results are skewed because code executed
- # earlier encounters different garbage collection overheads than
- # that run later. #bmbm attempts to minimize this effect by running
- # the tests twice, the first time as a rehearsal in order to get the
- # runtime environment stable, the second time for
- # real. <tt>GC.start</tt> is executed before the start of each of
- # the real timings; the cost of this is not included in the
- # timings. In reality, though, there's only so much that #bmbm can
- # do, and the results are not guaranteed to be isolated from garbage
- # collection and other effects.
- #
- # Because #bmbm takes two passes through the tests, it can
- # calculate the required label width.
- #
- # require 'benchmark'
- #
- # array = (1..1000000).map { rand }
- #
- # Benchmark.bmbm do |x|
- # x.report("sort!") { array.dup.sort! }
- # x.report("sort") { array.dup.sort }
- # end
- #
- # <i>Generates:</i>
- #
- # Rehearsal -----------------------------------------
- # sort! 11.928000 0.010000 11.938000 ( 12.756000)
- # sort 13.048000 0.020000 13.068000 ( 13.857000)
- # ------------------------------- total: 25.006000sec
- #
- # user system total real
- # sort! 12.959000 0.010000 12.969000 ( 13.793000)
- # sort 12.007000 0.000000 12.007000 ( 12.791000)
- #
- # #bmbm yields a Benchmark::Job object and returns an array of
- # Benchmark::Tms objects.
- #
- def bmbm(width = 0, &blk) # :yield: job
- job = Job.new(width)
- yield(job)
- width = job.width + 1
- sync = STDOUT.sync
- STDOUT.sync = true
-
- # rehearsal
- puts 'Rehearsal '.ljust(width+CAPTION.length,'-')
- ets = job.list.inject(Tms.new) { |sum,(label,item)|
- print label.ljust(width)
- res = Benchmark.measure(&item)
- print res.format
- sum + res
- }.format("total: %tsec")
- print " #{ets}\n\n".rjust(width+CAPTION.length+2,'-')
-
- # take
- print ' '*width + CAPTION
- job.list.map { |label,item|
- GC.start
- print label.ljust(width)
- Benchmark.measure(label, &item).tap { |res| print res }
- }
- ensure
- STDOUT.sync = sync unless sync.nil?
- end
-
- #
- # Returns the time used to execute the given block as a
- # Benchmark::Tms object.
- #
- def measure(label = "") # :yield:
- t0, r0 = Process.times, Time.now
- yield
- t1, r1 = Process.times, Time.now
- Benchmark::Tms.new(t1.utime - t0.utime,
- t1.stime - t0.stime,
- t1.cutime - t0.cutime,
- t1.cstime - t0.cstime,
- r1.to_f - r0.to_f,
- label)
- end
-
- #
- # Returns the elapsed real time used to execute the given block.
- #
- def realtime # :yield:
- r0 = Time.now
- yield
- Time.now - r0
- end
-
- module_function :benchmark, :measure, :realtime, :bm, :bmbm
-
- #
- # A Job is a sequence of labelled blocks to be processed by the
- # Benchmark.bmbm method. It is of little direct interest to the user.
- #
- class Job # :nodoc:
- #
- # Returns an initialized Job instance.
- # Usually, one doesn't call this method directly, as new
- # Job objects are created by the #bmbm method.
- # _width_ is a initial value for the label offset used in formatting;
- # the #bmbm method passes its _width_ argument to this constructor.
- #
- def initialize(width)
- @width = width
- @list = []
- end
-
- #
- # Registers the given label and block pair in the job list.
- #
- def item(label = "", &blk) # :yield:
- raise ArgumentError, "no block" unless block_given?
- label = label.to_s
- w = label.length
- @width = w if @width < w
- @list << [label, blk]
- self
- end
-
- alias report item
-
- # An array of 2-element arrays, consisting of label and block pairs.
- attr_reader :list
-
- # Length of the widest label in the #list.
- attr_reader :width
- end
-
- #
- # This class is used by the Benchmark.benchmark and Benchmark.bm methods.
- # It is of little direct interest to the user.
- #
- class Report # :nodoc:
- #
- # Returns an initialized Report instance.
- # Usually, one doesn't call this method directly, as new
- # Report objects are created by the #benchmark and #bm methods.
- # _width_ and _format_ are the label offset and
- # format string used by Tms#format.
- #
- def initialize(width = 0, format = nil)
- @width, @format, @list = width, format, []
- end
-
- #
- # Prints the _label_ and measured time for the block,
- # formatted by _format_. See Tms#format for the
- # formatting rules.
- #
- def item(label = "", *format, &blk) # :yield:
- print label.to_s.ljust(@width)
- @list << res = Benchmark.measure(label, &blk)
- print res.format(@format, *format)
- res
- end
-
- alias report item
-
- # An array of Benchmark::Tms objects representing each item.
- attr_reader :list
- end
-
-
-
- #
- # A data object, representing the times associated with a benchmark
- # measurement.
- #
- class Tms
-
- # Default caption, see also Benchmark::CAPTION
- CAPTION = " user system total real\n"
-
- # Default format string, see also Benchmark::FORMAT
- FORMAT = "%10.6u %10.6y %10.6t %10.6r\n"
-
- # User CPU time
- attr_reader :utime
-
- # System CPU time
- attr_reader :stime
-
- # User CPU time of children
- attr_reader :cutime
-
- # System CPU time of children
- attr_reader :cstime
-
- # Elapsed real time
- attr_reader :real
-
- # Total time, that is _utime_ + _stime_ + _cutime_ + _cstime_
- attr_reader :total
-
- # Label
- attr_reader :label
-
- #
- # Returns an initialized Tms object which has
- # _utime_ as the user CPU time, _stime_ as the system CPU time,
- # _cutime_ as the children's user CPU time, _cstime_ as the children's
- # system CPU time, _real_ as the elapsed real time and _label_ as the label.
- #
- def initialize(utime = 0.0, stime = 0.0, cutime = 0.0, cstime = 0.0, real = 0.0, label = nil)
- @utime, @stime, @cutime, @cstime, @real, @label = utime, stime, cutime, cstime, real, label.to_s
- @total = @utime + @stime + @cutime + @cstime
- end
-
- #
- # Returns a new Tms object whose times are the sum of the times for this
- # Tms object, plus the time required to execute the code block (_blk_).
- #
- def add(&blk) # :yield:
- self + Benchmark.measure(&blk)
- end
-
- #
- # An in-place version of #add.
- #
- def add!(&blk)
- t = Benchmark.measure(&blk)
- @utime = utime + t.utime
- @stime = stime + t.stime
- @cutime = cutime + t.cutime
- @cstime = cstime + t.cstime
- @real = real + t.real
- self
- end
-
- #
- # Returns a new Tms object obtained by memberwise summation
- # of the individual times for this Tms object with those of the other
- # Tms object.
- # This method and #/() are useful for taking statistics.
- #
- def +(other); memberwise(:+, other) end
-
- #
- # Returns a new Tms object obtained by memberwise subtraction
- # of the individual times for the other Tms object from those of this
- # Tms object.
- #
- def -(other); memberwise(:-, other) end
-
- #
- # Returns a new Tms object obtained by memberwise multiplication
- # of the individual times for this Tms object by _x_.
- #
- def *(x); memberwise(:*, x) end
-
- #
- # Returns a new Tms object obtained by memberwise division
- # of the individual times for this Tms object by _x_.
- # This method and #+() are useful for taking statistics.
- #
- def /(x); memberwise(:/, x) end
-
- #
- # Returns the contents of this Tms object as
- # a formatted string, according to a format string
- # like that passed to Kernel.format. In addition, #format
- # accepts the following extensions:
- #
- # <tt>%u</tt>:: Replaced by the user CPU time, as reported by Tms#utime.
- # <tt>%y</tt>:: Replaced by the system CPU time, as reported by #stime (Mnemonic: y of "s*y*stem")
- # <tt>%U</tt>:: Replaced by the children's user CPU time, as reported by Tms#cutime
- # <tt>%Y</tt>:: Replaced by the children's system CPU time, as reported by Tms#cstime
- # <tt>%t</tt>:: Replaced by the total CPU time, as reported by Tms#total
- # <tt>%r</tt>:: Replaced by the elapsed real time, as reported by Tms#real
- # <tt>%n</tt>:: Replaced by the label string, as reported by Tms#label (Mnemonic: n of "*n*ame")
- #
- # If _format_ is not given, FORMAT is used as default value, detailing the
- # user, system and real elapsed time.
- #
- def format(format = nil, *args)
- str = (format || FORMAT).dup
- str.gsub!(/(%[-+\.\d]*)n/) { "#{$1}s" % label }
- str.gsub!(/(%[-+\.\d]*)u/) { "#{$1}f" % utime }
- str.gsub!(/(%[-+\.\d]*)y/) { "#{$1}f" % stime }
- str.gsub!(/(%[-+\.\d]*)U/) { "#{$1}f" % cutime }
- str.gsub!(/(%[-+\.\d]*)Y/) { "#{$1}f" % cstime }
- str.gsub!(/(%[-+\.\d]*)t/) { "#{$1}f" % total }
- str.gsub!(/(%[-+\.\d]*)r/) { "(#{$1}f)" % real }
- format ? str % args : str
- end
-
- #
- # Same as #format.
- #
- def to_s
- format
- end
-
- #
- # Returns a new 6-element array, consisting of the
- # label, user CPU time, system CPU time, children's
- # user CPU time, children's system CPU time and elapsed
- # real time.
- #
- def to_a
- [@label, @utime, @stime, @cutime, @cstime, @real]
- end
-
- protected
-
- #
- # Returns a new Tms object obtained by memberwise operation +op+
- # of the individual times for this Tms object with those of the other
- # Tms object.
- #
- # +op+ can be a mathematical operation such as <tt>+</tt>, <tt>-</tt>,
- # <tt>*</tt>, <tt>/</tt>
- #
- def memberwise(op, x)
- case x
- when Benchmark::Tms
- Benchmark::Tms.new(utime.__send__(op, x.utime),
- stime.__send__(op, x.stime),
- cutime.__send__(op, x.cutime),
- cstime.__send__(op, x.cstime),
- real.__send__(op, x.real)
- )
- else
- Benchmark::Tms.new(utime.__send__(op, x),
- stime.__send__(op, x),
- cutime.__send__(op, x),
- cstime.__send__(op, x),
- real.__send__(op, x)
- )
- end
- end
- end
-
- # The default caption string (heading above the output times).
- CAPTION = Benchmark::Tms::CAPTION
-
- # The default format string used to display times. See also Benchmark::Tms#format.
- FORMAT = Benchmark::Tms::FORMAT
-end
-
-if __FILE__ == $0
- include Benchmark
-
- n = ARGV[0].to_i.nonzero? || 50000
- puts %Q([#{n} times iterations of `a = "1"'])
- benchmark(" " + CAPTION, 7, FORMAT) do |x|
- x.report("for:") {for _ in 1..n; _ = "1"; end} # Benchmark.measure
- x.report("times:") {n.times do ; _ = "1"; end}
- x.report("upto:") {1.upto(n) do ; _ = "1"; end}
- end
-
- benchmark do
- [
- measure{for _ in 1..n; _ = "1"; end}, # Benchmark.measure
- measure{n.times do ; _ = "1"; end},
- measure{1.upto(n) do ; _ = "1"; end}
- ]
- end
-end
diff --git a/ruby_1_9_3/lib/cgi.rb b/ruby_1_9_3/lib/cgi.rb
deleted file mode 100644
index 31730bd60c..0000000000
--- a/ruby_1_9_3/lib/cgi.rb
+++ /dev/null
@@ -1,273 +0,0 @@
-#
-# cgi.rb - cgi support library
-#
-# Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
-#
-# Copyright (C) 2000 Information-technology Promotion Agency, Japan
-#
-# Author: Wakou Aoyama <wakou@ruby-lang.org>
-#
-# Documentation: Wakou Aoyama (RDoc'd and embellished by William Webber)
-#
-
-raise "Please, use ruby 1.9.0 or later." if RUBY_VERSION < "1.9.0"
-
-# == Overview
-#
-# The Common Gateway Interface (CGI) is a simple protocol for passing an HTTP
-# request from a web server to a standalone program, and returning the output
-# to the web browser. Basically, a CGI program is called with the parameters
-# of the request passed in either in the environment (GET) or via $stdin
-# (POST), and everything it prints to $stdout is returned to the client.
-#
-# This file holds the CGI class. This class provides functionality for
-# retrieving HTTP request parameters, managing cookies, and generating HTML
-# output.
-#
-# The file CGI::Session provides session management functionality; see that
-# class for more details.
-#
-# See http://www.w3.org/CGI/ for more information on the CGI protocol.
-#
-# == Introduction
-#
-# CGI is a large class, providing several categories of methods, many of which
-# are mixed in from other modules. Some of the documentation is in this class,
-# some in the modules CGI::QueryExtension and CGI::HtmlExtension. See
-# CGI::Cookie for specific information on handling cookies, and cgi/session.rb
-# (CGI::Session) for information on sessions.
-#
-# For queries, CGI provides methods to get at environmental variables,
-# parameters, cookies, and multipart request data. For responses, CGI provides
-# methods for writing output and generating HTML.
-#
-# Read on for more details. Examples are provided at the bottom.
-#
-# == Queries
-#
-# The CGI class dynamically mixes in parameter and cookie-parsing
-# functionality, environmental variable access, and support for
-# parsing multipart requests (including uploaded files) from the
-# CGI::QueryExtension module.
-#
-# === Environmental Variables
-#
-# The standard CGI environmental variables are available as read-only
-# attributes of a CGI object. The following is a list of these variables:
-#
-#
-# AUTH_TYPE HTTP_HOST REMOTE_IDENT
-# CONTENT_LENGTH HTTP_NEGOTIATE REMOTE_USER
-# CONTENT_TYPE HTTP_PRAGMA REQUEST_METHOD
-# GATEWAY_INTERFACE HTTP_REFERER SCRIPT_NAME
-# HTTP_ACCEPT HTTP_USER_AGENT SERVER_NAME
-# HTTP_ACCEPT_CHARSET PATH_INFO SERVER_PORT
-# HTTP_ACCEPT_ENCODING PATH_TRANSLATED SERVER_PROTOCOL
-# HTTP_ACCEPT_LANGUAGE QUERY_STRING SERVER_SOFTWARE
-# HTTP_CACHE_CONTROL REMOTE_ADDR
-# HTTP_FROM REMOTE_HOST
-#
-#
-# For each of these variables, there is a corresponding attribute with the
-# same name, except all lower case and without a preceding HTTP_.
-# +content_length+ and +server_port+ are integers; the rest are strings.
-#
-# === Parameters
-#
-# The method #params() returns a hash of all parameters in the request as
-# name/value-list pairs, where the value-list is an Array of one or more
-# values. The CGI object itself also behaves as a hash of parameter names
-# to values, but only returns a single value (as a String) for each
-# parameter name.
-#
-# For instance, suppose the request contains the parameter
-# "favourite_colours" with the multiple values "blue" and "green". The
-# following behaviour would occur:
-#
-# cgi.params["favourite_colours"] # => ["blue", "green"]
-# cgi["favourite_colours"] # => "blue"
-#
-# If a parameter does not exist, the former method will return an empty
-# array, the latter an empty string. The simplest way to test for existence
-# of a parameter is by the #has_key? method.
-#
-# === Cookies
-#
-# HTTP Cookies are automatically parsed from the request. They are available
-# from the #cookies() accessor, which returns a hash from cookie name to
-# CGI::Cookie object.
-#
-# === Multipart requests
-#
-# If a request's method is POST and its content type is multipart/form-data,
-# then it may contain uploaded files. These are stored by the QueryExtension
-# module in the parameters of the request. The parameter name is the name
-# attribute of the file input field, as usual. However, the value is not
-# a string, but an IO object, either an IOString for small files, or a
-# Tempfile for larger ones. This object also has the additional singleton
-# methods:
-#
-# #local_path():: the path of the uploaded file on the local filesystem
-# #original_filename():: the name of the file on the client computer
-# #content_type():: the content type of the file
-#
-# == Responses
-#
-# The CGI class provides methods for sending header and content output to
-# the HTTP client, and mixes in methods for programmatic HTML generation
-# from CGI::HtmlExtension and CGI::TagMaker modules. The precise version of HTML
-# to use for HTML generation is specified at object creation time.
-#
-# === Writing output
-#
-# The simplest way to send output to the HTTP client is using the #out() method.
-# This takes the HTTP headers as a hash parameter, and the body content
-# via a block. The headers can be generated as a string using the #header()
-# method. The output stream can be written directly to using the #print()
-# method.
-#
-# === Generating HTML
-#
-# Each HTML element has a corresponding method for generating that
-# element as a String. The name of this method is the same as that
-# of the element, all lowercase. The attributes of the element are
-# passed in as a hash, and the body as a no-argument block that evaluates
-# to a String. The HTML generation module knows which elements are
-# always empty, and silently drops any passed-in body. It also knows
-# which elements require matching closing tags and which don't. However,
-# it does not know what attributes are legal for which elements.
-#
-# There are also some additional HTML generation methods mixed in from
-# the CGI::HtmlExtension module. These include individual methods for the
-# different types of form inputs, and methods for elements that commonly
-# take particular attributes where the attributes can be directly specified
-# as arguments, rather than via a hash.
-#
-# == Examples of use
-#
-# === Get form values
-#
-# require "cgi"
-# cgi = CGI.new
-# value = cgi['field_name'] # <== value string for 'field_name'
-# # if not 'field_name' included, then return "".
-# fields = cgi.keys # <== array of field names
-#
-# # returns true if form has 'field_name'
-# cgi.has_key?('field_name')
-# cgi.has_key?('field_name')
-# cgi.include?('field_name')
-#
-# CAUTION! cgi['field_name'] returned an Array with the old
-# cgi.rb(included in ruby 1.6)
-#
-# === Get form values as hash
-#
-# require "cgi"
-# cgi = CGI.new
-# params = cgi.params
-#
-# cgi.params is a hash.
-#
-# cgi.params['new_field_name'] = ["value"] # add new param
-# cgi.params['field_name'] = ["new_value"] # change value
-# cgi.params.delete('field_name') # delete param
-# cgi.params.clear # delete all params
-#
-#
-# === Save form values to file
-#
-# require "pstore"
-# db = PStore.new("query.db")
-# db.transaction do
-# db["params"] = cgi.params
-# end
-#
-#
-# === Restore form values from file
-#
-# require "pstore"
-# db = PStore.new("query.db")
-# db.transaction do
-# cgi.params = db["params"]
-# end
-#
-#
-# === Get multipart form values
-#
-# require "cgi"
-# cgi = CGI.new
-# value = cgi['field_name'] # <== value string for 'field_name'
-# value.read # <== body of value
-# value.local_path # <== path to local file of value
-# value.original_filename # <== original filename of value
-# value.content_type # <== content_type of value
-#
-# and value has StringIO or Tempfile class methods.
-#
-# === Get cookie values
-#
-# require "cgi"
-# cgi = CGI.new
-# values = cgi.cookies['name'] # <== array of 'name'
-# # if not 'name' included, then return [].
-# names = cgi.cookies.keys # <== array of cookie names
-#
-# and cgi.cookies is a hash.
-#
-# === Get cookie objects
-#
-# require "cgi"
-# cgi = CGI.new
-# for name, cookie in cgi.cookies
-# cookie.expires = Time.now + 30
-# end
-# cgi.out("cookie" => cgi.cookies) {"string"}
-#
-# cgi.cookies # { "name1" => cookie1, "name2" => cookie2, ... }
-#
-# require "cgi"
-# cgi = CGI.new
-# cgi.cookies['name'].expires = Time.now + 30
-# cgi.out("cookie" => cgi.cookies['name']) {"string"}
-#
-# === Print http header and html string to $DEFAULT_OUTPUT ($>)
-#
-# require "cgi"
-# cgi = CGI.new("html3") # add HTML generation methods
-# cgi.out() do
-# cgi.html() do
-# cgi.head{ cgi.title{"TITLE"} } +
-# cgi.body() do
-# cgi.form() do
-# cgi.textarea("get_text") +
-# cgi.br +
-# cgi.submit
-# end +
-# cgi.pre() do
-# CGI::escapeHTML(
-# "params: " + cgi.params.inspect + "\n" +
-# "cookies: " + cgi.cookies.inspect + "\n" +
-# ENV.collect() do |key, value|
-# key + " --> " + value + "\n"
-# end.join("")
-# )
-# end
-# end
-# end
-# end
-#
-# # add HTML generation methods
-# CGI.new("html3") # html3.2
-# CGI.new("html4") # html4.01 (Strict)
-# CGI.new("html4Tr") # html4.01 Transitional
-# CGI.new("html4Fr") # html4.01 Frameset
-#
-
-class CGI
-end
-
-require 'cgi/core'
-require 'cgi/cookie'
-require 'cgi/util'
-CGI.autoload(:HtmlExtension, 'cgi/html')
diff --git a/ruby_1_9_3/lib/cgi/cookie.rb b/ruby_1_9_3/lib/cgi/cookie.rb
deleted file mode 100644
index c2526931d5..0000000000
--- a/ruby_1_9_3/lib/cgi/cookie.rb
+++ /dev/null
@@ -1,164 +0,0 @@
-class CGI
- @@accept_charset="UTF-8" unless defined?(@@accept_charset)
- # Class representing an HTTP cookie.
- #
- # In addition to its specific fields and methods, a Cookie instance
- # is a delegator to the array of its values.
- #
- # See RFC 2965.
- #
- # == Examples of use
- # cookie1 = CGI::Cookie::new("name", "value1", "value2", ...)
- # cookie1 = CGI::Cookie::new("name" => "name", "value" => "value")
- # cookie1 = CGI::Cookie::new('name' => 'name',
- # 'value' => ['value1', 'value2', ...],
- # 'path' => 'path', # optional
- # 'domain' => 'domain', # optional
- # 'expires' => Time.now, # optional
- # 'secure' => true # optional
- # )
- #
- # cgi.out("cookie" => [cookie1, cookie2]) { "string" }
- #
- # name = cookie1.name
- # values = cookie1.value
- # path = cookie1.path
- # domain = cookie1.domain
- # expires = cookie1.expires
- # secure = cookie1.secure
- #
- # cookie1.name = 'name'
- # cookie1.value = ['value1', 'value2', ...]
- # cookie1.path = 'path'
- # cookie1.domain = 'domain'
- # cookie1.expires = Time.now + 30
- # cookie1.secure = true
- class Cookie < Array
-
- # Create a new CGI::Cookie object.
- #
- # :call-seq:
- # Cookie.new(name_string,*value)
- # Cookie.new(options_hash)
- #
- # +name_string+::
- # The name of the cookie; in this form, there is no #domain or
- # #expiration. The #path is gleaned from the +SCRIPT_NAME+ environment
- # variable, and #secure is false.
- # <tt>*value</tt>::
- # value or list of values of the cookie
- # +options_hash+::
- # A Hash of options to initialize this Cookie. Possible options are:
- #
- # name:: the name of the cookie. Required.
- # value:: the cookie's value or list of values.
- # path:: the path for which this cookie applies. Defaults to the
- # the value of the +SCRIPT_NAME+ environment variable.
- # domain:: the domain for which this cookie applies.
- # expires:: the time at which this cookie expires, as a +Time+ object.
- # secure:: whether this cookie is a secure cookie or not (default to
- # false). Secure cookies are only transmitted to HTTPS
- # servers.
- #
- # These keywords correspond to attributes of the cookie object.
- def initialize(name = "", *value)
- @domain = nil
- @expires = nil
- if name.kind_of?(String)
- @name = name
- %r|^(.*/)|.match(ENV["SCRIPT_NAME"])
- @path = ($1 or "")
- @secure = false
- return super(value)
- end
-
- options = name
- unless options.has_key?("name")
- raise ArgumentError, "`name' required"
- end
-
- @name = options["name"]
- value = Array(options["value"])
- # simple support for IE
- if options["path"]
- @path = options["path"]
- else
- %r|^(.*/)|.match(ENV["SCRIPT_NAME"])
- @path = ($1 or "")
- end
- @domain = options["domain"]
- @expires = options["expires"]
- @secure = options["secure"] == true ? true : false
-
- super(value)
- end
-
- # Name of this cookie, as a +String+
- attr_accessor :name
- # Path for which this cookie applies, as a +String+
- attr_accessor :path
- # Domain for which this cookie applies, as a +String+
- attr_accessor :domain
- # Time at which this cookie expires, as a +Time+
- attr_accessor :expires
- # True if this cookie is secure; false otherwise
- attr_reader("secure")
-
- # Returns the value or list of values for this cookie.
- def value
- self
- end
-
- # Replaces the value of this cookie with a new value or list of values.
- def value=(val)
- replace(Array(val))
- end
-
- # Set whether the Cookie is a secure cookie or not.
- #
- # +val+ must be a boolean.
- def secure=(val)
- @secure = val if val == true or val == false
- @secure
- end
-
- # Convert the Cookie to its string representation.
- def to_s
- val = collect{|v| CGI::escape(v) }.join("&")
- buf = "#{@name}=#{val}"
- buf << "; domain=#{@domain}" if @domain
- buf << "; path=#{@path}" if @path
- buf << "; expires=#{CGI::rfc1123_date(@expires)}" if @expires
- buf << "; secure" if @secure == true
- buf
- end
-
- end # class Cookie
-
- # Parse a raw cookie string into a hash of cookie-name=>Cookie
- # pairs.
- #
- # cookies = CGI::Cookie::parse("raw_cookie_string")
- # # { "name1" => cookie1, "name2" => cookie2, ... }
- #
- def Cookie::parse(raw_cookie)
- cookies = Hash.new([])
- return cookies unless raw_cookie
-
- raw_cookie.split(/[;,]\s?/).each do |pairs|
- name, values = pairs.split('=',2)
- next unless name and values
- name = CGI::unescape(name)
- values ||= ""
- values = values.split('&').collect{|v| CGI::unescape(v,@@accept_charset) }
- if cookies.has_key?(name)
- values = cookies[name].value + values
- end
- cookies[name] = Cookie::new(name, *values)
- end
-
- cookies
- end
-end
-
-
diff --git a/ruby_1_9_3/lib/cgi/core.rb b/ruby_1_9_3/lib/cgi/core.rb
deleted file mode 100644
index e961b16474..0000000000
--- a/ruby_1_9_3/lib/cgi/core.rb
+++ /dev/null
@@ -1,838 +0,0 @@
-#--
-# Methods for generating HTML, parsing CGI-related parameters, and
-# generating HTTP responses.
-#++
-class CGI
-
- $CGI_ENV = ENV # for FCGI support
-
- # String for carriage return
- CR = "\015"
-
- # String for linefeed
- LF = "\012"
-
- # Standard internet newline sequence
- EOL = CR + LF
-
- REVISION = '$Id$' #:nodoc:
-
- # Whether processing will be required in binary vs text
- NEEDS_BINMODE = File::BINARY != 0
-
- # Path separators in different environments.
- PATH_SEPARATOR = {'UNIX'=>'/', 'WINDOWS'=>'\\', 'MACINTOSH'=>':'}
-
- # HTTP status codes.
- HTTP_STATUS = {
- "OK" => "200 OK",
- "PARTIAL_CONTENT" => "206 Partial Content",
- "MULTIPLE_CHOICES" => "300 Multiple Choices",
- "MOVED" => "301 Moved Permanently",
- "REDIRECT" => "302 Found",
- "NOT_MODIFIED" => "304 Not Modified",
- "BAD_REQUEST" => "400 Bad Request",
- "AUTH_REQUIRED" => "401 Authorization Required",
- "FORBIDDEN" => "403 Forbidden",
- "NOT_FOUND" => "404 Not Found",
- "METHOD_NOT_ALLOWED" => "405 Method Not Allowed",
- "NOT_ACCEPTABLE" => "406 Not Acceptable",
- "LENGTH_REQUIRED" => "411 Length Required",
- "PRECONDITION_FAILED" => "412 Precondition Failed",
- "SERVER_ERROR" => "500 Internal Server Error",
- "NOT_IMPLEMENTED" => "501 Method Not Implemented",
- "BAD_GATEWAY" => "502 Bad Gateway",
- "VARIANT_ALSO_VARIES" => "506 Variant Also Negotiates"
- }
-
- # :startdoc:
-
- # Synonym for ENV.
- def env_table
- ENV
- end
-
- # Synonym for $stdin.
- def stdinput
- $stdin
- end
-
- # Synonym for $stdout.
- def stdoutput
- $stdout
- end
-
- private :env_table, :stdinput, :stdoutput
-
- # Create an HTTP header block as a string.
- #
- # :call-seq:
- # headers(content_type_string="text/html")
- # headers(headers_hash)
- #
- # Includes the empty line that ends the header block.
- #
- # +content_type_string+::
- # If this form is used, this string is the <tt>Content-Type</tt>
- # +headers_hash+::
- # A Hash of header values. The following header keys are recognized:
- #
- # type:: The Content-Type header. Defaults to "text/html"
- # charset:: The charset of the body, appended to the Content-Type header.
- # nph:: A boolean value. If true, prepend protocol string and status
- # code, and date; and sets default values for "server" and
- # "connection" if not explicitly set.
- # status::
- # The HTTP status code as a String, returned as the Status header. The
- # values are:
- #
- # OK:: 200 OK
- # PARTIAL_CONTENT:: 206 Partial Content
- # MULTIPLE_CHOICES:: 300 Multiple Choices
- # MOVED:: 301 Moved Permanently
- # REDIRECT:: 302 Found
- # NOT_MODIFIED:: 304 Not Modified
- # BAD_REQUEST:: 400 Bad Request
- # AUTH_REQUIRED:: 401 Authorization Required
- # FORBIDDEN:: 403 Forbidden
- # NOT_FOUND:: 404 Not Found
- # METHOD_NOT_ALLOWED:: 405 Method Not Allowed
- # NOT_ACCEPTABLE:: 406 Not Acceptable
- # LENGTH_REQUIRED:: 411 Length Required
- # PRECONDITION_FAILED:: 412 Precondition Failed
- # SERVER_ERROR:: 500 Internal Server Error
- # NOT_IMPLEMENTED:: 501 Method Not Implemented
- # BAD_GATEWAY:: 502 Bad Gateway
- # VARIANT_ALSO_VARIES:: 506 Variant Also Negotiates
- #
- # server:: The server software, returned as the Server header.
- # connection:: The connection type, returned as the Connection header (for
- # instance, "close".
- # length:: The length of the content that will be sent, returned as the
- # Content-Length header.
- # language:: The language of the content, returned as the Content-Language
- # header.
- # expires:: The time on which the current content expires, as a +Time+
- # object, returned as the Expires header.
- # cookie::
- # A cookie or cookies, returned as one or more Set-Cookie headers. The
- # value can be the literal string of the cookie; a CGI::Cookie object;
- # an Array of literal cookie strings or Cookie objects; or a hash all of
- # whose values are literal cookie strings or Cookie objects.
- #
- # These cookies are in addition to the cookies held in the
- # @output_cookies field.
- #
- # Other headers can also be set; they are appended as key: value.
- #
- # Examples:
- #
- # header
- # # Content-Type: text/html
- #
- # header("text/plain")
- # # Content-Type: text/plain
- #
- # header("nph" => true,
- # "status" => "OK", # == "200 OK"
- # # "status" => "200 GOOD",
- # "server" => ENV['SERVER_SOFTWARE'],
- # "connection" => "close",
- # "type" => "text/html",
- # "charset" => "iso-2022-jp",
- # # Content-Type: text/html; charset=iso-2022-jp
- # "length" => 103,
- # "language" => "ja",
- # "expires" => Time.now + 30,
- # "cookie" => [cookie1, cookie2],
- # "my_header1" => "my_value"
- # "my_header2" => "my_value")
- #
- # This method does not perform charset conversion.
- def header(options='text/html')
- if options.is_a?(String)
- content_type = options
- buf = _header_for_string(content_type)
- elsif options.is_a?(Hash)
- if options.size == 1 && options.has_key?('type')
- content_type = options['type']
- buf = _header_for_string(content_type)
- else
- buf = _header_for_hash(options.dup)
- end
- else
- raise ArgumentError.new("expected String or Hash but got #{options.class}")
- end
- if defined?(MOD_RUBY)
- _header_for_modruby(buf)
- return ''
- else
- buf << EOL # empty line of separator
- return buf
- end
- end # header()
-
- def _header_for_string(content_type) #:nodoc:
- buf = ''
- if nph?()
- buf << "#{$CGI_ENV['SERVER_PROTOCOL'] || 'HTTP/1.0'} 200 OK#{EOL}"
- buf << "Date: #{CGI.rfc1123_date(Time.now)}#{EOL}"
- buf << "Server: #{$CGI_ENV['SERVER_SOFTWARE']}#{EOL}"
- buf << "Connection: close#{EOL}"
- end
- buf << "Content-Type: #{content_type}#{EOL}"
- if @output_cookies
- @output_cookies.each {|cookie| buf << "Set-Cookie: #{cookie}#{EOL}" }
- end
- return buf
- end # _header_for_string
- private :_header_for_string
-
- def _header_for_hash(options) #:nodoc:
- buf = ''
- ## add charset to option['type']
- options['type'] ||= 'text/html'
- charset = options.delete('charset')
- options['type'] += "; charset=#{charset}" if charset
- ## NPH
- options.delete('nph') if defined?(MOD_RUBY)
- if options.delete('nph') || nph?()
- protocol = $CGI_ENV['SERVER_PROTOCOL'] || 'HTTP/1.0'
- status = options.delete('status')
- status = HTTP_STATUS[status] || status || '200 OK'
- buf << "#{protocol} #{status}#{EOL}"
- buf << "Date: #{CGI.rfc1123_date(Time.now)}#{EOL}"
- options['server'] ||= $CGI_ENV['SERVER_SOFTWARE'] || ''
- options['connection'] ||= 'close'
- end
- ## common headers
- status = options.delete('status')
- buf << "Status: #{HTTP_STATUS[status] || status}#{EOL}" if status
- server = options.delete('server')
- buf << "Server: #{server}#{EOL}" if server
- connection = options.delete('connection')
- buf << "Connection: #{connection}#{EOL}" if connection
- type = options.delete('type')
- buf << "Content-Type: #{type}#{EOL}" #if type
- length = options.delete('length')
- buf << "Content-Length: #{length}#{EOL}" if length
- language = options.delete('language')
- buf << "Content-Language: #{language}#{EOL}" if language
- expires = options.delete('expires')
- buf << "Expires: #{CGI.rfc1123_date(expires)}#{EOL}" if expires
- ## cookie
- if cookie = options.delete('cookie')
- case cookie
- when String, Cookie
- buf << "Set-Cookie: #{cookie}#{EOL}"
- when Array
- arr = cookie
- arr.each {|c| buf << "Set-Cookie: #{c}#{EOL}" }
- when Hash
- hash = cookie
- hash.each {|name, c| buf << "Set-Cookie: #{c}#{EOL}" }
- end
- end
- if @output_cookies
- @output_cookies.each {|c| buf << "Set-Cookie: #{c}#{EOL}" }
- end
- ## other headers
- options.each do |key, value|
- buf << "#{key}: #{value}#{EOL}"
- end
- return buf
- end # _header_for_hash
- private :_header_for_hash
-
- def nph? #:nodoc:
- return /IIS\/(\d+)/.match($CGI_ENV['SERVER_SOFTWARE']) && $1.to_i < 5
- end
-
- def _header_for_modruby(buf) #:nodoc:
- request = Apache::request
- buf.scan(/([^:]+): (.+)#{EOL}/o) do |name, value|
- warn sprintf("name:%s value:%s\n", name, value) if $DEBUG
- case name
- when 'Set-Cookie'
- request.headers_out.add(name, value)
- when /^status$/i
- request.status_line = value
- request.status = value.to_i
- when /^content-type$/i
- request.content_type = value
- when /^content-encoding$/i
- request.content_encoding = value
- when /^location$/i
- request.status = 302 if request.status == 200
- request.headers_out[name] = value
- else
- request.headers_out[name] = value
- end
- end
- request.send_http_header
- return ''
- end
- private :_header_for_modruby
-
- # Print an HTTP header and body to $DEFAULT_OUTPUT ($>)
- #
- # :call-seq:
- # cgi.out(content_type_string='text/html')
- # cgi.out(headers_hash)
- #
- # +content_type_string+::
- # If a string is passed, it is assumed to be the content type.
- # +headers_hash+::
- # This is a Hash of headers, similar to that used by #header.
- # +block+::
- # A block is required and should evaluate to the body of the response.
- #
- # <tt>Content-Length</tt> is automatically calculated from the size of
- # the String returned by the content block.
- #
- # If <tt>ENV['REQUEST_METHOD'] == "HEAD"</tt>, then only the header
- # is output (the content block is still required, but it is ignored).
- #
- # If the charset is "iso-2022-jp" or "euc-jp" or "shift_jis" then the
- # content is converted to this charset, and the language is set to "ja".
- #
- # Example:
- #
- # cgi = CGI.new
- # cgi.out{ "string" }
- # # Content-Type: text/html
- # # Content-Length: 6
- # #
- # # string
- #
- # cgi.out("text/plain") { "string" }
- # # Content-Type: text/plain
- # # Content-Length: 6
- # #
- # # string
- #
- # cgi.out("nph" => true,
- # "status" => "OK", # == "200 OK"
- # "server" => ENV['SERVER_SOFTWARE'],
- # "connection" => "close",
- # "type" => "text/html",
- # "charset" => "iso-2022-jp",
- # # Content-Type: text/html; charset=iso-2022-jp
- # "language" => "ja",
- # "expires" => Time.now + (3600 * 24 * 30),
- # "cookie" => [cookie1, cookie2],
- # "my_header1" => "my_value",
- # "my_header2" => "my_value") { "string" }
- # # HTTP/1.1 200 OK
- # # Date: Sun, 15 May 2011 17:35:54 GMT
- # # Server: Apache 2.2.0
- # # Connection: close
- # # Content-Type: text/html; charset=iso-2022-jp
- # # Content-Length: 6
- # # Content-Language: ja
- # # Expires: Tue, 14 Jun 2011 17:35:54 GMT
- # # Set-Cookie: foo
- # # Set-Cookie: bar
- # # my_header1: my_value
- # # my_header2: my_value
- # #
- # # string
- def out(options = "text/html") # :yield:
-
- options = { "type" => options } if options.kind_of?(String)
- content = yield
- options["length"] = content.bytesize.to_s
- output = stdoutput
- output.binmode if defined? output.binmode
- output.print header(options)
- output.print content unless "HEAD" == env_table['REQUEST_METHOD']
- end
-
-
- # Print an argument or list of arguments to the default output stream
- #
- # cgi = CGI.new
- # cgi.print # default: cgi.print == $DEFAULT_OUTPUT.print
- def print(*options)
- stdoutput.print(*options)
- end
-
- # Parse an HTTP query string into a hash of key=>value pairs.
- #
- # params = CGI::parse("query_string")
- # # {"name1" => ["value1", "value2", ...],
- # # "name2" => ["value1", "value2", ...], ... }
- #
- def CGI::parse(query)
- params = {}
- query.split(/[&;]/).each do |pairs|
- key, value = pairs.split('=',2).collect{|v| CGI::unescape(v) }
- if key && value
- params.has_key?(key) ? params[key].push(value) : params[key] = [value]
- elsif key
- params[key]=[]
- end
- end
- params.default=[].freeze
- params
- end
-
- # Maximum content length of post data
- ##MAX_CONTENT_LENGTH = 2 * 1024 * 1024
-
- # Maximum content length of multipart data
- MAX_MULTIPART_LENGTH = 128 * 1024 * 1024
-
- # Maximum number of request parameters when multipart
- MAX_MULTIPART_COUNT = 128
-
- # Mixin module that provides the following:
- #
- # 1. Access to the CGI environment variables as methods. See
- # documentation to the CGI class for a list of these variables. The
- # methods are exposed by removing the leading +HTTP_+ (if it exists) and
- # downcasing the name. For example, +auth_type+ will return the
- # environment variable +AUTH_TYPE+, and +accept+ will return the value
- # for +HTTP_ACCEPT+.
- #
- # 2. Access to cookies, including the cookies attribute.
- #
- # 3. Access to parameters, including the params attribute, and overloading
- # #[] to perform parameter value lookup by key.
- #
- # 4. The initialize_query method, for initializing the above
- # mechanisms, handling multipart forms, and allowing the
- # class to be used in "offline" mode.
- #
- module QueryExtension
-
- %w[ CONTENT_LENGTH SERVER_PORT ].each do |env|
- define_method(env.sub(/^HTTP_/, '').downcase) do
- (val = env_table[env]) && Integer(val)
- end
- end
-
- %w[ AUTH_TYPE CONTENT_TYPE GATEWAY_INTERFACE PATH_INFO
- PATH_TRANSLATED QUERY_STRING REMOTE_ADDR REMOTE_HOST
- REMOTE_IDENT REMOTE_USER REQUEST_METHOD SCRIPT_NAME
- SERVER_NAME SERVER_PROTOCOL SERVER_SOFTWARE
-
- HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_ACCEPT_ENCODING
- HTTP_ACCEPT_LANGUAGE HTTP_CACHE_CONTROL HTTP_FROM HTTP_HOST
- HTTP_NEGOTIATE HTTP_PRAGMA HTTP_REFERER HTTP_USER_AGENT ].each do |env|
- define_method(env.sub(/^HTTP_/, '').downcase) do
- env_table[env]
- end
- end
-
- # Get the raw cookies as a string.
- def raw_cookie
- env_table["HTTP_COOKIE"]
- end
-
- # Get the raw RFC2965 cookies as a string.
- def raw_cookie2
- env_table["HTTP_COOKIE2"]
- end
-
- # Get the cookies as a hash of cookie-name=>Cookie pairs.
- attr_accessor :cookies
-
- # Get the parameters as a hash of name=>values pairs, where
- # values is an Array.
- attr_reader :params
-
- # Get the uploaded files as a hash of name=>values pairs
- attr_reader :files
-
- # Set all the parameters.
- def params=(hash)
- @params.clear
- @params.update(hash)
- end
-
- ##
- # Parses multipart form elements according to
- # http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2
- #
- # Returns a hash of multipart form parameters with bodies of type StringIO or
- # Tempfile depending on whether the multipart form element exceeds 10 KB
- #
- # params[name => body]
- #
- def read_multipart(boundary, content_length)
- ## read first boundary
- stdin = stdinput
- first_line = "--#{boundary}#{EOL}"
- content_length -= first_line.bytesize
- status = stdin.read(first_line.bytesize)
- raise EOFError.new("no content body") unless status
- raise EOFError.new("bad content body") unless first_line == status
- ## parse and set params
- params = {}
- @files = {}
- boundary_rexp = /--#{Regexp.quote(boundary)}(#{EOL}|--)/
- boundary_size = "#{EOL}--#{boundary}#{EOL}".bytesize
- boundary_end = nil
- buf = ''
- bufsize = 10 * 1024
- max_count = MAX_MULTIPART_COUNT
- n = 0
- while true
- (n += 1) < max_count or raise StandardError.new("too many parameters.")
- ## create body (StringIO or Tempfile)
- body = create_body(bufsize < content_length)
- class << body
- if method_defined?(:path)
- alias local_path path
- else
- def local_path
- nil
- end
- end
- attr_reader :original_filename, :content_type
- end
- ## find head and boundary
- head = nil
- separator = EOL * 2
- until head && matched = boundary_rexp.match(buf)
- if !head && pos = buf.index(separator)
- len = pos + EOL.bytesize
- head = buf[0, len]
- buf = buf[(pos+separator.bytesize)..-1]
- else
- if head && buf.size > boundary_size
- len = buf.size - boundary_size
- body.print(buf[0, len])
- buf[0, len] = ''
- end
- c = stdin.read(bufsize < content_length ? bufsize : content_length)
- raise EOFError.new("bad content body") if c.nil? || c.empty?
- buf << c
- content_length -= c.bytesize
- end
- end
- ## read to end of boundary
- m = matched
- len = m.begin(0)
- s = buf[0, len]
- if s =~ /(\r?\n)\z/
- s = buf[0, len - $1.bytesize]
- end
- body.print(s)
- buf = buf[m.end(0)..-1]
- boundary_end = m[1]
- content_length = -1 if boundary_end == '--'
- ## reset file cursor position
- body.rewind
- ## original filename
- /Content-Disposition:.* filename=(?:"(.*?)"|([^;\r\n]*))/i.match(head)
- filename = $1 || $2 || ''
- filename = CGI.unescape(filename) if unescape_filename?()
- body.instance_variable_set('@original_filename', filename.taint)
- ## content type
- /Content-Type: (.*)/i.match(head)
- (content_type = $1 || '').chomp!
- body.instance_variable_set('@content_type', content_type.taint)
- ## query parameter name
- /Content-Disposition:.* name=(?:"(.*?)"|([^;\r\n]*))/i.match(head)
- name = $1 || $2 || ''
- if body.original_filename.empty?
- value=body.read.dup.force_encoding(@accept_charset)
- (params[name] ||= []) << value
- unless value.valid_encoding?
- if @accept_charset_error_block
- @accept_charset_error_block.call(name,value)
- else
- raise InvalidEncoding,"Accept-Charset encoding error"
- end
- end
- class << params[name].last;self;end.class_eval do
- define_method(:read){self}
- define_method(:original_filename){""}
- define_method(:content_type){""}
- end
- else
- (params[name] ||= []) << body
- @files[name]=body
- end
- ## break loop
- break if content_length == -1
- end
- raise EOFError, "bad boundary end of body part" unless boundary_end =~ /--/
- params.default = []
- params
- end # read_multipart
- private :read_multipart
- def create_body(is_large) #:nodoc:
- if is_large
- require 'tempfile'
- body = Tempfile.new('CGI', encoding: "ascii-8bit")
- else
- begin
- require 'stringio'
- body = StringIO.new("".force_encoding("ascii-8bit"))
- rescue LoadError
- require 'tempfile'
- body = Tempfile.new('CGI', encoding: "ascii-8bit")
- end
- end
- body.binmode if defined? body.binmode
- return body
- end
- def unescape_filename? #:nodoc:
- user_agent = $CGI_ENV['HTTP_USER_AGENT']
- return /Mac/i.match(user_agent) && /Mozilla/i.match(user_agent) && !/MSIE/i.match(user_agent)
- end
-
- # offline mode. read name=value pairs on standard input.
- def read_from_cmdline
- require "shellwords"
-
- string = unless ARGV.empty?
- ARGV.join(' ')
- else
- if STDIN.tty?
- STDERR.print(
- %|(offline mode: enter name=value pairs on standard input)\n|
- )
- end
- array = readlines rescue nil
- if not array.nil?
- array.join(' ').gsub(/\n/n, '')
- else
- ""
- end
- end.gsub(/\\=/n, '%3D').gsub(/\\&/n, '%26')
-
- words = Shellwords.shellwords(string)
-
- if words.find{|x| /=/n.match(x) }
- words.join('&')
- else
- words.join('+')
- end
- end
- private :read_from_cmdline
-
- # A wrapper class to use a StringIO object as the body and switch
- # to a TempFile when the passed threshold is passed.
- # Initialize the data from the query.
- #
- # Handles multipart forms (in particular, forms that involve file uploads).
- # Reads query parameters in the @params field, and cookies into @cookies.
- def initialize_query()
- if ("POST" == env_table['REQUEST_METHOD']) and
- %r|\Amultipart/form-data.*boundary=\"?([^\";,]+)\"?|.match(env_table['CONTENT_TYPE'])
- raise StandardError.new("too large multipart data.") if env_table['CONTENT_LENGTH'].to_i > MAX_MULTIPART_LENGTH
- boundary = $1.dup
- @multipart = true
- @params = read_multipart(boundary, Integer(env_table['CONTENT_LENGTH']))
- else
- @multipart = false
- @params = CGI::parse(
- case env_table['REQUEST_METHOD']
- when "GET", "HEAD"
- if defined?(MOD_RUBY)
- Apache::request.args or ""
- else
- env_table['QUERY_STRING'] or ""
- end
- when "POST"
- stdinput.binmode if defined? stdinput.binmode
- stdinput.read(Integer(env_table['CONTENT_LENGTH'])) or ''
- else
- read_from_cmdline
- end.dup.force_encoding(@accept_charset)
- )
- unless Encoding.find(@accept_charset) == Encoding::ASCII_8BIT
- @params.each do |key,values|
- values.each do |value|
- unless value.valid_encoding?
- if @accept_charset_error_block
- @accept_charset_error_block.call(key,value)
- else
- raise InvalidEncoding,"Accept-Charset encoding error"
- end
- end
- end
- end
- end
- end
-
- @cookies = CGI::Cookie::parse((env_table['HTTP_COOKIE'] or env_table['COOKIE']))
- end
- private :initialize_query
-
- # Returns whether the form contained multipart/form-data
- def multipart?
- @multipart
- end
-
- # Get the value for the parameter with a given key.
- #
- # If the parameter has multiple values, only the first will be
- # retrieved; use #params to get the array of values.
- def [](key)
- params = @params[key]
- return '' unless params
- value = params[0]
- if @multipart
- if value
- return value
- elsif defined? StringIO
- StringIO.new("".force_encoding("ascii-8bit"))
- else
- Tempfile.new("CGI",encoding:"ascii-8bit")
- end
- else
- str = if value then value.dup else "" end
- str
- end
- end
-
- # Return all query parameter names as an array of String.
- def keys(*args)
- @params.keys(*args)
- end
-
- # Returns true if a given query string parameter exists.
- def has_key?(*args)
- @params.has_key?(*args)
- end
- alias key? has_key?
- alias include? has_key?
-
- end # QueryExtension
-
- # Exception raised when there is an invalid encoding detected
- class InvalidEncoding < Exception; end
-
- # @@accept_charset is default accept character set.
- # This default value default is "UTF-8"
- # If you want to change the default accept character set
- # when create a new CGI instance, set this:
- #
- # CGI.accept_charset = "EUC-JP"
- #
- @@accept_charset="UTF-8"
-
- # Return the accept character set for all new CGI instances.
- def self.accept_charset
- @@accept_charset
- end
-
- # Set the accept character set for all new CGI instances.
- def self.accept_charset=(accept_charset)
- @@accept_charset=accept_charset
- end
-
- # Return the accept character set for this CGI instance.
- attr_reader :accept_charset
-
- # Create a new CGI instance.
- #
- # :call-seq:
- # CGI.new(tag_maker) { block }
- # CGI.new(options_hash = {}) { block }
- #
- #
- # <tt>tag_maker</tt>::
- # This is the same as using the +options_hash+ form with the value <tt>{
- # :tag_maker => tag_maker }</tt> Note that it is recommended to use the
- # +options_hash+ form, since it also allows you specify the charset you
- # will accept.
- # <tt>options_hash</tt>::
- # A Hash that recognizes two options:
- #
- # <tt>:accept_charset</tt>::
- # specifies encoding of received query string. If omitted,
- # <tt>@@accept_charset</tt> is used. If the encoding is not valid, a
- # CGI::InvalidEncoding will be raised.
- #
- # Example. Suppose <tt>@@accept_charset</tt> is "UTF-8"
- #
- # when not specified:
- #
- # cgi=CGI.new # @accept_charset # => "UTF-8"
- #
- # when specified as "EUC-JP":
- #
- # cgi=CGI.new(:accept_charset => "EUC-JP") # => "EUC-JP"
- #
- # <tt>:tag_maker</tt>::
- # String that specifies which version of the HTML generation methods to
- # use. If not specified, no HTML generation methods will be loaded.
- #
- # The following values are supported:
- #
- # "html3":: HTML 3.x
- # "html4":: HTML 4.0
- # "html4Tr":: HTML 4.0 Transitional
- # "html4Fr":: HTML 4.0 with Framesets
- #
- # <tt>block</tt>::
- # If provided, the block is called when an invalid encoding is
- # encountered. For example:
- #
- # encoding_errors={}
- # cgi=CGI.new(:accept_charset=>"EUC-JP") do |name,value|
- # encoding_errors[name] = value
- # end
- #
- # Finally, if the CGI object is not created in a standard CGI call
- # environment (that is, it can't locate REQUEST_METHOD in its environment),
- # then it will run in "offline" mode. In this mode, it reads its parameters
- # from the command line or (failing that) from standard input. Otherwise,
- # cookies and other parameters are parsed automatically from the standard
- # CGI locations, which varies according to the REQUEST_METHOD.
- def initialize(options = {}, &block) # :yields: name, value
- @accept_charset_error_block=block if block_given?
- @options={:accept_charset=>@@accept_charset}
- case options
- when Hash
- @options.merge!(options)
- when String
- @options[:tag_maker]=options
- end
- @accept_charset=@options[:accept_charset]
- if defined?(MOD_RUBY) && !ENV.key?("GATEWAY_INTERFACE")
- Apache.request.setup_cgi_env
- end
-
- extend QueryExtension
- @multipart = false
-
- initialize_query() # set @params, @cookies
- @output_cookies = nil
- @output_hidden = nil
-
- case @options[:tag_maker]
- when "html3"
- require 'cgi/html'
- extend Html3
- element_init()
- extend HtmlExtension
- when "html4"
- require 'cgi/html'
- extend Html4
- element_init()
- extend HtmlExtension
- when "html4Tr"
- require 'cgi/html'
- extend Html4Tr
- element_init()
- extend HtmlExtension
- when "html4Fr"
- require 'cgi/html'
- extend Html4Tr
- element_init()
- extend Html4Fr
- element_init()
- extend HtmlExtension
- end
- end
-
-end # class CGI
-
-
diff --git a/ruby_1_9_3/lib/cgi/html.rb b/ruby_1_9_3/lib/cgi/html.rb
deleted file mode 100644
index 04e2431735..0000000000
--- a/ruby_1_9_3/lib/cgi/html.rb
+++ /dev/null
@@ -1,1021 +0,0 @@
-class CGI
- # Base module for HTML-generation mixins.
- #
- # Provides methods for code generation for tags following
- # the various DTD element types.
- module TagMaker # :nodoc:
-
- # Generate code for an element with required start and end tags.
- #
- # - -
- def nn_element_def(element)
- nOE_element_def(element, <<-END)
- if block_given?
- yield.to_s
- else
- ""
- end +
- "</#{element.upcase}>"
- END
- end
-
- # Generate code for an empty element.
- #
- # - O EMPTY
- def nOE_element_def(element, append = nil)
- s = <<-END
- attributes={attributes=>nil} if attributes.kind_of?(String)
- "<#{element.upcase}" + attributes.collect{|name, value|
- next unless value
- " " + CGI::escapeHTML(name.to_s) +
- if true == value
- ""
- else
- '="' + CGI::escapeHTML(value.to_s) + '"'
- end
- }.join + ">"
- END
- s.sub!(/\Z/, " +") << append if append
- s
- end
-
- # Generate code for an element for which the end (and possibly the
- # start) tag is optional.
- #
- # O O or - O
- def nO_element_def(element)
- nOE_element_def(element, <<-END)
- if block_given?
- yield.to_s + "</#{element.upcase}>"
- else
- ""
- end
- END
- end
-
- end # TagMaker
-
-
- #
- # Mixin module providing HTML generation methods.
- #
- # For example,
- # cgi.a("http://www.example.com") { "Example" }
- # # => "<A HREF=\"http://www.example.com\">Example</A>"
- #
- # Modules Http3, Http4, etc., contain more basic HTML-generation methods
- # (:title, :center, etc.).
- #
- # See class CGI for a detailed example.
- #
- module HtmlExtension
-
-
- # Generate an Anchor element as a string.
- #
- # +href+ can either be a string, giving the URL
- # for the HREF attribute, or it can be a hash of
- # the element's attributes.
- #
- # The body of the element is the string returned by the no-argument
- # block passed in.
- #
- # a("http://www.example.com") { "Example" }
- # # => "<A HREF=\"http://www.example.com\">Example</A>"
- #
- # a("HREF" => "http://www.example.com", "TARGET" => "_top") { "Example" }
- # # => "<A HREF=\"http://www.example.com\" TARGET=\"_top\">Example</A>"
- #
- def a(href = "") # :yield:
- attributes = if href.kind_of?(String)
- { "HREF" => href }
- else
- href
- end
- if block_given?
- super(attributes){ yield }
- else
- super(attributes)
- end
- end
-
- # Generate a Document Base URI element as a String.
- #
- # +href+ can either by a string, giving the base URL for the HREF
- # attribute, or it can be a has of the element's attributes.
- #
- # The passed-in no-argument block is ignored.
- #
- # base("http://www.example.com/cgi")
- # # => "<BASE HREF=\"http://www.example.com/cgi\">"
- def base(href = "") # :yield:
- attributes = if href.kind_of?(String)
- { "HREF" => href }
- else
- href
- end
- if block_given?
- super(attributes){ yield }
- else
- super(attributes)
- end
- end
-
- # Generate a BlockQuote element as a string.
- #
- # +cite+ can either be a string, give the URI for the source of
- # the quoted text, or a hash, giving all attributes of the element,
- # or it can be omitted, in which case the element has no attributes.
- #
- # The body is provided by the passed-in no-argument block
- #
- # blockquote("http://www.example.com/quotes/foo.html") { "Foo!" }
- # #=> "<BLOCKQUOTE CITE=\"http://www.example.com/quotes/foo.html\">Foo!</BLOCKQUOTE>
- def blockquote(cite = {}) # :yield:
- attributes = if cite.kind_of?(String)
- { "CITE" => cite }
- else
- cite
- end
- if block_given?
- super(attributes){ yield }
- else
- super(attributes)
- end
- end
-
-
- # Generate a Table Caption element as a string.
- #
- # +align+ can be a string, giving the alignment of the caption
- # (one of top, bottom, left, or right). It can be a hash of
- # all the attributes of the element. Or it can be omitted.
- #
- # The body of the element is provided by the passed-in no-argument block.
- #
- # caption("left") { "Capital Cities" }
- # # => <CAPTION ALIGN=\"left\">Capital Cities</CAPTION>
- def caption(align = {}) # :yield:
- attributes = if align.kind_of?(String)
- { "ALIGN" => align }
- else
- align
- end
- if block_given?
- super(attributes){ yield }
- else
- super(attributes)
- end
- end
-
-
- # Generate a Checkbox Input element as a string.
- #
- # The attributes of the element can be specified as three arguments,
- # +name+, +value+, and +checked+. +checked+ is a boolean value;
- # if true, the CHECKED attribute will be included in the element.
- #
- # Alternatively, the attributes can be specified as a hash.
- #
- # checkbox("name")
- # # = checkbox("NAME" => "name")
- #
- # checkbox("name", "value")
- # # = checkbox("NAME" => "name", "VALUE" => "value")
- #
- # checkbox("name", "value", true)
- # # = checkbox("NAME" => "name", "VALUE" => "value", "CHECKED" => true)
- def checkbox(name = "", value = nil, checked = nil)
- attributes = if name.kind_of?(String)
- { "TYPE" => "checkbox", "NAME" => name,
- "VALUE" => value, "CHECKED" => checked }
- else
- name["TYPE"] = "checkbox"
- name
- end
- input(attributes)
- end
-
- # Generate a sequence of checkbox elements, as a String.
- #
- # The checkboxes will all have the same +name+ attribute.
- # Each checkbox is followed by a label.
- # There will be one checkbox for each value. Each value
- # can be specified as a String, which will be used both
- # as the value of the VALUE attribute and as the label
- # for that checkbox. A single-element array has the
- # same effect.
- #
- # Each value can also be specified as a three-element array.
- # The first element is the VALUE attribute; the second is the
- # label; and the third is a boolean specifying whether this
- # checkbox is CHECKED.
- #
- # Each value can also be specified as a two-element
- # array, by omitting either the value element (defaults
- # to the same as the label), or the boolean checked element
- # (defaults to false).
- #
- # checkbox_group("name", "foo", "bar", "baz")
- # # <INPUT TYPE="checkbox" NAME="name" VALUE="foo">foo
- # # <INPUT TYPE="checkbox" NAME="name" VALUE="bar">bar
- # # <INPUT TYPE="checkbox" NAME="name" VALUE="baz">baz
- #
- # checkbox_group("name", ["foo"], ["bar", true], "baz")
- # # <INPUT TYPE="checkbox" NAME="name" VALUE="foo">foo
- # # <INPUT TYPE="checkbox" CHECKED NAME="name" VALUE="bar">bar
- # # <INPUT TYPE="checkbox" NAME="name" VALUE="baz">baz
- #
- # checkbox_group("name", ["1", "Foo"], ["2", "Bar", true], "Baz")
- # # <INPUT TYPE="checkbox" NAME="name" VALUE="1">Foo
- # # <INPUT TYPE="checkbox" CHECKED NAME="name" VALUE="2">Bar
- # # <INPUT TYPE="checkbox" NAME="name" VALUE="Baz">Baz
- #
- # checkbox_group("NAME" => "name",
- # "VALUES" => ["foo", "bar", "baz"])
- #
- # checkbox_group("NAME" => "name",
- # "VALUES" => [["foo"], ["bar", true], "baz"])
- #
- # checkbox_group("NAME" => "name",
- # "VALUES" => [["1", "Foo"], ["2", "Bar", true], "Baz"])
- def checkbox_group(name = "", *values)
- if name.kind_of?(Hash)
- values = name["VALUES"]
- name = name["NAME"]
- end
- values.collect{|value|
- if value.kind_of?(String)
- checkbox(name, value) + value
- else
- if value[-1] == true || value[-1] == false
- checkbox(name, value[0], value[-1]) +
- value[-2]
- else
- checkbox(name, value[0]) +
- value[-1]
- end
- end
- }.join
- end
-
-
- # Generate an File Upload Input element as a string.
- #
- # The attributes of the element can be specified as three arguments,
- # +name+, +size+, and +maxlength+. +maxlength+ is the maximum length
- # of the file's _name_, not of the file's _contents_.
- #
- # Alternatively, the attributes can be specified as a hash.
- #
- # See #multipart_form() for forms that include file uploads.
- #
- # file_field("name")
- # # <INPUT TYPE="file" NAME="name" SIZE="20">
- #
- # file_field("name", 40)
- # # <INPUT TYPE="file" NAME="name" SIZE="40">
- #
- # file_field("name", 40, 100)
- # # <INPUT TYPE="file" NAME="name" SIZE="40" MAXLENGTH="100">
- #
- # file_field("NAME" => "name", "SIZE" => 40)
- # # <INPUT TYPE="file" NAME="name" SIZE="40">
- def file_field(name = "", size = 20, maxlength = nil)
- attributes = if name.kind_of?(String)
- { "TYPE" => "file", "NAME" => name,
- "SIZE" => size.to_s }
- else
- name["TYPE"] = "file"
- name
- end
- attributes["MAXLENGTH"] = maxlength.to_s if maxlength
- input(attributes)
- end
-
-
- # Generate a Form element as a string.
- #
- # +method+ should be either "get" or "post", and defaults to the latter.
- # +action+ defaults to the current CGI script name. +enctype+
- # defaults to "application/x-www-form-urlencoded".
- #
- # Alternatively, the attributes can be specified as a hash.
- #
- # See also #multipart_form() for forms that include file uploads.
- #
- # form{ "string" }
- # # <FORM METHOD="post" ENCTYPE="application/x-www-form-urlencoded">string</FORM>
- #
- # form("get") { "string" }
- # # <FORM METHOD="get" ENCTYPE="application/x-www-form-urlencoded">string</FORM>
- #
- # form("get", "url") { "string" }
- # # <FORM METHOD="get" ACTION="url" ENCTYPE="application/x-www-form-urlencoded">string</FORM>
- #
- # form("METHOD" => "post", "ENCTYPE" => "enctype") { "string" }
- # # <FORM METHOD="post" ENCTYPE="enctype">string</FORM>
- def form(method = "post", action = script_name, enctype = "application/x-www-form-urlencoded")
- attributes = if method.kind_of?(String)
- { "METHOD" => method, "ACTION" => action,
- "ENCTYPE" => enctype }
- else
- unless method.has_key?("METHOD")
- method["METHOD"] = "post"
- end
- unless method.has_key?("ENCTYPE")
- method["ENCTYPE"] = enctype
- end
- method
- end
- if block_given?
- body = yield
- else
- body = ""
- end
- if @output_hidden
- body += @output_hidden.collect{|k,v|
- "<INPUT TYPE=\"HIDDEN\" NAME=\"#{k}\" VALUE=\"#{v}\">"
- }.join
- end
- super(attributes){body}
- end
-
- # Generate a Hidden Input element as a string.
- #
- # The attributes of the element can be specified as two arguments,
- # +name+ and +value+.
- #
- # Alternatively, the attributes can be specified as a hash.
- #
- # hidden("name")
- # # <INPUT TYPE="hidden" NAME="name">
- #
- # hidden("name", "value")
- # # <INPUT TYPE="hidden" NAME="name" VALUE="value">
- #
- # hidden("NAME" => "name", "VALUE" => "reset", "ID" => "foo")
- # # <INPUT TYPE="hidden" NAME="name" VALUE="value" ID="foo">
- def hidden(name = "", value = nil)
- attributes = if name.kind_of?(String)
- { "TYPE" => "hidden", "NAME" => name, "VALUE" => value }
- else
- name["TYPE"] = "hidden"
- name
- end
- input(attributes)
- end
-
- # Generate a top-level HTML element as a string.
- #
- # The attributes of the element are specified as a hash. The
- # pseudo-attribute "PRETTY" can be used to specify that the generated
- # HTML string should be indented. "PRETTY" can also be specified as
- # a string as the sole argument to this method. The pseudo-attribute
- # "DOCTYPE", if given, is used as the leading DOCTYPE SGML tag; it
- # should include the entire text of this tag, including angle brackets.
- #
- # The body of the html element is supplied as a block.
- #
- # html{ "string" }
- # # <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><HTML>string</HTML>
- #
- # html("LANG" => "ja") { "string" }
- # # <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><HTML LANG="ja">string</HTML>
- #
- # html("DOCTYPE" => false) { "string" }
- # # <HTML>string</HTML>
- #
- # html("DOCTYPE" => '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">') { "string" }
- # # <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"><HTML>string</HTML>
- #
- # html("PRETTY" => " ") { "<BODY></BODY>" }
- # # <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
- # # <HTML>
- # # <BODY>
- # # </BODY>
- # # </HTML>
- #
- # html("PRETTY" => "\t") { "<BODY></BODY>" }
- # # <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
- # # <HTML>
- # # <BODY>
- # # </BODY>
- # # </HTML>
- #
- # html("PRETTY") { "<BODY></BODY>" }
- # # = html("PRETTY" => " ") { "<BODY></BODY>" }
- #
- # html(if $VERBOSE then "PRETTY" end) { "HTML string" }
- #
- def html(attributes = {}) # :yield:
- if nil == attributes
- attributes = {}
- elsif "PRETTY" == attributes
- attributes = { "PRETTY" => true }
- end
- pretty = attributes.delete("PRETTY")
- pretty = " " if true == pretty
- buf = ""
-
- if attributes.has_key?("DOCTYPE")
- if attributes["DOCTYPE"]
- buf += attributes.delete("DOCTYPE")
- else
- attributes.delete("DOCTYPE")
- end
- else
- buf += doctype
- end
-
- if block_given?
- buf += super(attributes){ yield }
- else
- buf += super(attributes)
- end
-
- if pretty
- CGI::pretty(buf, pretty)
- else
- buf
- end
-
- end
-
- # Generate an Image Button Input element as a string.
- #
- # +src+ is the URL of the image to use for the button. +name+
- # is the input name. +alt+ is the alternative text for the image.
- #
- # Alternatively, the attributes can be specified as a hash.
- #
- # image_button("url")
- # # <INPUT TYPE="image" SRC="url">
- #
- # image_button("url", "name", "string")
- # # <INPUT TYPE="image" SRC="url" NAME="name" ALT="string">
- #
- # image_button("SRC" => "url", "ALT" => "string")
- # # <INPUT TYPE="image" SRC="url" ALT="string">
- def image_button(src = "", name = nil, alt = nil)
- attributes = if src.kind_of?(String)
- { "TYPE" => "image", "SRC" => src, "NAME" => name,
- "ALT" => alt }
- else
- src["TYPE"] = "image"
- src["SRC"] ||= ""
- src
- end
- input(attributes)
- end
-
-
- # Generate an Image element as a string.
- #
- # +src+ is the URL of the image. +alt+ is the alternative text for
- # the image. +width+ is the width of the image, and +height+ is
- # its height.
- #
- # Alternatively, the attributes can be specified as a hash.
- #
- # img("src", "alt", 100, 50)
- # # <IMG SRC="src" ALT="alt" WIDTH="100" HEIGHT="50">
- #
- # img("SRC" => "src", "ALT" => "alt", "WIDTH" => 100, "HEIGHT" => 50)
- # # <IMG SRC="src" ALT="alt" WIDTH="100" HEIGHT="50">
- def img(src = "", alt = "", width = nil, height = nil)
- attributes = if src.kind_of?(String)
- { "SRC" => src, "ALT" => alt }
- else
- src
- end
- attributes["WIDTH"] = width.to_s if width
- attributes["HEIGHT"] = height.to_s if height
- super(attributes)
- end
-
-
- # Generate a Form element with multipart encoding as a String.
- #
- # Multipart encoding is used for forms that include file uploads.
- #
- # +action+ is the action to perform. +enctype+ is the encoding
- # type, which defaults to "multipart/form-data".
- #
- # Alternatively, the attributes can be specified as a hash.
- #
- # multipart_form{ "string" }
- # # <FORM METHOD="post" ENCTYPE="multipart/form-data">string</FORM>
- #
- # multipart_form("url") { "string" }
- # # <FORM METHOD="post" ACTION="url" ENCTYPE="multipart/form-data">string</FORM>
- def multipart_form(action = nil, enctype = "multipart/form-data")
- attributes = if action == nil
- { "METHOD" => "post", "ENCTYPE" => enctype }
- elsif action.kind_of?(String)
- { "METHOD" => "post", "ACTION" => action,
- "ENCTYPE" => enctype }
- else
- unless action.has_key?("METHOD")
- action["METHOD"] = "post"
- end
- unless action.has_key?("ENCTYPE")
- action["ENCTYPE"] = enctype
- end
- action
- end
- if block_given?
- form(attributes){ yield }
- else
- form(attributes)
- end
- end
-
-
- # Generate a Password Input element as a string.
- #
- # +name+ is the name of the input field. +value+ is its default
- # value. +size+ is the size of the input field display. +maxlength+
- # is the maximum length of the inputted password.
- #
- # Alternatively, attributes can be specified as a hash.
- #
- # password_field("name")
- # # <INPUT TYPE="password" NAME="name" SIZE="40">
- #
- # password_field("name", "value")
- # # <INPUT TYPE="password" NAME="name" VALUE="value" SIZE="40">
- #
- # password_field("password", "value", 80, 200)
- # # <INPUT TYPE="password" NAME="name" VALUE="value" SIZE="80" MAXLENGTH="200">
- #
- # password_field("NAME" => "name", "VALUE" => "value")
- # # <INPUT TYPE="password" NAME="name" VALUE="value">
- def password_field(name = "", value = nil, size = 40, maxlength = nil)
- attributes = if name.kind_of?(String)
- { "TYPE" => "password", "NAME" => name,
- "VALUE" => value, "SIZE" => size.to_s }
- else
- name["TYPE"] = "password"
- name
- end
- attributes["MAXLENGTH"] = maxlength.to_s if maxlength
- input(attributes)
- end
-
- # Generate a Select element as a string.
- #
- # +name+ is the name of the element. The +values+ are the options that
- # can be selected from the Select menu. Each value can be a String or
- # a one, two, or three-element Array. If a String or a one-element
- # Array, this is both the value of that option and the text displayed for
- # it. If a three-element Array, the elements are the option value, displayed
- # text, and a boolean value specifying whether this option starts as selected.
- # The two-element version omits either the option value (defaults to the same
- # as the display text) or the boolean selected specifier (defaults to false).
- #
- # The attributes and options can also be specified as a hash. In this
- # case, options are specified as an array of values as described above,
- # with the hash key of "VALUES".
- #
- # popup_menu("name", "foo", "bar", "baz")
- # # <SELECT NAME="name">
- # # <OPTION VALUE="foo">foo</OPTION>
- # # <OPTION VALUE="bar">bar</OPTION>
- # # <OPTION VALUE="baz">baz</OPTION>
- # # </SELECT>
- #
- # popup_menu("name", ["foo"], ["bar", true], "baz")
- # # <SELECT NAME="name">
- # # <OPTION VALUE="foo">foo</OPTION>
- # # <OPTION VALUE="bar" SELECTED>bar</OPTION>
- # # <OPTION VALUE="baz">baz</OPTION>
- # # </SELECT>
- #
- # popup_menu("name", ["1", "Foo"], ["2", "Bar", true], "Baz")
- # # <SELECT NAME="name">
- # # <OPTION VALUE="1">Foo</OPTION>
- # # <OPTION SELECTED VALUE="2">Bar</OPTION>
- # # <OPTION VALUE="Baz">Baz</OPTION>
- # # </SELECT>
- #
- # popup_menu("NAME" => "name", "SIZE" => 2, "MULTIPLE" => true,
- # "VALUES" => [["1", "Foo"], ["2", "Bar", true], "Baz"])
- # # <SELECT NAME="name" MULTIPLE SIZE="2">
- # # <OPTION VALUE="1">Foo</OPTION>
- # # <OPTION SELECTED VALUE="2">Bar</OPTION>
- # # <OPTION VALUE="Baz">Baz</OPTION>
- # # </SELECT>
- def popup_menu(name = "", *values)
-
- if name.kind_of?(Hash)
- values = name["VALUES"]
- size = name["SIZE"].to_s if name["SIZE"]
- multiple = name["MULTIPLE"]
- name = name["NAME"]
- else
- size = nil
- multiple = nil
- end
-
- select({ "NAME" => name, "SIZE" => size,
- "MULTIPLE" => multiple }){
- values.collect{|value|
- if value.kind_of?(String)
- option({ "VALUE" => value }){ value }
- else
- if value[value.size - 1] == true
- option({ "VALUE" => value[0], "SELECTED" => true }){
- value[value.size - 2]
- }
- else
- option({ "VALUE" => value[0] }){
- value[value.size - 1]
- }
- end
- end
- }.join
- }
-
- end
-
- # Generates a radio-button Input element.
- #
- # +name+ is the name of the input field. +value+ is the value of
- # the field if checked. +checked+ specifies whether the field
- # starts off checked.
- #
- # Alternatively, the attributes can be specified as a hash.
- #
- # radio_button("name", "value")
- # # <INPUT TYPE="radio" NAME="name" VALUE="value">
- #
- # radio_button("name", "value", true)
- # # <INPUT TYPE="radio" NAME="name" VALUE="value" CHECKED>
- #
- # radio_button("NAME" => "name", "VALUE" => "value", "ID" => "foo")
- # # <INPUT TYPE="radio" NAME="name" VALUE="value" ID="foo">
- def radio_button(name = "", value = nil, checked = nil)
- attributes = if name.kind_of?(String)
- { "TYPE" => "radio", "NAME" => name,
- "VALUE" => value, "CHECKED" => checked }
- else
- name["TYPE"] = "radio"
- name
- end
- input(attributes)
- end
-
- # Generate a sequence of radio button Input elements, as a String.
- #
- # This works the same as #checkbox_group(). However, it is not valid
- # to have more than one radiobutton in a group checked.
- #
- # radio_group("name", "foo", "bar", "baz")
- # # <INPUT TYPE="radio" NAME="name" VALUE="foo">foo
- # # <INPUT TYPE="radio" NAME="name" VALUE="bar">bar
- # # <INPUT TYPE="radio" NAME="name" VALUE="baz">baz
- #
- # radio_group("name", ["foo"], ["bar", true], "baz")
- # # <INPUT TYPE="radio" NAME="name" VALUE="foo">foo
- # # <INPUT TYPE="radio" CHECKED NAME="name" VALUE="bar">bar
- # # <INPUT TYPE="radio" NAME="name" VALUE="baz">baz
- #
- # radio_group("name", ["1", "Foo"], ["2", "Bar", true], "Baz")
- # # <INPUT TYPE="radio" NAME="name" VALUE="1">Foo
- # # <INPUT TYPE="radio" CHECKED NAME="name" VALUE="2">Bar
- # # <INPUT TYPE="radio" NAME="name" VALUE="Baz">Baz
- #
- # radio_group("NAME" => "name",
- # "VALUES" => ["foo", "bar", "baz"])
- #
- # radio_group("NAME" => "name",
- # "VALUES" => [["foo"], ["bar", true], "baz"])
- #
- # radio_group("NAME" => "name",
- # "VALUES" => [["1", "Foo"], ["2", "Bar", true], "Baz"])
- def radio_group(name = "", *values)
- if name.kind_of?(Hash)
- values = name["VALUES"]
- name = name["NAME"]
- end
- values.collect{|value|
- if value.kind_of?(String)
- radio_button(name, value) + value
- else
- if value[-1] == true || value[-1] == false
- radio_button(name, value[0], value[-1]) +
- value[-2]
- else
- radio_button(name, value[0]) +
- value[-1]
- end
- end
- }.join
- end
-
- # Generate a reset button Input element, as a String.
- #
- # This resets the values on a form to their initial values. +value+
- # is the text displayed on the button. +name+ is the name of this button.
- #
- # Alternatively, the attributes can be specified as a hash.
- #
- # reset
- # # <INPUT TYPE="reset">
- #
- # reset("reset")
- # # <INPUT TYPE="reset" VALUE="reset">
- #
- # reset("VALUE" => "reset", "ID" => "foo")
- # # <INPUT TYPE="reset" VALUE="reset" ID="foo">
- def reset(value = nil, name = nil)
- attributes = if (not value) or value.kind_of?(String)
- { "TYPE" => "reset", "VALUE" => value, "NAME" => name }
- else
- value["TYPE"] = "reset"
- value
- end
- input(attributes)
- end
-
- alias scrolling_list popup_menu
-
- # Generate a submit button Input element, as a String.
- #
- # +value+ is the text to display on the button. +name+ is the name
- # of the input.
- #
- # Alternatively, the attributes can be specified as a hash.
- #
- # submit
- # # <INPUT TYPE="submit">
- #
- # submit("ok")
- # # <INPUT TYPE="submit" VALUE="ok">
- #
- # submit("ok", "button1")
- # # <INPUT TYPE="submit" VALUE="ok" NAME="button1">
- #
- # submit("VALUE" => "ok", "NAME" => "button1", "ID" => "foo")
- # # <INPUT TYPE="submit" VALUE="ok" NAME="button1" ID="foo">
- def submit(value = nil, name = nil)
- attributes = if (not value) or value.kind_of?(String)
- { "TYPE" => "submit", "VALUE" => value, "NAME" => name }
- else
- value["TYPE"] = "submit"
- value
- end
- input(attributes)
- end
-
- # Generate a text field Input element, as a String.
- #
- # +name+ is the name of the input field. +value+ is its initial
- # value. +size+ is the size of the input area. +maxlength+
- # is the maximum length of input accepted.
- #
- # Alternatively, the attributes can be specified as a hash.
- #
- # text_field("name")
- # # <INPUT TYPE="text" NAME="name" SIZE="40">
- #
- # text_field("name", "value")
- # # <INPUT TYPE="text" NAME="name" VALUE="value" SIZE="40">
- #
- # text_field("name", "value", 80)
- # # <INPUT TYPE="text" NAME="name" VALUE="value" SIZE="80">
- #
- # text_field("name", "value", 80, 200)
- # # <INPUT TYPE="text" NAME="name" VALUE="value" SIZE="80" MAXLENGTH="200">
- #
- # text_field("NAME" => "name", "VALUE" => "value")
- # # <INPUT TYPE="text" NAME="name" VALUE="value">
- def text_field(name = "", value = nil, size = 40, maxlength = nil)
- attributes = if name.kind_of?(String)
- { "TYPE" => "text", "NAME" => name, "VALUE" => value,
- "SIZE" => size.to_s }
- else
- name["TYPE"] = "text"
- name
- end
- attributes["MAXLENGTH"] = maxlength.to_s if maxlength
- input(attributes)
- end
-
- # Generate a TextArea element, as a String.
- #
- # +name+ is the name of the textarea. +cols+ is the number of
- # columns and +rows+ is the number of rows in the display.
- #
- # Alternatively, the attributes can be specified as a hash.
- #
- # The body is provided by the passed-in no-argument block
- #
- # textarea("name")
- # # = textarea("NAME" => "name", "COLS" => 70, "ROWS" => 10)
- #
- # textarea("name", 40, 5)
- # # = textarea("NAME" => "name", "COLS" => 40, "ROWS" => 5)
- def textarea(name = "", cols = 70, rows = 10) # :yield:
- attributes = if name.kind_of?(String)
- { "NAME" => name, "COLS" => cols.to_s,
- "ROWS" => rows.to_s }
- else
- name
- end
- if block_given?
- super(attributes){ yield }
- else
- super(attributes)
- end
- end
-
- end # HtmlExtension
-
-
- # Mixin module for HTML version 3 generation methods.
- module Html3 # :nodoc:
-
- # The DOCTYPE declaration for this version of HTML
- def doctype
- %|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">|
- end
-
- # Initialise the HTML generation methods for this version.
- def element_init
- extend TagMaker
- methods = ""
- # - -
- for element in %w[ A TT I B U STRIKE BIG SMALL SUB SUP EM STRONG
- DFN CODE SAMP KBD VAR CITE FONT ADDRESS DIV center MAP
- APPLET PRE XMP LISTING DL OL UL DIR MENU SELECT table TITLE
- STYLE SCRIPT H1 H2 H3 H4 H5 H6 TEXTAREA FORM BLOCKQUOTE
- CAPTION ]
- methods += <<-BEGIN + nn_element_def(element) + <<-END
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- end
-
- # - O EMPTY
- for element in %w[ IMG BASE BASEFONT BR AREA LINK PARAM HR INPUT
- ISINDEX META ]
- methods += <<-BEGIN + nOE_element_def(element) + <<-END
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- end
-
- # O O or - O
- for element in %w[ HTML HEAD BODY P PLAINTEXT DT DD LI OPTION tr
- th td ]
- methods += <<-BEGIN + nO_element_def(element) + <<-END
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- end
- eval(methods)
- end
-
- end # Html3
-
-
- # Mixin module for HTML version 4 generation methods.
- module Html4 # :nodoc:
-
- # The DOCTYPE declaration for this version of HTML
- def doctype
- %|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">|
- end
-
- # Initialise the HTML generation methods for this version.
- def element_init
- extend TagMaker
- methods = ""
- # - -
- for element in %w[ TT I B BIG SMALL EM STRONG DFN CODE SAMP KBD
- VAR CITE ABBR ACRONYM SUB SUP SPAN BDO ADDRESS DIV MAP OBJECT
- H1 H2 H3 H4 H5 H6 PRE Q INS DEL DL OL UL LABEL SELECT OPTGROUP
- FIELDSET LEGEND BUTTON TABLE TITLE STYLE SCRIPT NOSCRIPT
- TEXTAREA FORM A BLOCKQUOTE CAPTION ]
- methods += <<-BEGIN + nn_element_def(element) + <<-END
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- end
-
- # - O EMPTY
- for element in %w[ IMG BASE BR AREA LINK PARAM HR INPUT COL META ]
- methods += <<-BEGIN + nOE_element_def(element) + <<-END
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- end
-
- # O O or - O
- for element in %w[ HTML BODY P DT DD LI OPTION THEAD TFOOT TBODY
- COLGROUP TR TH TD HEAD]
- methods += <<-BEGIN + nO_element_def(element) + <<-END
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- end
- eval(methods)
- end
-
- end # Html4
-
-
- # Mixin module for HTML version 4 transitional generation methods.
- module Html4Tr # :nodoc:
-
- # The DOCTYPE declaration for this version of HTML
- def doctype
- %|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">|
- end
-
- # Initialise the HTML generation methods for this version.
- def element_init
- extend TagMaker
- methods = ""
- # - -
- for element in %w[ TT I B U S STRIKE BIG SMALL EM STRONG DFN
- CODE SAMP KBD VAR CITE ABBR ACRONYM FONT SUB SUP SPAN BDO
- ADDRESS DIV CENTER MAP OBJECT APPLET H1 H2 H3 H4 H5 H6 PRE Q
- INS DEL DL OL UL DIR MENU LABEL SELECT OPTGROUP FIELDSET
- LEGEND BUTTON TABLE IFRAME NOFRAMES TITLE STYLE SCRIPT
- NOSCRIPT TEXTAREA FORM A BLOCKQUOTE CAPTION ]
- methods += <<-BEGIN + nn_element_def(element) + <<-END
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- end
-
- # - O EMPTY
- for element in %w[ IMG BASE BASEFONT BR AREA LINK PARAM HR INPUT
- COL ISINDEX META ]
- methods += <<-BEGIN + nOE_element_def(element) + <<-END
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- end
-
- # O O or - O
- for element in %w[ HTML BODY P DT DD LI OPTION THEAD TFOOT TBODY
- COLGROUP TR TH TD HEAD ]
- methods += <<-BEGIN + nO_element_def(element) + <<-END
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- end
- eval(methods)
- end
-
- end # Html4Tr
-
-
- # Mixin module for generating HTML version 4 with framesets.
- module Html4Fr # :nodoc:
-
- # The DOCTYPE declaration for this version of HTML
- def doctype
- %|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">|
- end
-
- # Initialise the HTML generation methods for this version.
- def element_init
- methods = ""
- # - -
- for element in %w[ FRAMESET ]
- methods += <<-BEGIN + nn_element_def(element) + <<-END
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- end
-
- # - O EMPTY
- for element in %w[ FRAME ]
- methods += <<-BEGIN + nOE_element_def(element) + <<-END
- def #{element.downcase}(attributes = {})
- BEGIN
- end
- END
- end
- eval(methods)
- end
-
- end # Html4Fr
-end
-
-
diff --git a/ruby_1_9_3/lib/cgi/session.rb b/ruby_1_9_3/lib/cgi/session.rb
deleted file mode 100644
index 42b5ead81a..0000000000
--- a/ruby_1_9_3/lib/cgi/session.rb
+++ /dev/null
@@ -1,531 +0,0 @@
-#
-# cgi/session.rb - session support for cgi scripts
-#
-# Copyright (C) 2001 Yukihiro "Matz" Matsumoto
-# Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
-# Copyright (C) 2000 Information-technology Promotion Agency, Japan
-#
-# Author: Yukihiro "Matz" Matsumoto
-#
-# Documentation: William Webber (william@williamwebber.com)
-
-require 'cgi'
-require 'tmpdir'
-
-class CGI
-
- # == Overview
- #
- # This file provides the CGI::Session class, which provides session
- # support for CGI scripts. A session is a sequence of HTTP requests
- # and responses linked together and associated with a single client.
- # Information associated with the session is stored
- # on the server between requests. A session id is passed between client
- # and server with every request and response, transparently
- # to the user. This adds state information to the otherwise stateless
- # HTTP request/response protocol.
- #
- # == Lifecycle
- #
- # A CGI::Session instance is created from a CGI object. By default,
- # this CGI::Session instance will start a new session if none currently
- # exists, or continue the current session for this client if one does
- # exist. The +new_session+ option can be used to either always or
- # never create a new session. See #new() for more details.
- #
- # #delete() deletes a session from session storage. It
- # does not however remove the session id from the client. If the client
- # makes another request with the same id, the effect will be to start
- # a new session with the old session's id.
- #
- # == Setting and retrieving session data.
- #
- # The Session class associates data with a session as key-value pairs.
- # This data can be set and retrieved by indexing the Session instance
- # using '[]', much the same as hashes (although other hash methods
- # are not supported).
- #
- # When session processing has been completed for a request, the
- # session should be closed using the close() method. This will
- # store the session's state to persistent storage. If you want
- # to store the session's state to persistent storage without
- # finishing session processing for this request, call the update()
- # method.
- #
- # == Storing session state
- #
- # The caller can specify what form of storage to use for the session's
- # data with the +database_manager+ option to CGI::Session::new. The
- # following storage classes are provided as part of the standard library:
- #
- # CGI::Session::FileStore:: stores data as plain text in a flat file. Only
- # works with String data. This is the default
- # storage type.
- # CGI::Session::MemoryStore:: stores data in an in-memory hash. The data
- # only persists for as long as the current ruby
- # interpreter instance does.
- # CGI::Session::PStore:: stores data in Marshalled format. Provided by
- # cgi/session/pstore.rb. Supports data of any type,
- # and provides file-locking and transaction support.
- #
- # Custom storage types can also be created by defining a class with
- # the following methods:
- #
- # new(session, options)
- # restore # returns hash of session data.
- # update
- # close
- # delete
- #
- # Changing storage type mid-session does not work. Note in particular
- # that by default the FileStore and PStore session data files have the
- # same name. If your application switches from one to the other without
- # making sure that filenames will be different
- # and clients still have old sessions lying around in cookies, then
- # things will break nastily!
- #
- # == Maintaining the session id.
- #
- # Most session state is maintained on the server. However, a session
- # id must be passed backwards and forwards between client and server
- # to maintain a reference to this session state.
- #
- # The simplest way to do this is via cookies. The CGI::Session class
- # provides transparent support for session id communication via cookies
- # if the client has cookies enabled.
- #
- # If the client has cookies disabled, the session id must be included
- # as a parameter of all requests sent by the client to the server. The
- # CGI::Session class in conjunction with the CGI class will transparently
- # add the session id as a hidden input field to all forms generated
- # using the CGI#form() HTML generation method. No built-in support is
- # provided for other mechanisms, such as URL re-writing. The caller is
- # responsible for extracting the session id from the session_id
- # attribute and manually encoding it in URLs and adding it as a hidden
- # input to HTML forms created by other mechanisms. Also, session expiry
- # is not automatically handled.
- #
- # == Examples of use
- #
- # === Setting the user's name
- #
- # require 'cgi'
- # require 'cgi/session'
- # require 'cgi/session/pstore' # provides CGI::Session::PStore
- #
- # cgi = CGI.new("html4")
- #
- # session = CGI::Session.new(cgi,
- # 'database_manager' => CGI::Session::PStore, # use PStore
- # 'session_key' => '_rb_sess_id', # custom session key
- # 'session_expires' => Time.now + 30 * 60, # 30 minute timeout
- # 'prefix' => 'pstore_sid_') # PStore option
- # if cgi.has_key?('user_name') and cgi['user_name'] != ''
- # # coerce to String: cgi[] returns the
- # # string-like CGI::QueryExtension::Value
- # session['user_name'] = cgi['user_name'].to_s
- # elsif !session['user_name']
- # session['user_name'] = "guest"
- # end
- # session.close
- #
- # === Creating a new session safely
- #
- # require 'cgi'
- # require 'cgi/session'
- #
- # cgi = CGI.new("html4")
- #
- # # We make sure to delete an old session if one exists,
- # # not just to free resources, but to prevent the session
- # # from being maliciously hijacked later on.
- # begin
- # session = CGI::Session.new(cgi, 'new_session' => false)
- # session.delete
- # rescue ArgumentError # if no old session
- # end
- # session = CGI::Session.new(cgi, 'new_session' => true)
- # session.close
- #
- class Session
-
- class NoSession < RuntimeError #:nodoc:
- end
-
- # The id of this session.
- attr_reader :session_id, :new_session
-
- def Session::callback(dbman) #:nodoc:
- Proc.new{
- dbman[0].close unless dbman.empty?
- }
- end
-
- # Create a new session id.
- #
- # The session id is an MD5 hash based upon the time,
- # a random number, and a constant string. This routine
- # is used internally for automatically generated
- # session ids.
- def create_new_id
- require 'securerandom'
- begin
- session_id = SecureRandom.hex(16)
- rescue NotImplementedError
- require 'digest/md5'
- md5 = Digest::MD5::new
- now = Time::now
- md5.update(now.to_s)
- md5.update(String(now.usec))
- md5.update(String(rand(0)))
- md5.update(String($$))
- md5.update('foobar')
- session_id = md5.hexdigest
- end
- session_id
- end
- private :create_new_id
-
- # Create a new CGI::Session object for +request+.
- #
- # +request+ is an instance of the +CGI+ class (see cgi.rb).
- # +option+ is a hash of options for initialising this
- # CGI::Session instance. The following options are
- # recognised:
- #
- # session_key:: the parameter name used for the session id.
- # Defaults to '_session_id'.
- # session_id:: the session id to use. If not provided, then
- # it is retrieved from the +session_key+ parameter
- # of the request, or automatically generated for
- # a new session.
- # new_session:: if true, force creation of a new session. If not set,
- # a new session is only created if none currently
- # exists. If false, a new session is never created,
- # and if none currently exists and the +session_id+
- # option is not set, an ArgumentError is raised.
- # database_manager:: the name of the class providing storage facilities
- # for session state persistence. Built-in support
- # is provided for +FileStore+ (the default),
- # +MemoryStore+, and +PStore+ (from
- # cgi/session/pstore.rb). See the documentation for
- # these classes for more details.
- #
- # The following options are also recognised, but only apply if the
- # session id is stored in a cookie.
- #
- # session_expires:: the time the current session expires, as a
- # +Time+ object. If not set, the session will terminate
- # when the user's browser is closed.
- # session_domain:: the hostname domain for which this session is valid.
- # If not set, defaults to the hostname of the server.
- # session_secure:: if +true+, this session will only work over HTTPS.
- # session_path:: the path for which this session applies. Defaults
- # to the directory of the CGI script.
- #
- # +option+ is also passed on to the session storage class initializer; see
- # the documentation for each session storage class for the options
- # they support.
- #
- # The retrieved or created session is automatically added to +request+
- # as a cookie, and also to its +output_hidden+ table, which is used
- # to add hidden input elements to forms.
- #
- # *WARNING* the +output_hidden+
- # fields are surrounded by a <fieldset> tag in HTML 4 generation, which
- # is _not_ invisible on many browsers; you may wish to disable the
- # use of fieldsets with code similar to the following
- # (see http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-list/37805)
- #
- # cgi = CGI.new("html4")
- # class << cgi
- # undef_method :fieldset
- # end
- #
- def initialize(request, option={})
- @new_session = false
- session_key = option['session_key'] || '_session_id'
- session_id = option['session_id']
- unless session_id
- if option['new_session']
- session_id = create_new_id
- @new_session = true
- end
- end
- unless session_id
- if request.key?(session_key)
- session_id = request[session_key]
- session_id = session_id.read if session_id.respond_to?(:read)
- end
- unless session_id
- session_id, = request.cookies[session_key]
- end
- unless session_id
- unless option.fetch('new_session', true)
- raise ArgumentError, "session_key `%s' should be supplied"%session_key
- end
- session_id = create_new_id
- @new_session = true
- end
- end
- @session_id = session_id
- dbman = option['database_manager'] || FileStore
- begin
- @dbman = dbman::new(self, option)
- rescue NoSession
- unless option.fetch('new_session', true)
- raise ArgumentError, "invalid session_id `%s'"%session_id
- end
- session_id = @session_id = create_new_id unless session_id
- @new_session=true
- retry
- end
- request.instance_eval do
- @output_hidden = {session_key => session_id} unless option['no_hidden']
- @output_cookies = [
- Cookie::new("name" => session_key,
- "value" => session_id,
- "expires" => option['session_expires'],
- "domain" => option['session_domain'],
- "secure" => option['session_secure'],
- "path" =>
- if option['session_path']
- option['session_path']
- elsif ENV["SCRIPT_NAME"]
- File::dirname(ENV["SCRIPT_NAME"])
- else
- ""
- end)
- ] unless option['no_cookies']
- end
- @dbprot = [@dbman]
- ObjectSpace::define_finalizer(self, Session::callback(@dbprot))
- end
-
- # Retrieve the session data for key +key+.
- def [](key)
- @data ||= @dbman.restore
- @data[key]
- end
-
- # Set the session date for key +key+.
- def []=(key, val)
- @write_lock ||= true
- @data ||= @dbman.restore
- @data[key] = val
- end
-
- # Store session data on the server. For some session storage types,
- # this is a no-op.
- def update
- @dbman.update
- end
-
- # Store session data on the server and close the session storage.
- # For some session storage types, this is a no-op.
- def close
- @dbman.close
- @dbprot.clear
- end
-
- # Delete the session from storage. Also closes the storage.
- #
- # Note that the session's data is _not_ automatically deleted
- # upon the session expiring.
- def delete
- @dbman.delete
- @dbprot.clear
- end
-
- # File-based session storage class.
- #
- # Implements session storage as a flat file of 'key=value' values.
- # This storage type only works directly with String values; the
- # user is responsible for converting other types to Strings when
- # storing and from Strings when retrieving.
- class FileStore
- # Create a new FileStore instance.
- #
- # This constructor is used internally by CGI::Session. The
- # user does not generally need to call it directly.
- #
- # +session+ is the session for which this instance is being
- # created. The session id must only contain alphanumeric
- # characters; automatically generated session ids observe
- # this requirement.
- #
- # +option+ is a hash of options for the initializer. The
- # following options are recognised:
- #
- # tmpdir:: the directory to use for storing the FileStore
- # file. Defaults to Dir::tmpdir (generally "/tmp"
- # on Unix systems).
- # prefix:: the prefix to add to the session id when generating
- # the filename for this session's FileStore file.
- # Defaults to "cgi_sid_".
- # suffix:: the prefix to add to the session id when generating
- # the filename for this session's FileStore file.
- # Defaults to the empty string.
- #
- # This session's FileStore file will be created if it does
- # not exist, or opened if it does.
- def initialize(session, option={})
- dir = option['tmpdir'] || Dir::tmpdir
- prefix = option['prefix'] || 'cgi_sid_'
- suffix = option['suffix'] || ''
- id = session.session_id
- require 'digest/md5'
- md5 = Digest::MD5.hexdigest(id)[0,16]
- @path = dir+"/"+prefix+md5+suffix
- if File::exist? @path
- @hash = nil
- else
- unless session.new_session
- raise CGI::Session::NoSession, "uninitialized session"
- end
- @hash = {}
- end
- end
-
- # Restore session state from the session's FileStore file.
- #
- # Returns the session state as a hash.
- def restore
- unless @hash
- @hash = {}
- begin
- lockf = File.open(@path+".lock", "r")
- lockf.flock File::LOCK_SH
- f = File.open(@path, 'r')
- for line in f
- line.chomp!
- k, v = line.split('=',2)
- @hash[CGI::unescape(k)] = Marshal.restore(CGI::unescape(v))
- end
- ensure
- f.close unless f.nil?
- lockf.close if lockf
- end
- end
- @hash
- end
-
- # Save session state to the session's FileStore file.
- def update
- return unless @hash
- begin
- lockf = File.open(@path+".lock", File::CREAT|File::RDWR, 0600)
- lockf.flock File::LOCK_EX
- f = File.open(@path+".new", File::CREAT|File::TRUNC|File::WRONLY, 0600)
- for k,v in @hash
- f.printf "%s=%s\n", CGI::escape(k), CGI::escape(String(Marshal.dump(v)))
- end
- f.close
- File.rename @path+".new", @path
- ensure
- f.close if f and !f.closed?
- lockf.close if lockf
- end
- end
-
- # Update and close the session's FileStore file.
- def close
- update
- end
-
- # Close and delete the session's FileStore file.
- def delete
- File::unlink @path+".lock" rescue nil
- File::unlink @path+".new" rescue nil
- File::unlink @path rescue Errno::ENOENT
- end
- end
-
- # In-memory session storage class.
- #
- # Implements session storage as a global in-memory hash. Session
- # data will only persist for as long as the ruby interpreter
- # instance does.
- class MemoryStore
- GLOBAL_HASH_TABLE = {} #:nodoc:
-
- # Create a new MemoryStore instance.
- #
- # +session+ is the session this instance is associated with.
- # +option+ is a list of initialisation options. None are
- # currently recognised.
- def initialize(session, option=nil)
- @session_id = session.session_id
- unless GLOBAL_HASH_TABLE.key?(@session_id)
- unless session.new_session
- raise CGI::Session::NoSession, "uninitialized session"
- end
- GLOBAL_HASH_TABLE[@session_id] = {}
- end
- end
-
- # Restore session state.
- #
- # Returns session data as a hash.
- def restore
- GLOBAL_HASH_TABLE[@session_id]
- end
-
- # Update session state.
- #
- # A no-op.
- def update
- # don't need to update; hash is shared
- end
-
- # Close session storage.
- #
- # A no-op.
- def close
- # don't need to close
- end
-
- # Delete the session state.
- def delete
- GLOBAL_HASH_TABLE.delete(@session_id)
- end
- end
-
- # Dummy session storage class.
- #
- # Implements session storage place holder. No actual storage
- # will be done.
- class NullStore
- # Create a new NullStore instance.
- #
- # +session+ is the session this instance is associated with.
- # +option+ is a list of initialisation options. None are
- # currently recognised.
- def initialize(session, option=nil)
- end
-
- # Restore (empty) session state.
- def restore
- {}
- end
-
- # Update session state.
- #
- # A no-op.
- def update
- end
-
- # Close session storage.
- #
- # A no-op.
- def close
- end
-
- # Delete the session state.
- #
- # A no-op.
- def delete
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/cgi/session/pstore.rb b/ruby_1_9_3/lib/cgi/session/pstore.rb
deleted file mode 100644
index a63d7d3984..0000000000
--- a/ruby_1_9_3/lib/cgi/session/pstore.rb
+++ /dev/null
@@ -1,111 +0,0 @@
-#
-# cgi/session/pstore.rb - persistent storage of marshalled session data
-#
-# Documentation: William Webber (william@williamwebber.com)
-#
-# == Overview
-#
-# This file provides the CGI::Session::PStore class, which builds
-# persistent of session data on top of the pstore library. See
-# cgi/session.rb for more details on session storage managers.
-
-require 'cgi/session'
-require 'pstore'
-
-class CGI
- class Session
- # PStore-based session storage class.
- #
- # This builds upon the top-level PStore class provided by the
- # library file pstore.rb. Session data is marshalled and stored
- # in a file. File locking and transaction services are provided.
- class PStore
- # Create a new CGI::Session::PStore instance
- #
- # This constructor is used internally by CGI::Session. The
- # user does not generally need to call it directly.
- #
- # +session+ is the session for which this instance is being
- # created. The session id must only contain alphanumeric
- # characters; automatically generated session ids observe
- # this requirement.
- #
- # +option+ is a hash of options for the initializer. The
- # following options are recognised:
- #
- # tmpdir:: the directory to use for storing the PStore
- # file. Defaults to Dir::tmpdir (generally "/tmp"
- # on Unix systems).
- # prefix:: the prefix to add to the session id when generating
- # the filename for this session's PStore file.
- # Defaults to the empty string.
- #
- # This session's PStore file will be created if it does
- # not exist, or opened if it does.
- def initialize(session, option={})
- dir = option['tmpdir'] || Dir::tmpdir
- prefix = option['prefix'] || ''
- id = session.session_id
- require 'digest/md5'
- md5 = Digest::MD5.hexdigest(id)[0,16]
- path = dir+"/"+prefix+md5
- path.untaint
- if File::exist?(path)
- @hash = nil
- else
- unless session.new_session
- raise CGI::Session::NoSession, "uninitialized session"
- end
- @hash = {}
- end
- @p = ::PStore.new(path)
- @p.transaction do |p|
- File.chmod(0600, p.path)
- end
- end
-
- # Restore session state from the session's PStore file.
- #
- # Returns the session state as a hash.
- def restore
- unless @hash
- @p.transaction do
- @hash = @p['hash'] || {}
- end
- end
- @hash
- end
-
- # Save session state to the session's PStore file.
- def update
- @p.transaction do
- @p['hash'] = @hash
- end
- end
-
- # Update and close the session's PStore file.
- def close
- update
- end
-
- # Close and delete the session's PStore file.
- def delete
- path = @p.path
- File::unlink path
- end
-
- end
- end
-end
-
-if $0 == __FILE__
- # :enddoc:
- STDIN.reopen("/dev/null")
- cgi = CGI.new
- session = CGI::Session.new(cgi, 'database_manager' => CGI::Session::PStore)
- session['key'] = {'k' => 'v'}
- puts session['key'].class
- fail unless Hash === session['key']
- puts session['key'].inspect
- fail unless session['key'].inspect == '{"k"=>"v"}'
-end
diff --git a/ruby_1_9_3/lib/cgi/util.rb b/ruby_1_9_3/lib/cgi/util.rb
deleted file mode 100644
index 2bb3b0da78..0000000000
--- a/ruby_1_9_3/lib/cgi/util.rb
+++ /dev/null
@@ -1,194 +0,0 @@
-class CGI
- @@accept_charset="UTF-8" unless defined?(@@accept_charset)
- # URL-encode a string.
- # url_encoded_string = CGI::escape("'Stop!' said Fred")
- # # => "%27Stop%21%27+said+Fred"
- def CGI::escape(string)
- string.gsub(/([^ a-zA-Z0-9_.-]+)/) do
- '%' + $1.unpack('H2' * $1.bytesize).join('%').upcase
- end.tr(' ', '+')
- end
-
- # URL-decode a string with encoding(optional).
- # string = CGI::unescape("%27Stop%21%27+said+Fred")
- # # => "'Stop!' said Fred"
- def CGI::unescape(string,encoding=@@accept_charset)
- str=string.tr('+', ' ').force_encoding(Encoding::ASCII_8BIT).gsub(/((?:%[0-9a-fA-F]{2})+)/) do
- [$1.delete('%')].pack('H*')
- end.force_encoding(encoding)
- str.valid_encoding? ? str : str.force_encoding(string.encoding)
- end
-
- # The set of special characters and their escaped values
- TABLE_FOR_ESCAPE_HTML__ = {
- '&' => '&amp;',
- '"' => '&quot;',
- '<' => '&lt;',
- '>' => '&gt;',
- }
-
- # Escape special characters in HTML, namely &\"<>
- # CGI::escapeHTML('Usage: foo "bar" <baz>')
- # # => "Usage: foo &quot;bar&quot; &lt;baz&gt;"
- def CGI::escapeHTML(string)
- string.gsub(/[&\"<>]/, TABLE_FOR_ESCAPE_HTML__)
- end
-
- # Unescape a string that has been HTML-escaped
- # CGI::unescapeHTML("Usage: foo &quot;bar&quot; &lt;baz&gt;")
- # # => "Usage: foo \"bar\" <baz>"
- def CGI::unescapeHTML(string)
- enc = string.encoding
- if [Encoding::UTF_16BE, Encoding::UTF_16LE, Encoding::UTF_32BE, Encoding::UTF_32LE].include?(enc)
- return string.gsub(Regexp.new('&(amp|quot|gt|lt|#[0-9]+|#x[0-9A-Fa-f]+);'.encode(enc))) do
- case $1.encode("US-ASCII")
- when 'amp' then '&'.encode(enc)
- when 'quot' then '"'.encode(enc)
- when 'gt' then '>'.encode(enc)
- when 'lt' then '<'.encode(enc)
- when /\A#0*(\d+)\z/ then $1.to_i.chr(enc)
- when /\A#x([0-9a-f]+)\z/i then $1.hex.chr(enc)
- end
- end
- end
- asciicompat = Encoding.compatible?(string, "a")
- string.gsub(/&(amp|quot|gt|lt|\#[0-9]+|\#x[0-9A-Fa-f]+);/) do
- match = $1.dup
- case match
- when 'amp' then '&'
- when 'quot' then '"'
- when 'gt' then '>'
- when 'lt' then '<'
- when /\A#0*(\d+)\z/
- n = $1.to_i
- if enc == Encoding::UTF_8 or
- enc == Encoding::ISO_8859_1 && n < 256 or
- asciicompat && n < 128
- n.chr(enc)
- else
- "&##{$1};"
- end
- when /\A#x([0-9a-f]+)\z/i
- n = $1.hex
- if enc == Encoding::UTF_8 or
- enc == Encoding::ISO_8859_1 && n < 256 or
- asciicompat && n < 128
- n.chr(enc)
- else
- "&#x#{$1};"
- end
- else
- "&#{match};"
- end
- end
- end
-
- # Synonym for CGI::escapeHTML(str)
- def CGI::escape_html(str)
- escapeHTML(str)
- end
-
- # Synonym for CGI::unescapeHTML(str)
- def CGI::unescape_html(str)
- unescapeHTML(str)
- end
-
- # Escape only the tags of certain HTML elements in +string+.
- #
- # Takes an element or elements or array of elements. Each element
- # is specified by the name of the element, without angle brackets.
- # This matches both the start and the end tag of that element.
- # The attribute list of the open tag will also be escaped (for
- # instance, the double-quotes surrounding attribute values).
- #
- # print CGI::escapeElement('<BR><A HREF="url"></A>', "A", "IMG")
- # # "<BR>&lt;A HREF=&quot;url&quot;&gt;&lt;/A&gt"
- #
- # print CGI::escapeElement('<BR><A HREF="url"></A>', ["A", "IMG"])
- # # "<BR>&lt;A HREF=&quot;url&quot;&gt;&lt;/A&gt"
- def CGI::escapeElement(string, *elements)
- elements = elements[0] if elements[0].kind_of?(Array)
- unless elements.empty?
- string.gsub(/<\/?(?:#{elements.join("|")})(?!\w)(?:.|\n)*?>/i) do
- CGI::escapeHTML($&)
- end
- else
- string
- end
- end
-
- # Undo escaping such as that done by CGI::escapeElement()
- #
- # print CGI::unescapeElement(
- # CGI::escapeHTML('<BR><A HREF="url"></A>'), "A", "IMG")
- # # "&lt;BR&gt;<A HREF="url"></A>"
- #
- # print CGI::unescapeElement(
- # CGI::escapeHTML('<BR><A HREF="url"></A>'), ["A", "IMG"])
- # # "&lt;BR&gt;<A HREF="url"></A>"
- def CGI::unescapeElement(string, *elements)
- elements = elements[0] if elements[0].kind_of?(Array)
- unless elements.empty?
- string.gsub(/&lt;\/?(?:#{elements.join("|")})(?!\w)(?:.|\n)*?&gt;/i) do
- CGI::unescapeHTML($&)
- end
- else
- string
- end
- end
-
- # Synonym for CGI::escapeElement(str)
- def CGI::escape_element(str)
- escapeElement(str)
- end
-
- # Synonym for CGI::unescapeElement(str)
- def CGI::unescape_element(str)
- unescapeElement(str)
- end
-
- # Abbreviated day-of-week names specified by RFC 822
- RFC822_DAYS = %w[ Sun Mon Tue Wed Thu Fri Sat ]
-
- # Abbreviated month names specified by RFC 822
- RFC822_MONTHS = %w[ Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ]
-
- # Format a +Time+ object as a String using the format specified by RFC 1123.
- #
- # CGI::rfc1123_date(Time.now)
- # # Sat, 01 Jan 2000 00:00:00 GMT
- def CGI::rfc1123_date(time)
- t = time.clone.gmtime
- return format("%s, %.2d %s %.4d %.2d:%.2d:%.2d GMT",
- RFC822_DAYS[t.wday], t.day, RFC822_MONTHS[t.month-1], t.year,
- t.hour, t.min, t.sec)
- end
-
- # Prettify (indent) an HTML string.
- #
- # +string+ is the HTML string to indent. +shift+ is the indentation
- # unit to use; it defaults to two spaces.
- #
- # print CGI::pretty("<HTML><BODY></BODY></HTML>")
- # # <HTML>
- # # <BODY>
- # # </BODY>
- # # </HTML>
- #
- # print CGI::pretty("<HTML><BODY></BODY></HTML>", "\t")
- # # <HTML>
- # # <BODY>
- # # </BODY>
- # # </HTML>
- #
- def CGI::pretty(string, shift = " ")
- lines = string.gsub(/(?!\A)<.*?>/m, "\n\\0").gsub(/<.*?>(?!\n)/m, "\\0\n")
- end_pos = 0
- while end_pos = lines.index(/^<\/(\w+)/, end_pos)
- element = $1.dup
- start_pos = lines.rindex(/^\s*<#{element}/i, end_pos)
- lines[start_pos ... end_pos] = "__" + lines[start_pos ... end_pos].gsub(/\n(?!\z)/, "\n" + shift) + "__"
- end
- lines.gsub(/^((?:#{Regexp::quote(shift)})*)__(?=<\/?\w)/, '\1')
- end
-end
diff --git a/ruby_1_9_3/lib/cmath.rb b/ruby_1_9_3/lib/cmath.rb
deleted file mode 100644
index d613a3f6f9..0000000000
--- a/ruby_1_9_3/lib/cmath.rb
+++ /dev/null
@@ -1,402 +0,0 @@
-##
-# = CMath
-#
-# CMath is a library that provides trigonometric and transcendental
-# functions for complex numbers.
-#
-# == Usage
-#
-# To start using this library, simply:
-#
-# require "cmath"
-#
-# Square root of a negative number is a complex number.
-#
-# CMath.sqrt(-9) #=> 0+3.0i
-#
-
-module CMath
-
- include Math
-
- alias exp! exp
- alias log! log
- alias log2! log2
- alias log10! log10
- alias sqrt! sqrt
- alias cbrt! cbrt
-
- alias sin! sin
- alias cos! cos
- alias tan! tan
-
- alias sinh! sinh
- alias cosh! cosh
- alias tanh! tanh
-
- alias asin! asin
- alias acos! acos
- alias atan! atan
- alias atan2! atan2
-
- alias asinh! asinh
- alias acosh! acosh
- alias atanh! atanh
-
- ##
- # Math::E raised to the +z+ power
- #
- # exp(Complex(0,0)) #=> 1.0+0.0i
- # exp(Complex(0,PI)) #=> -1.0+1.2246467991473532e-16i
- # exp(Complex(0,PI/2.0)) #=> 6.123233995736766e-17+1.0i
- def exp(z)
- begin
- if z.real?
- exp!(z)
- else
- ere = exp!(z.real)
- Complex(ere * cos!(z.imag),
- ere * sin!(z.imag))
- end
- rescue NoMethodError
- handle_no_method_error
- end
- end
-
- ##
- # Returns the natural logarithm of Complex. If a second argument is given,
- # it will be the base of logarithm.
- #
- # log(Complex(0,0)) #=> -Infinity+0.0i
- def log(*args)
- begin
- z, b = args
- unless b.nil? || b.kind_of?(Numeric)
- raise TypeError, "Numeric Number required"
- end
- if z.real? and z >= 0 and (b.nil? or b >= 0)
- log!(*args)
- else
- a = Complex(log!(z.abs), z.arg)
- if b
- a /= log(b)
- end
- a
- end
- rescue NoMethodError
- handle_no_method_error
- end
- end
-
- ##
- # returns the base 2 logarithm of +z+
- def log2(z)
- begin
- if z.real? and z >= 0
- log2!(z)
- else
- log(z) / log!(2)
- end
- rescue NoMethodError
- handle_no_method_error
- end
- end
-
- ##
- # returns the base 10 logarithm of +z+
- def log10(z)
- begin
- if z.real? and z >= 0
- log10!(z)
- else
- log(z) / log!(10)
- end
- rescue NoMethodError
- handle_no_method_error
- end
- end
-
- ##
- # Returns the non-negative square root of Complex.
- # sqrt(-1) #=> 0+1.0i
- # sqrt(Complex(-1,0)) #=> 0.0+1.0i
- # sqrt(Complex(0,8)) #=> 2.0+2.0i
- def sqrt(z)
- begin
- if z.real?
- if z < 0
- Complex(0, sqrt!(-z))
- else
- sqrt!(z)
- end
- else
- if z.imag < 0 ||
- (z.imag == 0 && z.imag.to_s[0] == '-')
- sqrt(z.conjugate).conjugate
- else
- r = z.abs
- x = z.real
- Complex(sqrt!((r + x) / 2.0), sqrt!((r - x) / 2.0))
- end
- end
- rescue NoMethodError
- handle_no_method_error
- end
- end
-
- ##
- # returns the principal value of the cube root of +z+
- def cbrt(z)
- z ** (1.0/3)
- end
-
- ##
- # returns the sine of +z+, where +z+ is given in radians
- def sin(z)
- begin
- if z.real?
- sin!(z)
- else
- Complex(sin!(z.real) * cosh!(z.imag),
- cos!(z.real) * sinh!(z.imag))
- end
- rescue NoMethodError
- handle_no_method_error
- end
- end
-
- ##
- # returns the cosine of +z+, where +z+ is given in radians
- def cos(z)
- begin
- if z.real?
- cos!(z)
- else
- Complex(cos!(z.real) * cosh!(z.imag),
- -sin!(z.real) * sinh!(z.imag))
- end
- rescue NoMethodError
- handle_no_method_error
- end
- end
-
- ##
- # returns the tangent of +z+, where +z+ is given in radians
- def tan(z)
- begin
- if z.real?
- tan!(z)
- else
- sin(z) / cos(z)
- end
- rescue NoMethodError
- handle_no_method_error
- end
- end
-
- ##
- # returns the hyperbolic sine of +z+, where +z+ is given in radians
- def sinh(z)
- begin
- if z.real?
- sinh!(z)
- else
- Complex(sinh!(z.real) * cos!(z.imag),
- cosh!(z.real) * sin!(z.imag))
- end
- rescue NoMethodError
- handle_no_method_error
- end
- end
-
- ##
- # returns the hyperbolic cosine of +z+, where +z+ is given in radians
- def cosh(z)
- begin
- if z.real?
- cosh!(z)
- else
- Complex(cosh!(z.real) * cos!(z.imag),
- sinh!(z.real) * sin!(z.imag))
- end
- rescue NoMethodError
- handle_no_method_error
- end
- end
-
- ##
- # returns the hyperbolic tangent of +z+, where +z+ is given in radians
- def tanh(z)
- begin
- if z.real?
- tanh!(z)
- else
- sinh(z) / cosh(z)
- end
- rescue NoMethodError
- handle_no_method_error
- end
- end
-
- ##
- # returns the arc sine of +z+
- def asin(z)
- begin
- if z.real? and z >= -1 and z <= 1
- asin!(z)
- else
- (-1.0).i * log(1.0.i * z + sqrt(1.0 - z * z))
- end
- rescue NoMethodError
- handle_no_method_error
- end
- end
-
- ##
- # returns the arc cosine of +z+
- def acos(z)
- begin
- if z.real? and z >= -1 and z <= 1
- acos!(z)
- else
- (-1.0).i * log(z + 1.0.i * sqrt(1.0 - z * z))
- end
- rescue NoMethodError
- handle_no_method_error
- end
- end
-
- ##
- # returns the arc tangent of +z+
- def atan(z)
- begin
- if z.real?
- atan!(z)
- else
- 1.0.i * log((1.0.i + z) / (1.0.i - z)) / 2.0
- end
- rescue NoMethodError
- handle_no_method_error
- end
- end
-
- ##
- # returns the arc tangent of +y+ divided by +x+ using the signs of +y+ and
- # +x+ to determine the quadrant
- def atan2(y,x)
- begin
- if y.real? and x.real?
- atan2!(y,x)
- else
- (-1.0).i * log((x + 1.0.i * y) / sqrt(x * x + y * y))
- end
- rescue NoMethodError
- handle_no_method_error
- end
- end
-
- ##
- # returns the inverse hyperbolic sine of +z+
- def asinh(z)
- begin
- if z.real?
- asinh!(z)
- else
- log(z + sqrt(1.0 + z * z))
- end
- rescue NoMethodError
- handle_no_method_error
- end
- end
-
- ##
- # returns the inverse hyperbolic cosine of +z+
- def acosh(z)
- begin
- if z.real? and z >= 1
- acosh!(z)
- else
- log(z + sqrt(z * z - 1.0))
- end
- rescue NoMethodError
- handle_no_method_error
- end
- end
-
- ##
- # returns the inverse hyperbolic tangent of +z+
- def atanh(z)
- begin
- if z.real? and z >= -1 and z <= 1
- atanh!(z)
- else
- log((1.0 + z) / (1.0 - z)) / 2.0
- end
- rescue NoMethodError
- handle_no_method_error
- end
- end
-
- module_function :exp!
- module_function :exp
- module_function :log!
- module_function :log
- module_function :log2!
- module_function :log2
- module_function :log10!
- module_function :log10
- module_function :sqrt!
- module_function :sqrt
- module_function :cbrt!
- module_function :cbrt
-
- module_function :sin!
- module_function :sin
- module_function :cos!
- module_function :cos
- module_function :tan!
- module_function :tan
-
- module_function :sinh!
- module_function :sinh
- module_function :cosh!
- module_function :cosh
- module_function :tanh!
- module_function :tanh
-
- module_function :asin!
- module_function :asin
- module_function :acos!
- module_function :acos
- module_function :atan!
- module_function :atan
- module_function :atan2!
- module_function :atan2
-
- module_function :asinh!
- module_function :asinh
- module_function :acosh!
- module_function :acosh
- module_function :atanh!
- module_function :atanh
-
- module_function :frexp
- module_function :ldexp
- module_function :hypot
- module_function :erf
- module_function :erfc
- module_function :gamma
- module_function :lgamma
-
- private
- def handle_no_method_error # :nodoc:
- if $!.name == :real?
- raise TypeError, "Numeric Number required"
- else
- raise
- end
- end
- module_function :handle_no_method_error
-
-end
-
diff --git a/ruby_1_9_3/lib/complex.rb b/ruby_1_9_3/lib/complex.rb
deleted file mode 100644
index 9c57ecdf7a..0000000000
--- a/ruby_1_9_3/lib/complex.rb
+++ /dev/null
@@ -1,28 +0,0 @@
-# :enddoc:
-
-warn('lib/complex.rb is deprecated') if $VERBOSE
-
-require 'cmath'
-
-unless defined?(Math.exp!)
- Object.instance_eval{remove_const :Math}
- Math = CMath
-end
-
-def Complex.generic? (other)
- other.kind_of?(Integer) ||
- other.kind_of?(Float) ||
- other.kind_of?(Rational)
-end
-
-class Complex
-
- alias image imag
-
-end
-
-class Numeric
-
- def im() Complex(0, self) end
-
-end
diff --git a/ruby_1_9_3/lib/csv.rb b/ruby_1_9_3/lib/csv.rb
deleted file mode 100644
index 13f86ec318..0000000000
--- a/ruby_1_9_3/lib/csv.rb
+++ /dev/null
@@ -1,2356 +0,0 @@
-# encoding: US-ASCII
-# = csv.rb -- CSV Reading and Writing
-#
-# Created by James Edward Gray II on 2005-10-31.
-# Copyright 2005 James Edward Gray II. You can redistribute or modify this code
-# under the terms of Ruby's license.
-#
-# See CSV for documentation.
-#
-# == Description
-#
-# Welcome to the new and improved CSV.
-#
-# This version of the CSV library began its life as FasterCSV. FasterCSV was
-# intended as a replacement to Ruby's then standard CSV library. It was
-# designed to address concerns users of that library had and it had three
-# primary goals:
-#
-# 1. Be significantly faster than CSV while remaining a pure Ruby library.
-# 2. Use a smaller and easier to maintain code base. (FasterCSV eventually
-# grew larger, was also but considerably richer in features. The parsing
-# core remains quite small.)
-# 3. Improve on the CSV interface.
-#
-# Obviously, the last one is subjective. I did try to defer to the original
-# interface whenever I didn't have a compelling reason to change it though, so
-# hopefully this won't be too radically different.
-#
-# We must have met our goals because FasterCSV was renamed to CSV and replaced
-# the original library as of Ruby 1.9. If you are migrating code from 1.8 or
-# earlier, you may have to change your code to comply with the new interface.
-#
-# == What's Different From the Old CSV?
-#
-# I'm sure I'll miss something, but I'll try to mention most of the major
-# differences I am aware of, to help others quickly get up to speed:
-#
-# === CSV Parsing
-#
-# * This parser is m17n aware. See CSV for full details.
-# * This library has a stricter parser and will throw MalformedCSVErrors on
-# problematic data.
-# * This library has a less liberal idea of a line ending than CSV. What you
-# set as the <tt>:row_sep</tt> is law. It can auto-detect your line endings
-# though.
-# * The old library returned empty lines as <tt>[nil]</tt>. This library calls
-# them <tt>[]</tt>.
-# * This library has a much faster parser.
-#
-# === Interface
-#
-# * CSV now uses Hash-style parameters to set options.
-# * CSV no longer has generate_row() or parse_row().
-# * The old CSV's Reader and Writer classes have been dropped.
-# * CSV::open() is now more like Ruby's open().
-# * CSV objects now support most standard IO methods.
-# * CSV now has a new() method used to wrap objects like String and IO for
-# reading and writing.
-# * CSV::generate() is different from the old method.
-# * CSV no longer supports partial reads. It works line-by-line.
-# * CSV no longer allows the instance methods to override the separators for
-# performance reasons. They must be set in the constructor.
-#
-# If you use this library and find yourself missing any functionality I have
-# trimmed, please {let me know}[mailto:james@grayproductions.net].
-#
-# == Documentation
-#
-# See CSV for documentation.
-#
-# == What is CSV, really?
-#
-# CSV maintains a pretty strict definition of CSV taken directly from
-# {the RFC}[http://www.ietf.org/rfc/rfc4180.txt]. I relax the rules in only one
-# place and that is to make using this library easier. CSV will parse all valid
-# CSV.
-#
-# What you don't want to do is feed CSV invalid data. Because of the way the
-# CSV format works, it's common for a parser to need to read until the end of
-# the file to be sure a field is invalid. This eats a lot of time and memory.
-#
-# Luckily, when working with invalid CSV, Ruby's built-in methods will almost
-# always be superior in every way. For example, parsing non-quoted fields is as
-# easy as:
-#
-# data.split(",")
-#
-# == Questions and/or Comments
-#
-# Feel free to email {James Edward Gray II}[mailto:james@grayproductions.net]
-# with any questions.
-
-require "forwardable"
-require "English"
-require "date"
-require "stringio"
-
-#
-# This class provides a complete interface to CSV files and data. It offers
-# tools to enable you to read and write to and from Strings or IO objects, as
-# needed.
-#
-# == Reading
-#
-# === From a File
-#
-# ==== A Line at a Time
-#
-# CSV.foreach("path/to/file.csv") do |row|
-# # use row here...
-# end
-#
-# ==== All at Once
-#
-# arr_of_arrs = CSV.read("path/to/file.csv")
-#
-# === From a String
-#
-# ==== A Line at a Time
-#
-# CSV.parse("CSV,data,String") do |row|
-# # use row here...
-# end
-#
-# ==== All at Once
-#
-# arr_of_arrs = CSV.parse("CSV,data,String")
-#
-# == Writing
-#
-# === To a File
-#
-# CSV.open("path/to/file.csv", "wb") do |csv|
-# csv << ["row", "of", "CSV", "data"]
-# csv << ["another", "row"]
-# # ...
-# end
-#
-# === To a String
-#
-# csv_string = CSV.generate do |csv|
-# csv << ["row", "of", "CSV", "data"]
-# csv << ["another", "row"]
-# # ...
-# end
-#
-# == Convert a Single Line
-#
-# csv_string = ["CSV", "data"].to_csv # to CSV
-# csv_array = "CSV,String".parse_csv # from CSV
-#
-# == Shortcut Interface
-#
-# CSV { |csv_out| csv_out << %w{my data here} } # to $stdout
-# CSV(csv = "") { |csv_str| csv_str << %w{my data here} } # to a String
-# CSV($stderr) { |csv_err| csv_err << %w{my data here} } # to $stderr
-# CSV($stdin) { |csv_in| csv_in.each { |row| p row } } # from $stdin
-#
-# == Advanced Usage
-#
-# === Wrap an IO Object
-#
-# csv = CSV.new(io, options)
-# # ... read (with gets() or each()) from and write (with <<) to csv here ...
-#
-# == CSV and Character Encodings (M17n or Multilingualization)
-#
-# This new CSV parser is m17n savvy. The parser works in the Encoding of the IO
-# or String object being read from or written to. Your data is never transcoded
-# (unless you ask Ruby to transcode it for you) and will literally be parsed in
-# the Encoding it is in. Thus CSV will return Arrays or Rows of Strings in the
-# Encoding of your data. This is accomplished by transcoding the parser itself
-# into your Encoding.
-#
-# Some transcoding must take place, of course, to accomplish this multiencoding
-# support. For example, <tt>:col_sep</tt>, <tt>:row_sep</tt>, and
-# <tt>:quote_char</tt> must be transcoded to match your data. Hopefully this
-# makes the entire process feel transparent, since CSV's defaults should just
-# magically work for you data. However, you can set these values manually in
-# the target Encoding to avoid the translation.
-#
-# It's also important to note that while all of CSV's core parser is now
-# Encoding agnostic, some features are not. For example, the built-in
-# converters will try to transcode data to UTF-8 before making conversions.
-# Again, you can provide custom converters that are aware of your Encodings to
-# avoid this translation. It's just too hard for me to support native
-# conversions in all of Ruby's Encodings.
-#
-# Anyway, the practical side of this is simple: make sure IO and String objects
-# passed into CSV have the proper Encoding set and everything should just work.
-# CSV methods that allow you to open IO objects (CSV::foreach(), CSV::open(),
-# CSV::read(), and CSV::readlines()) do allow you to specify the Encoding.
-#
-# One minor exception comes when generating CSV into a String with an Encoding
-# that is not ASCII compatible. There's no existing data for CSV to use to
-# prepare itself and thus you will probably need to manually specify the desired
-# Encoding for most of those cases. It will try to guess using the fields in a
-# row of output though, when using CSV::generate_line() or Array#to_csv().
-#
-# I try to point out any other Encoding issues in the documentation of methods
-# as they come up.
-#
-# This has been tested to the best of my ability with all non-"dummy" Encodings
-# Ruby ships with. However, it is brave new code and may have some bugs.
-# Please feel free to {report}[mailto:james@grayproductions.net] any issues you
-# find with it.
-#
-class CSV
- # The version of the installed library.
- VERSION = "2.4.8".freeze
-
- #
- # A CSV::Row is part Array and part Hash. It retains an order for the fields
- # and allows duplicates just as an Array would, but also allows you to access
- # fields by name just as you could if they were in a Hash.
- #
- # All rows returned by CSV will be constructed from this class, if header row
- # processing is activated.
- #
- class Row
- #
- # Construct a new CSV::Row from +headers+ and +fields+, which are expected
- # to be Arrays. If one Array is shorter than the other, it will be padded
- # with +nil+ objects.
- #
- # The optional +header_row+ parameter can be set to +true+ to indicate, via
- # CSV::Row.header_row?() and CSV::Row.field_row?(), that this is a header
- # row. Otherwise, the row is assumes to be a field row.
- #
- # A CSV::Row object supports the following Array methods through delegation:
- #
- # * empty?()
- # * length()
- # * size()
- #
- def initialize(headers, fields, header_row = false)
- @header_row = header_row
-
- # handle extra headers or fields
- @row = if headers.size > fields.size
- headers.zip(fields)
- else
- fields.zip(headers).map { |pair| pair.reverse }
- end
- end
-
- # Internal data format used to compare equality.
- attr_reader :row
- protected :row
-
- ### Array Delegation ###
-
- extend Forwardable
- def_delegators :@row, :empty?, :length, :size
-
- # Returns +true+ if this is a header row.
- def header_row?
- @header_row
- end
-
- # Returns +true+ if this is a field row.
- def field_row?
- not header_row?
- end
-
- # Returns the headers of this row.
- def headers
- @row.map { |pair| pair.first }
- end
-
- #
- # :call-seq:
- # field( header )
- # field( header, offset )
- # field( index )
- #
- # This method will fetch the field value by +header+ or +index+. If a field
- # is not found, +nil+ is returned.
- #
- # When provided, +offset+ ensures that a header match occurrs on or later
- # than the +offset+ index. You can use this to find duplicate headers,
- # without resorting to hard-coding exact indices.
- #
- def field(header_or_index, minimum_index = 0)
- # locate the pair
- finder = header_or_index.is_a?(Integer) ? :[] : :assoc
- pair = @row[minimum_index..-1].send(finder, header_or_index)
-
- # return the field if we have a pair
- pair.nil? ? nil : pair.last
- end
- alias_method :[], :field
-
- #
- # :call-seq:
- # []=( header, value )
- # []=( header, offset, value )
- # []=( index, value )
- #
- # Looks up the field by the semantics described in CSV::Row.field() and
- # assigns the +value+.
- #
- # Assigning past the end of the row with an index will set all pairs between
- # to <tt>[nil, nil]</tt>. Assigning to an unused header appends the new
- # pair.
- #
- def []=(*args)
- value = args.pop
-
- if args.first.is_a? Integer
- if @row[args.first].nil? # extending past the end with index
- @row[args.first] = [nil, value]
- @row.map! { |pair| pair.nil? ? [nil, nil] : pair }
- else # normal index assignment
- @row[args.first][1] = value
- end
- else
- index = index(*args)
- if index.nil? # appending a field
- self << [args.first, value]
- else # normal header assignment
- @row[index][1] = value
- end
- end
- end
-
- #
- # :call-seq:
- # <<( field )
- # <<( header_and_field_array )
- # <<( header_and_field_hash )
- #
- # If a two-element Array is provided, it is assumed to be a header and field
- # and the pair is appended. A Hash works the same way with the key being
- # the header and the value being the field. Anything else is assumed to be
- # a lone field which is appended with a +nil+ header.
- #
- # This method returns the row for chaining.
- #
- def <<(arg)
- if arg.is_a?(Array) and arg.size == 2 # appending a header and name
- @row << arg
- elsif arg.is_a?(Hash) # append header and name pairs
- arg.each { |pair| @row << pair }
- else # append field value
- @row << [nil, arg]
- end
-
- self # for chaining
- end
-
- #
- # A shortcut for appending multiple fields. Equivalent to:
- #
- # args.each { |arg| csv_row << arg }
- #
- # This method returns the row for chaining.
- #
- def push(*args)
- args.each { |arg| self << arg }
-
- self # for chaining
- end
-
- #
- # :call-seq:
- # delete( header )
- # delete( header, offset )
- # delete( index )
- #
- # Used to remove a pair from the row by +header+ or +index+. The pair is
- # located as described in CSV::Row.field(). The deleted pair is returned,
- # or +nil+ if a pair could not be found.
- #
- def delete(header_or_index, minimum_index = 0)
- if header_or_index.is_a? Integer # by index
- @row.delete_at(header_or_index)
- elsif i = index(header_or_index, minimum_index) # by header
- @row.delete_at(i)
- else
- [ ]
- end
- end
-
- #
- # The provided +block+ is passed a header and field for each pair in the row
- # and expected to return +true+ or +false+, depending on whether the pair
- # should be deleted.
- #
- # This method returns the row for chaining.
- #
- def delete_if(&block)
- @row.delete_if(&block)
-
- self # for chaining
- end
-
- #
- # This method accepts any number of arguments which can be headers, indices,
- # Ranges of either, or two-element Arrays containing a header and offset.
- # Each argument will be replaced with a field lookup as described in
- # CSV::Row.field().
- #
- # If called with no arguments, all fields are returned.
- #
- def fields(*headers_and_or_indices)
- if headers_and_or_indices.empty? # return all fields--no arguments
- @row.map { |pair| pair.last }
- else # or work like values_at()
- headers_and_or_indices.inject(Array.new) do |all, h_or_i|
- all + if h_or_i.is_a? Range
- index_begin = h_or_i.begin.is_a?(Integer) ? h_or_i.begin :
- index(h_or_i.begin)
- index_end = h_or_i.end.is_a?(Integer) ? h_or_i.end :
- index(h_or_i.end)
- new_range = h_or_i.exclude_end? ? (index_begin...index_end) :
- (index_begin..index_end)
- fields.values_at(new_range)
- else
- [field(*Array(h_or_i))]
- end
- end
- end
- end
- alias_method :values_at, :fields
-
- #
- # :call-seq:
- # index( header )
- # index( header, offset )
- #
- # This method will return the index of a field with the provided +header+.
- # The +offset+ can be used to locate duplicate header names, as described in
- # CSV::Row.field().
- #
- def index(header, minimum_index = 0)
- # find the pair
- index = headers[minimum_index..-1].index(header)
- # return the index at the right offset, if we found one
- index.nil? ? nil : index + minimum_index
- end
-
- # Returns +true+ if +name+ is a header for this row, and +false+ otherwise.
- def header?(name)
- headers.include? name
- end
- alias_method :include?, :header?
-
- #
- # Returns +true+ if +data+ matches a field in this row, and +false+
- # otherwise.
- #
- def field?(data)
- fields.include? data
- end
-
- include Enumerable
-
- #
- # Yields each pair of the row as header and field tuples (much like
- # iterating over a Hash).
- #
- # Support for Enumerable.
- #
- # This method returns the row for chaining.
- #
- def each(&block)
- @row.each(&block)
-
- self # for chaining
- end
-
- #
- # Returns +true+ if this row contains the same headers and fields in the
- # same order as +other+.
- #
- def ==(other)
- @row == other.row
- end
-
- #
- # Collapses the row into a simple Hash. Be warning that this discards field
- # order and clobbers duplicate fields.
- #
- def to_hash
- # flatten just one level of the internal Array
- Hash[*@row.inject(Array.new) { |ary, pair| ary.push(*pair) }]
- end
-
- #
- # Returns the row as a CSV String. Headers are not used. Equivalent to:
- #
- # csv_row.fields.to_csv( options )
- #
- def to_csv(options = Hash.new)
- fields.to_csv(options)
- end
- alias_method :to_s, :to_csv
-
- # A summary of fields, by header, in an ASCII compatible String.
- def inspect
- str = ["#<", self.class.to_s]
- each do |header, field|
- str << " " << (header.is_a?(Symbol) ? header.to_s : header.inspect) <<
- ":" << field.inspect
- end
- str << ">"
- begin
- str.join('')
- rescue # any encoding error
- str.map do |s|
- e = Encoding::Converter.asciicompat_encoding(s.encoding)
- e ? s.encode(e) : s.force_encoding("ASCII-8BIT")
- end.join('')
- end
- end
- end
-
- #
- # A CSV::Table is a two-dimensional data structure for representing CSV
- # documents. Tables allow you to work with the data by row or column,
- # manipulate the data, and even convert the results back to CSV, if needed.
- #
- # All tables returned by CSV will be constructed from this class, if header
- # row processing is activated.
- #
- class Table
- #
- # Construct a new CSV::Table from +array_of_rows+, which are expected
- # to be CSV::Row objects. All rows are assumed to have the same headers.
- #
- # A CSV::Table object supports the following Array methods through
- # delegation:
- #
- # * empty?()
- # * length()
- # * size()
- #
- def initialize(array_of_rows)
- @table = array_of_rows
- @mode = :col_or_row
- end
-
- # The current access mode for indexing and iteration.
- attr_reader :mode
-
- # Internal data format used to compare equality.
- attr_reader :table
- protected :table
-
- ### Array Delegation ###
-
- extend Forwardable
- def_delegators :@table, :empty?, :length, :size
-
- #
- # Returns a duplicate table object, in column mode. This is handy for
- # chaining in a single call without changing the table mode, but be aware
- # that this method can consume a fair amount of memory for bigger data sets.
- #
- # This method returns the duplicate table for chaining. Don't chain
- # destructive methods (like []=()) this way though, since you are working
- # with a duplicate.
- #
- def by_col
- self.class.new(@table.dup).by_col!
- end
-
- #
- # Switches the mode of this table to column mode. All calls to indexing and
- # iteration methods will work with columns until the mode is changed again.
- #
- # This method returns the table and is safe to chain.
- #
- def by_col!
- @mode = :col
-
- self
- end
-
- #
- # Returns a duplicate table object, in mixed mode. This is handy for
- # chaining in a single call without changing the table mode, but be aware
- # that this method can consume a fair amount of memory for bigger data sets.
- #
- # This method returns the duplicate table for chaining. Don't chain
- # destructive methods (like []=()) this way though, since you are working
- # with a duplicate.
- #
- def by_col_or_row
- self.class.new(@table.dup).by_col_or_row!
- end
-
- #
- # Switches the mode of this table to mixed mode. All calls to indexing and
- # iteration methods will use the default intelligent indexing system until
- # the mode is changed again. In mixed mode an index is assumed to be a row
- # reference while anything else is assumed to be column access by headers.
- #
- # This method returns the table and is safe to chain.
- #
- def by_col_or_row!
- @mode = :col_or_row
-
- self
- end
-
- #
- # Returns a duplicate table object, in row mode. This is handy for chaining
- # in a single call without changing the table mode, but be aware that this
- # method can consume a fair amount of memory for bigger data sets.
- #
- # This method returns the duplicate table for chaining. Don't chain
- # destructive methods (like []=()) this way though, since you are working
- # with a duplicate.
- #
- def by_row
- self.class.new(@table.dup).by_row!
- end
-
- #
- # Switches the mode of this table to row mode. All calls to indexing and
- # iteration methods will work with rows until the mode is changed again.
- #
- # This method returns the table and is safe to chain.
- #
- def by_row!
- @mode = :row
-
- self
- end
-
- #
- # Returns the headers for the first row of this table (assumed to match all
- # other rows). An empty Array is returned for empty tables.
- #
- def headers
- if @table.empty?
- Array.new
- else
- @table.first.headers
- end
- end
-
- #
- # In the default mixed mode, this method returns rows for index access and
- # columns for header access. You can force the index association by first
- # calling by_col!() or by_row!().
- #
- # Columns are returned as an Array of values. Altering that Array has no
- # effect on the table.
- #
- def [](index_or_header)
- if @mode == :row or # by index
- (@mode == :col_or_row and index_or_header.is_a? Integer)
- @table[index_or_header]
- else # by header
- @table.map { |row| row[index_or_header] }
- end
- end
-
- #
- # In the default mixed mode, this method assigns rows for index access and
- # columns for header access. You can force the index association by first
- # calling by_col!() or by_row!().
- #
- # Rows may be set to an Array of values (which will inherit the table's
- # headers()) or a CSV::Row.
- #
- # Columns may be set to a single value, which is copied to each row of the
- # column, or an Array of values. Arrays of values are assigned to rows top
- # to bottom in row major order. Excess values are ignored and if the Array
- # does not have a value for each row the extra rows will receive a +nil+.
- #
- # Assigning to an existing column or row clobbers the data. Assigning to
- # new columns creates them at the right end of the table.
- #
- def []=(index_or_header, value)
- if @mode == :row or # by index
- (@mode == :col_or_row and index_or_header.is_a? Integer)
- if value.is_a? Array
- @table[index_or_header] = Row.new(headers, value)
- else
- @table[index_or_header] = value
- end
- else # set column
- if value.is_a? Array # multiple values
- @table.each_with_index do |row, i|
- if row.header_row?
- row[index_or_header] = index_or_header
- else
- row[index_or_header] = value[i]
- end
- end
- else # repeated value
- @table.each do |row|
- if row.header_row?
- row[index_or_header] = index_or_header
- else
- row[index_or_header] = value
- end
- end
- end
- end
- end
-
- #
- # The mixed mode default is to treat a list of indices as row access,
- # returning the rows indicated. Anything else is considered columnar
- # access. For columnar access, the return set has an Array for each row
- # with the values indicated by the headers in each Array. You can force
- # column or row mode using by_col!() or by_row!().
- #
- # You cannot mix column and row access.
- #
- def values_at(*indices_or_headers)
- if @mode == :row or # by indices
- ( @mode == :col_or_row and indices_or_headers.all? do |index|
- index.is_a?(Integer) or
- ( index.is_a?(Range) and
- index.first.is_a?(Integer) and
- index.last.is_a?(Integer) )
- end )
- @table.values_at(*indices_or_headers)
- else # by headers
- @table.map { |row| row.values_at(*indices_or_headers) }
- end
- end
-
- #
- # Adds a new row to the bottom end of this table. You can provide an Array,
- # which will be converted to a CSV::Row (inheriting the table's headers()),
- # or a CSV::Row.
- #
- # This method returns the table for chaining.
- #
- def <<(row_or_array)
- if row_or_array.is_a? Array # append Array
- @table << Row.new(headers, row_or_array)
- else # append Row
- @table << row_or_array
- end
-
- self # for chaining
- end
-
- #
- # A shortcut for appending multiple rows. Equivalent to:
- #
- # rows.each { |row| self << row }
- #
- # This method returns the table for chaining.
- #
- def push(*rows)
- rows.each { |row| self << row }
-
- self # for chaining
- end
-
- #
- # Removes and returns the indicated column or row. In the default mixed
- # mode indices refer to rows and everything else is assumed to be a column
- # header. Use by_col!() or by_row!() to force the lookup.
- #
- def delete(index_or_header)
- if @mode == :row or # by index
- (@mode == :col_or_row and index_or_header.is_a? Integer)
- @table.delete_at(index_or_header)
- else # by header
- @table.map { |row| row.delete(index_or_header).last }
- end
- end
-
- #
- # Removes any column or row for which the block returns +true+. In the
- # default mixed mode or row mode, iteration is the standard row major
- # walking of rows. In column mode, interation will +yield+ two element
- # tuples containing the column name and an Array of values for that column.
- #
- # This method returns the table for chaining.
- #
- def delete_if(&block)
- if @mode == :row or @mode == :col_or_row # by index
- @table.delete_if(&block)
- else # by header
- to_delete = Array.new
- headers.each_with_index do |header, i|
- to_delete << header if block[[header, self[header]]]
- end
- to_delete.map { |header| delete(header) }
- end
-
- self # for chaining
- end
-
- include Enumerable
-
- #
- # In the default mixed mode or row mode, iteration is the standard row major
- # walking of rows. In column mode, interation will +yield+ two element
- # tuples containing the column name and an Array of values for that column.
- #
- # This method returns the table for chaining.
- #
- def each(&block)
- if @mode == :col
- headers.each { |header| block[[header, self[header]]] }
- else
- @table.each(&block)
- end
-
- self # for chaining
- end
-
- # Returns +true+ if all rows of this table ==() +other+'s rows.
- def ==(other)
- @table == other.table
- end
-
- #
- # Returns the table as an Array of Arrays. Headers will be the first row,
- # then all of the field rows will follow.
- #
- def to_a
- @table.inject([headers]) do |array, row|
- if row.header_row?
- array
- else
- array + [row.fields]
- end
- end
- end
-
- #
- # Returns the table as a complete CSV String. Headers will be listed first,
- # then all of the field rows.
- #
- # This method assumes you want the Table.headers(), unless you explicitly
- # pass <tt>:write_headers => false</tt>.
- #
- def to_csv(options = Hash.new)
- wh = options.fetch(:write_headers, true)
- @table.inject(wh ? [headers.to_csv(options)] : [ ]) do |rows, row|
- if row.header_row?
- rows
- else
- rows + [row.fields.to_csv(options)]
- end
- end.join('')
- end
- alias_method :to_s, :to_csv
-
- # Shows the mode and size of this table in a US-ASCII String.
- def inspect
- "#<#{self.class} mode:#{@mode} row_count:#{to_a.size}>".encode("US-ASCII")
- end
- end
-
- # The error thrown when the parser encounters illegal CSV formatting.
- class MalformedCSVError < RuntimeError; end
-
- #
- # A FieldInfo Struct contains details about a field's position in the data
- # source it was read from. CSV will pass this Struct to some blocks that make
- # decisions based on field structure. See CSV.convert_fields() for an
- # example.
- #
- # <b><tt>index</tt></b>:: The zero-based index of the field in its row.
- # <b><tt>line</tt></b>:: The line of the data source this row is from.
- # <b><tt>header</tt></b>:: The header for the column, when available.
- #
- FieldInfo = Struct.new(:index, :line, :header)
-
- # A Regexp used to find and convert some common Date formats.
- DateMatcher = / \A(?: (\w+,?\s+)?\w+\s+\d{1,2},?\s+\d{2,4} |
- \d{4}-\d{2}-\d{2} )\z /x
- # A Regexp used to find and convert some common DateTime formats.
- DateTimeMatcher =
- / \A(?: (\w+,?\s+)?\w+\s+\d{1,2}\s+\d{1,2}:\d{1,2}:\d{1,2},?\s+\d{2,4} |
- \d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2} )\z /x
-
- # The encoding used by all converters.
- ConverterEncoding = Encoding.find("UTF-8")
-
- #
- # This Hash holds the built-in converters of CSV that can be accessed by name.
- # You can select Converters with CSV.convert() or through the +options+ Hash
- # passed to CSV::new().
- #
- # <b><tt>:integer</tt></b>:: Converts any field Integer() accepts.
- # <b><tt>:float</tt></b>:: Converts any field Float() accepts.
- # <b><tt>:numeric</tt></b>:: A combination of <tt>:integer</tt>
- # and <tt>:float</tt>.
- # <b><tt>:date</tt></b>:: Converts any field Date::parse() accepts.
- # <b><tt>:date_time</tt></b>:: Converts any field DateTime::parse() accepts.
- # <b><tt>:all</tt></b>:: All built-in converters. A combination of
- # <tt>:date_time</tt> and <tt>:numeric</tt>.
- #
- # All built-in converters transcode field data to UTF-8 before attempting a
- # conversion. If your data cannot be transcoded to UTF-8 the conversion will
- # fail and the field will remain unchanged.
- #
- # This Hash is intentionally left unfrozen and users should feel free to add
- # values to it that can be accessed by all CSV objects.
- #
- # To add a combo field, the value should be an Array of names. Combo fields
- # can be nested with other combo fields.
- #
- Converters = { integer: lambda { |f|
- Integer(f.encode(ConverterEncoding)) rescue f
- },
- float: lambda { |f|
- Float(f.encode(ConverterEncoding)) rescue f
- },
- numeric: [:integer, :float],
- date: lambda { |f|
- begin
- e = f.encode(ConverterEncoding)
- e =~ DateMatcher ? Date.parse(e) : f
- rescue # encoding conversion or date parse errors
- f
- end
- },
- date_time: lambda { |f|
- begin
- e = f.encode(ConverterEncoding)
- e =~ DateTimeMatcher ? DateTime.parse(e) : f
- rescue # encoding conversion or date parse errors
- f
- end
- },
- all: [:date_time, :numeric] }
-
- #
- # This Hash holds the built-in header converters of CSV that can be accessed
- # by name. You can select HeaderConverters with CSV.header_convert() or
- # through the +options+ Hash passed to CSV::new().
- #
- # <b><tt>:downcase</tt></b>:: Calls downcase() on the header String.
- # <b><tt>:symbol</tt></b>:: The header String is downcased, spaces are
- # replaced with underscores, non-word characters
- # are dropped, and finally to_sym() is called.
- #
- # All built-in header converters transcode header data to UTF-8 before
- # attempting a conversion. If your data cannot be transcoded to UTF-8 the
- # conversion will fail and the header will remain unchanged.
- #
- # This Hash is intetionally left unfrozen and users should feel free to add
- # values to it that can be accessed by all CSV objects.
- #
- # To add a combo field, the value should be an Array of names. Combo fields
- # can be nested with other combo fields.
- #
- HeaderConverters = {
- downcase: lambda { |h| h.encode(ConverterEncoding).downcase },
- symbol: lambda { |h|
- h.encode(ConverterEncoding).downcase.gsub(/\s+/, "_").
- gsub(/\W+/, "").to_sym
- }
- }
-
- #
- # The options used when no overrides are given by calling code. They are:
- #
- # <b><tt>:col_sep</tt></b>:: <tt>","</tt>
- # <b><tt>:row_sep</tt></b>:: <tt>:auto</tt>
- # <b><tt>:quote_char</tt></b>:: <tt>'"'</tt>
- # <b><tt>:field_size_limit</tt></b>:: +nil+
- # <b><tt>:converters</tt></b>:: +nil+
- # <b><tt>:unconverted_fields</tt></b>:: +nil+
- # <b><tt>:headers</tt></b>:: +false+
- # <b><tt>:return_headers</tt></b>:: +false+
- # <b><tt>:header_converters</tt></b>:: +nil+
- # <b><tt>:skip_blanks</tt></b>:: +false+
- # <b><tt>:force_quotes</tt></b>:: +false+
- #
- DEFAULT_OPTIONS = { col_sep: ",",
- row_sep: :auto,
- quote_char: '"',
- field_size_limit: nil,
- converters: nil,
- unconverted_fields: nil,
- headers: false,
- return_headers: false,
- header_converters: nil,
- skip_blanks: false,
- force_quotes: false }.freeze
-
- #
- # This method will return a CSV instance, just like CSV::new(), but the
- # instance will be cached and returned for all future calls to this method for
- # the same +data+ object (tested by Object#object_id()) with the same
- # +options+.
- #
- # If a block is given, the instance is passed to the block and the return
- # value becomes the return value of the block.
- #
- def self.instance(data = $stdout, options = Hash.new)
- # create a _signature_ for this method call, data object and options
- sig = [data.object_id] +
- options.values_at(*DEFAULT_OPTIONS.keys.sort_by { |sym| sym.to_s })
-
- # fetch or create the instance for this signature
- @@instances ||= Hash.new
- instance = (@@instances[sig] ||= new(data, options))
-
- if block_given?
- yield instance # run block, if given, returning result
- else
- instance # or return the instance
- end
- end
-
- #
- # This method allows you to serialize an Array of Ruby objects to a String or
- # File of CSV data. This is not as powerful as Marshal or YAML, but perhaps
- # useful for spreadsheet and database interaction.
- #
- # Out of the box, this method is intended to work with simple data objects or
- # Structs. It will serialize a list of instance variables and/or
- # Struct.members().
- #
- # If you need need more complicated serialization, you can control the process
- # by adding methods to the class to be serialized.
- #
- # A class method csv_meta() is responsible for returning the first row of the
- # document (as an Array). This row is considered to be a Hash of the form
- # key_1,value_1,key_2,value_2,... CSV::load() expects to find a class key
- # with a value of the stringified class name and CSV::dump() will create this,
- # if you do not define this method. This method is only called on the first
- # object of the Array.
- #
- # The next method you can provide is an instance method called csv_headers().
- # This method is expected to return the second line of the document (again as
- # an Array), which is to be used to give each column a header. By default,
- # CSV::load() will set an instance variable if the field header starts with an
- # @ character or call send() passing the header as the method name and
- # the field value as an argument. This method is only called on the first
- # object of the Array.
- #
- # Finally, you can provide an instance method called csv_dump(), which will
- # be passed the headers. This should return an Array of fields that can be
- # serialized for this object. This method is called once for every object in
- # the Array.
- #
- # The +io+ parameter can be used to serialize to a File, and +options+ can be
- # anything CSV::new() accepts.
- #
- def self.dump(ary_of_objs, io = "", options = Hash.new)
- obj_template = ary_of_objs.first
-
- csv = new(io, options)
-
- # write meta information
- begin
- csv << obj_template.class.csv_meta
- rescue NoMethodError
- csv << [:class, obj_template.class]
- end
-
- # write headers
- begin
- headers = obj_template.csv_headers
- rescue NoMethodError
- headers = obj_template.instance_variables.sort
- if obj_template.class.ancestors.find { |cls| cls.to_s =~ /\AStruct\b/ }
- headers += obj_template.members.map { |mem| "#{mem}=" }.sort
- end
- end
- csv << headers
-
- # serialize each object
- ary_of_objs.each do |obj|
- begin
- csv << obj.csv_dump(headers)
- rescue NoMethodError
- csv << headers.map do |var|
- if var[0] == ?@
- obj.instance_variable_get(var)
- else
- obj[var[0..-2]]
- end
- end
- end
- end
-
- if io.is_a? String
- csv.string
- else
- csv.close
- end
- end
-
- #
- # This method is the reading counterpart to CSV::dump(). See that method for
- # a detailed description of the process.
- #
- # You can customize loading by adding a class method called csv_load() which
- # will be passed a Hash of meta information, an Array of headers, and an Array
- # of fields for the object the method is expected to return.
- #
- # Remember that all fields will be Strings after this load. If you need
- # something else, use +options+ to setup converters or provide a custom
- # csv_load() implementation.
- #
- def self.load(io_or_str, options = Hash.new)
- csv = new(io_or_str, options)
-
- # load meta information
- meta = Hash[*csv.shift]
- cls = meta["class".encode(csv.encoding)].split("::".encode(csv.encoding)).
- inject(Object) do |c, const|
- c.const_get(const)
- end
-
- # load headers
- headers = csv.shift
-
- # unserialize each object stored in the file
- results = csv.inject(Array.new) do |all, row|
- begin
- obj = cls.csv_load(meta, headers, row)
- rescue NoMethodError
- obj = cls.allocate
- headers.zip(row) do |name, value|
- if name[0] == ?@
- obj.instance_variable_set(name, value)
- else
- obj.send(name, value)
- end
- end
- end
- all << obj
- end
-
- csv.close unless io_or_str.is_a? String
-
- results
- end
-
- #
- # :call-seq:
- # filter( options = Hash.new ) { |row| ... }
- # filter( input, options = Hash.new ) { |row| ... }
- # filter( input, output, options = Hash.new ) { |row| ... }
- #
- # This method is a convenience for building Unix-like filters for CSV data.
- # Each row is yielded to the provided block which can alter it as needed.
- # After the block returns, the row is appended to +output+ altered or not.
- #
- # The +input+ and +output+ arguments can be anything CSV::new() accepts
- # (generally String or IO objects). If not given, they default to
- # <tt>ARGF</tt> and <tt>$stdout</tt>.
- #
- # The +options+ parameter is also filtered down to CSV::new() after some
- # clever key parsing. Any key beginning with <tt>:in_</tt> or
- # <tt>:input_</tt> will have that leading identifier stripped and will only
- # be used in the +options+ Hash for the +input+ object. Keys starting with
- # <tt>:out_</tt> or <tt>:output_</tt> affect only +output+. All other keys
- # are assigned to both objects.
- #
- # The <tt>:output_row_sep</tt> +option+ defaults to
- # <tt>$INPUT_RECORD_SEPARATOR</tt> (<tt>$/</tt>).
- #
- def self.filter(*args)
- # parse options for input, output, or both
- in_options, out_options = Hash.new, {row_sep: $INPUT_RECORD_SEPARATOR}
- if args.last.is_a? Hash
- args.pop.each do |key, value|
- case key.to_s
- when /\Ain(?:put)?_(.+)\Z/
- in_options[$1.to_sym] = value
- when /\Aout(?:put)?_(.+)\Z/
- out_options[$1.to_sym] = value
- else
- in_options[key] = value
- out_options[key] = value
- end
- end
- end
- # build input and output wrappers
- input = new(args.shift || ARGF, in_options)
- output = new(args.shift || $stdout, out_options)
-
- # read, yield, write
- input.each do |row|
- yield row
- output << row
- end
- end
-
- #
- # This method is intended as the primary interface for reading CSV files. You
- # pass a +path+ and any +options+ you wish to set for the read. Each row of
- # file will be passed to the provided +block+ in turn.
- #
- # The +options+ parameter can be anything CSV::new() understands. This method
- # also understands an additional <tt>:encoding</tt> parameter that you can use
- # to specify the Encoding of the data in the file to be read. You must provide
- # this unless your data is in Encoding::default_external(). CSV will use this
- # to determine how to parse the data. You may provide a second Encoding to
- # have the data transcoded as it is read. For example,
- # <tt>encoding: "UTF-32BE:UTF-8"</tt> would read UTF-32BE data from the file
- # but transcode it to UTF-8 before CSV parses it.
- #
- def self.foreach(path, options = Hash.new, &block)
- open(path, options) do |csv|
- csv.each(&block)
- end
- end
-
- #
- # :call-seq:
- # generate( str, options = Hash.new ) { |csv| ... }
- # generate( options = Hash.new ) { |csv| ... }
- #
- # This method wraps a String you provide, or an empty default String, in a
- # CSV object which is passed to the provided block. You can use the block to
- # append CSV rows to the String and when the block exits, the final String
- # will be returned.
- #
- # Note that a passed String *is* modfied by this method. Call dup() before
- # passing if you need a new String.
- #
- # The +options+ parameter can be anything CSV::new() understands. This method
- # understands an additional <tt>:encoding</tt> parameter when not passed a
- # String to set the base Encoding for the output. CSV needs this hint if you
- # plan to output non-ASCII compatible data.
- #
- def self.generate(*args)
- # add a default empty String, if none was given
- if args.first.is_a? String
- io = StringIO.new(args.shift)
- io.seek(0, IO::SEEK_END)
- args.unshift(io)
- else
- encoding = (args[-1] = args[-1].dup).delete(:encoding) if args.last.is_a?(Hash)
- str = ""
- str.encode!(encoding) if encoding
- args.unshift(str)
- end
- csv = new(*args) # wrap
- yield csv # yield for appending
- csv.string # return final String
- end
-
- #
- # This method is a shortcut for converting a single row (Array) into a CSV
- # String.
- #
- # The +options+ parameter can be anything CSV::new() understands. This method
- # understands an additional <tt>:encoding</tt> parameter to set the base
- # Encoding for the output. This method will try to guess your Encoding from
- # the first non-+nil+ field in +row+, if possible, but you may need to use
- # this parameter as a backup plan.
- #
- # The <tt>:row_sep</tt> +option+ defaults to <tt>$INPUT_RECORD_SEPARATOR</tt>
- # (<tt>$/</tt>) when calling this method.
- #
- def self.generate_line(row, options = Hash.new)
- options = {row_sep: $INPUT_RECORD_SEPARATOR}.merge(options)
- encoding = options.delete(:encoding)
- str = ""
- if encoding
- str.force_encoding(encoding)
- elsif field = row.find { |f| not f.nil? }
- str.force_encoding(String(field).encoding)
- end
- (new(str, options) << row).string
- end
-
- #
- # :call-seq:
- # open( filename, mode = "rb", options = Hash.new ) { |faster_csv| ... }
- # open( filename, options = Hash.new ) { |faster_csv| ... }
- # open( filename, mode = "rb", options = Hash.new )
- # open( filename, options = Hash.new )
- #
- # This method opens an IO object, and wraps that with CSV. This is intended
- # as the primary interface for writing a CSV file.
- #
- # You must pass a +filename+ and may optionally add a +mode+ for Ruby's
- # open(). You may also pass an optional Hash containing any +options+
- # CSV::new() understands as the final argument.
- #
- # This method works like Ruby's open() call, in that it will pass a CSV object
- # to a provided block and close it when the block terminates, or it will
- # return the CSV object when no block is provided. (*Note*: This is different
- # from the Ruby 1.8 CSV library which passed rows to the block. Use
- # CSV::foreach() for that behavior.)
- #
- # You must provide a +mode+ with an embedded Encoding designator unless your
- # data is in Encoding::default_external(). CSV will check the Encoding of the
- # underlying IO object (set by the +mode+ you pass) to determine how to parse
- # the data. You may provide a second Encoding to have the data transcoded as
- # it is read just as you can with a normal call to IO::open(). For example,
- # <tt>"rb:UTF-32BE:UTF-8"</tt> would read UTF-32BE data from the file but
- # transcode it to UTF-8 before CSV parses it.
- #
- # An opened CSV object will delegate to many IO methods for convenience. You
- # may call:
- #
- # * binmode()
- # * binmode?()
- # * close()
- # * close_read()
- # * close_write()
- # * closed?()
- # * eof()
- # * eof?()
- # * external_encoding()
- # * fcntl()
- # * fileno()
- # * flock()
- # * flush()
- # * fsync()
- # * internal_encoding()
- # * ioctl()
- # * isatty()
- # * path()
- # * pid()
- # * pos()
- # * pos=()
- # * reopen()
- # * seek()
- # * stat()
- # * sync()
- # * sync=()
- # * tell()
- # * to_i()
- # * to_io()
- # * truncate()
- # * tty?()
- #
- def self.open(*args)
- # find the +options+ Hash
- options = if args.last.is_a? Hash then args.pop else Hash.new end
- # wrap a File opened with the remaining +args+ with no newline
- # decorator
- file_opts = {universal_newline: false}.merge(options)
- begin
- f = File.open(*args, file_opts)
- rescue ArgumentError => e
- raise unless /needs binmode/ =~ e.message and args.size == 1
- args << "rb"
- file_opts = {encoding: Encoding.default_external}.merge(file_opts)
- retry
- end
- csv = new(f, options)
-
- # handle blocks like Ruby's open(), not like the CSV library
- if block_given?
- begin
- yield csv
- ensure
- csv.close
- end
- else
- csv
- end
- end
-
- #
- # :call-seq:
- # parse( str, options = Hash.new ) { |row| ... }
- # parse( str, options = Hash.new )
- #
- # This method can be used to easily parse CSV out of a String. You may either
- # provide a +block+ which will be called with each row of the String in turn,
- # or just use the returned Array of Arrays (when no +block+ is given).
- #
- # You pass your +str+ to read from, and an optional +options+ Hash containing
- # anything CSV::new() understands.
- #
- def self.parse(*args, &block)
- csv = new(*args)
- if block.nil? # slurp contents, if no block is given
- begin
- csv.read
- ensure
- csv.close
- end
- else # or pass each row to a provided block
- csv.each(&block)
- end
- end
-
- #
- # This method is a shortcut for converting a single line of a CSV String into
- # a into an Array. Note that if +line+ contains multiple rows, anything
- # beyond the first row is ignored.
- #
- # The +options+ parameter can be anything CSV::new() understands.
- #
- def self.parse_line(line, options = Hash.new)
- new(line, options).shift
- end
-
- #
- # Use to slurp a CSV file into an Array of Arrays. Pass the +path+ to the
- # file and any +options+ CSV::new() understands. This method also understands
- # an additional <tt>:encoding</tt> parameter that you can use to specify the
- # Encoding of the data in the file to be read. You must provide this unless
- # your data is in Encoding::default_external(). CSV will use this to determine
- # how to parse the data. You may provide a second Encoding to have the data
- # transcoded as it is read. For example,
- # <tt>encoding: "UTF-32BE:UTF-8"</tt> would read UTF-32BE data from the file
- # but transcode it to UTF-8 before CSV parses it.
- #
- def self.read(path, *options)
- open(path, *options) { |csv| csv.read }
- end
-
- # Alias for CSV::read().
- def self.readlines(*args)
- read(*args)
- end
-
- #
- # A shortcut for:
- #
- # CSV.read( path, { headers: true,
- # converters: :numeric,
- # header_converters: :symbol }.merge(options) )
- #
- def self.table(path, options = Hash.new)
- read( path, { headers: true,
- converters: :numeric,
- header_converters: :symbol }.merge(options) )
- end
-
- #
- # This constructor will wrap either a String or IO object passed in +data+ for
- # reading and/or writing. In addition to the CSV instance methods, several IO
- # methods are delegated. (See CSV::open() for a complete list.) If you pass
- # a String for +data+, you can later retrieve it (after writing to it, for
- # example) with CSV.string().
- #
- # Note that a wrapped String will be positioned at at the beginning (for
- # reading). If you want it at the end (for writing), use CSV::generate().
- # If you want any other positioning, pass a preset StringIO object instead.
- #
- # You may set any reading and/or writing preferences in the +options+ Hash.
- # Available options are:
- #
- # <b><tt>:col_sep</tt></b>:: The String placed between each field.
- # This String will be transcoded into
- # the data's Encoding before parsing.
- # <b><tt>:row_sep</tt></b>:: The String appended to the end of each
- # row. This can be set to the special
- # <tt>:auto</tt> setting, which requests
- # that CSV automatically discover this
- # from the data. Auto-discovery reads
- # ahead in the data looking for the next
- # <tt>"\r\n"</tt>, <tt>"\n"</tt>, or
- # <tt>"\r"</tt> sequence. A sequence
- # will be selected even if it occurs in
- # a quoted field, assuming that you
- # would have the same line endings
- # there. If none of those sequences is
- # found, +data+ is <tt>ARGF</tt>,
- # <tt>STDIN</tt>, <tt>STDOUT</tt>, or
- # <tt>STDERR</tt>, or the stream is only
- # available for output, the default
- # <tt>$INPUT_RECORD_SEPARATOR</tt>
- # (<tt>$/</tt>) is used. Obviously,
- # discovery takes a little time. Set
- # manually if speed is important. Also
- # note that IO objects should be opened
- # in binary mode on Windows if this
- # feature will be used as the
- # line-ending translation can cause
- # problems with resetting the document
- # position to where it was before the
- # read ahead. This String will be
- # transcoded into the data's Encoding
- # before parsing.
- # <b><tt>:quote_char</tt></b>:: The character used to quote fields.
- # This has to be a single character
- # String. This is useful for
- # application that incorrectly use
- # <tt>'</tt> as the quote character
- # instead of the correct <tt>"</tt>.
- # CSV will always consider a double
- # sequence this character to be an
- # escaped quote. This String will be
- # transcoded into the data's Encoding
- # before parsing.
- # <b><tt>:field_size_limit</tt></b>:: This is a maximum size CSV will read
- # ahead looking for the closing quote
- # for a field. (In truth, it reads to
- # the first line ending beyond this
- # size.) If a quote cannot be found
- # within the limit CSV will raise a
- # MalformedCSVError, assuming the data
- # is faulty. You can use this limit to
- # prevent what are effectively DoS
- # attacks on the parser. However, this
- # limit can cause a legitimate parse to
- # fail and thus is set to +nil+, or off,
- # by default.
- # <b><tt>:converters</tt></b>:: An Array of names from the Converters
- # Hash and/or lambdas that handle custom
- # conversion. A single converter
- # doesn't have to be in an Array. All
- # built-in converters try to transcode
- # fields to UTF-8 before converting.
- # The conversion will fail if the data
- # cannot be transcoded, leaving the
- # field unchanged.
- # <b><tt>:unconverted_fields</tt></b>:: If set to +true+, an
- # unconverted_fields() method will be
- # added to all returned rows (Array or
- # CSV::Row) that will return the fields
- # as they were before conversion. Note
- # that <tt>:headers</tt> supplied by
- # Array or String were not fields of the
- # document and thus will have an empty
- # Array attached.
- # <b><tt>:headers</tt></b>:: If set to <tt>:first_row</tt> or
- # +true+, the initial row of the CSV
- # file will be treated as a row of
- # headers. If set to an Array, the
- # contents will be used as the headers.
- # If set to a String, the String is run
- # through a call of CSV::parse_line()
- # with the same <tt>:col_sep</tt>,
- # <tt>:row_sep</tt>, and
- # <tt>:quote_char</tt> as this instance
- # to produce an Array of headers. This
- # setting causes CSV#shift() to return
- # rows as CSV::Row objects instead of
- # Arrays and CSV#read() to return
- # CSV::Table objects instead of an Array
- # of Arrays.
- # <b><tt>:return_headers</tt></b>:: When +false+, header rows are silently
- # swallowed. If set to +true+, header
- # rows are returned in a CSV::Row object
- # with identical headers and
- # fields (save that the fields do not go
- # through the converters).
- # <b><tt>:write_headers</tt></b>:: When +true+ and <tt>:headers</tt> is
- # set, a header row will be added to the
- # output.
- # <b><tt>:header_converters</tt></b>:: Identical in functionality to
- # <tt>:converters</tt> save that the
- # conversions are only made to header
- # rows. All built-in converters try to
- # transcode headers to UTF-8 before
- # converting. The conversion will fail
- # if the data cannot be transcoded,
- # leaving the header unchanged.
- # <b><tt>:skip_blanks</tt></b>:: When set to a +true+ value, CSV will
- # skip over any rows with no content.
- # <b><tt>:force_quotes</tt></b>:: When set to a +true+ value, CSV will
- # quote all CSV fields it creates.
- #
- # See CSV::DEFAULT_OPTIONS for the default settings.
- #
- # Options cannot be overridden in the instance methods for performance reasons,
- # so be sure to set what you want here.
- #
- def initialize(data, options = Hash.new)
- # build the options for this read/write
- options = DEFAULT_OPTIONS.merge(options)
-
- # create the IO object we will read from
- @io = data.is_a?(String) ? StringIO.new(data) : data
- # honor the IO encoding if we can, otherwise default to ASCII-8BIT
- @encoding = raw_encoding(nil) ||
- ( if encoding = options.delete(:internal_encoding)
- case encoding
- when Encoding; encoding
- else Encoding.find(encoding)
- end
- end ) ||
- ( case encoding = options.delete(:encoding)
- when Encoding; encoding
- when /\A[^:]+/; Encoding.find($&)
- end ) ||
- Encoding.default_internal || Encoding.default_external
- #
- # prepare for building safe regular expressions in the target encoding,
- # if we can transcode the needed characters
- #
- @re_esc = "\\".encode(@encoding) rescue ""
- @re_chars = /#{%"[-][\\.^$?*+{}()|# \r\n\t\f\v]".encode(@encoding)}/
- # @re_chars = /#{%"[-][\\.^$?*+{}()|# \r\n\t\f\v]".encode(@encoding, fallback: proc{""})}/
-
- init_separators(options)
- init_parsers(options)
- init_converters(options)
- init_headers(options)
-
- options.delete(:encoding)
- options.delete(:internal_encoding)
- options.delete(:external_encoding)
- unless options.empty?
- raise ArgumentError, "Unknown options: #{options.keys.join(', ')}."
- end
-
- # track our own lineno since IO gets confused about line-ends is CSV fields
- @lineno = 0
- end
-
- #
- # The encoded <tt>:col_sep</tt> used in parsing and writing. See CSV::new
- # for details.
- #
- attr_reader :col_sep
- #
- # The encoded <tt>:row_sep</tt> used in parsing and writing. See CSV::new
- # for details.
- #
- attr_reader :row_sep
- #
- # The encoded <tt>:quote_char</tt> used in parsing and writing. See CSV::new
- # for details.
- #
- attr_reader :quote_char
- # The limit for field size, if any. See CSV::new for details.
- attr_reader :field_size_limit
- #
- # Returns the current list of converters in effect. See CSV::new for details.
- # Built-in converters will be returned by name, while others will be returned
- # as is.
- #
- def converters
- @converters.map do |converter|
- name = Converters.rassoc(converter)
- name ? name.first : converter
- end
- end
- #
- # Returns +true+ if unconverted_fields() to parsed results. See CSV::new
- # for details.
- #
- def unconverted_fields?() @unconverted_fields end
- #
- # Returns +nil+ if headers will not be used, +true+ if they will but have not
- # yet been read, or the actual headers after they have been read. See
- # CSV::new for details.
- #
- def headers
- @headers || true if @use_headers
- end
- #
- # Returns +true+ if headers will be returned as a row of results.
- # See CSV::new for details.
- #
- def return_headers?() @return_headers end
- # Returns +true+ if headers are written in output. See CSV::new for details.
- def write_headers?() @write_headers end
- #
- # Returns the current list of converters in effect for headers. See CSV::new
- # for details. Built-in converters will be returned by name, while others
- # will be returned as is.
- #
- def header_converters
- @header_converters.map do |converter|
- name = HeaderConverters.rassoc(converter)
- name ? name.first : converter
- end
- end
- #
- # Returns +true+ blank lines are skipped by the parser. See CSV::new
- # for details.
- #
- def skip_blanks?() @skip_blanks end
- # Returns +true+ if all output fields are quoted. See CSV::new for details.
- def force_quotes?() @force_quotes end
-
- #
- # The Encoding CSV is parsing or writing in. This will be the Encoding you
- # receive parsed data in and/or the Encoding data will be written in.
- #
- attr_reader :encoding
-
- #
- # The line number of the last row read from this file. Fields with nested
- # line-end characters will not affect this count.
- #
- attr_reader :lineno
-
- ### IO and StringIO Delegation ###
-
- extend Forwardable
- def_delegators :@io, :binmode, :binmode?, :close, :close_read, :close_write,
- :closed?, :eof, :eof?, :external_encoding, :fcntl,
- :fileno, :flock, :flush, :fsync, :internal_encoding,
- :ioctl, :isatty, :path, :pid, :pos, :pos=, :reopen,
- :seek, :stat, :string, :sync, :sync=, :tell, :to_i,
- :to_io, :truncate, :tty?
-
- # Rewinds the underlying IO object and resets CSV's lineno() counter.
- def rewind
- @headers = nil
- @lineno = 0
-
- @io.rewind
- end
-
- ### End Delegation ###
-
- #
- # The primary write method for wrapped Strings and IOs, +row+ (an Array or
- # CSV::Row) is converted to CSV and appended to the data source. When a
- # CSV::Row is passed, only the row's fields() are appended to the output.
- #
- # The data source must be open for writing.
- #
- def <<(row)
- # make sure headers have been assigned
- if header_row? and [Array, String].include? @use_headers.class
- parse_headers # won't read data for Array or String
- self << @headers if @write_headers
- end
-
- # handle CSV::Row objects and Hashes
- row = case row
- when self.class::Row then row.fields
- when Hash then @headers.map { |header| row[header] }
- else row
- end
-
- @headers = row if header_row?
- @lineno += 1
-
- output = row.map(&@quote).join(@col_sep) + @row_sep # quote and separate
- if @io.is_a?(StringIO) and
- output.encoding != raw_encoding and
- (compatible_encoding = Encoding.compatible?(@io.string, output))
- @io = StringIO.new(@io.string.force_encoding(compatible_encoding))
- @io.seek(0, IO::SEEK_END)
- end
- @io << output
-
- self # for chaining
- end
- alias_method :add_row, :<<
- alias_method :puts, :<<
-
- #
- # :call-seq:
- # convert( name )
- # convert { |field| ... }
- # convert { |field, field_info| ... }
- #
- # You can use this method to install a CSV::Converters built-in, or provide a
- # block that handles a custom conversion.
- #
- # If you provide a block that takes one argument, it will be passed the field
- # and is expected to return the converted value or the field itself. If your
- # block takes two arguments, it will also be passed a CSV::FieldInfo Struct,
- # containing details about the field. Again, the block should return a
- # converted field or the field itself.
- #
- def convert(name = nil, &converter)
- add_converter(:converters, self.class::Converters, name, &converter)
- end
-
- #
- # :call-seq:
- # header_convert( name )
- # header_convert { |field| ... }
- # header_convert { |field, field_info| ... }
- #
- # Identical to CSV#convert(), but for header rows.
- #
- # Note that this method must be called before header rows are read to have any
- # effect.
- #
- def header_convert(name = nil, &converter)
- add_converter( :header_converters,
- self.class::HeaderConverters,
- name,
- &converter )
- end
-
- include Enumerable
-
- #
- # Yields each row of the data source in turn.
- #
- # Support for Enumerable.
- #
- # The data source must be open for reading.
- #
- def each
- if block_given?
- while row = shift
- yield row
- end
- else
- to_enum
- end
- end
-
- #
- # Slurps the remaining rows and returns an Array of Arrays.
- #
- # The data source must be open for reading.
- #
- def read
- rows = to_a
- if @use_headers
- Table.new(rows)
- else
- rows
- end
- end
- alias_method :readlines, :read
-
- # Returns +true+ if the next row read will be a header row.
- def header_row?
- @use_headers and @headers.nil?
- end
-
- #
- # The primary read method for wrapped Strings and IOs, a single row is pulled
- # from the data source, parsed and returned as an Array of fields (if header
- # rows are not used) or a CSV::Row (when header rows are used).
- #
- # The data source must be open for reading.
- #
- def shift
- #########################################################################
- ### This method is purposefully kept a bit long as simple conditional ###
- ### checks are faster than numerous (expensive) method calls. ###
- #########################################################################
-
- # handle headers not based on document content
- if header_row? and @return_headers and
- [Array, String].include? @use_headers.class
- if @unconverted_fields
- return add_unconverted_fields(parse_headers, Array.new)
- else
- return parse_headers
- end
- end
-
- #
- # it can take multiple calls to <tt>@io.gets()</tt> to get a full line,
- # because of \r and/or \n characters embedded in quoted fields
- #
- in_extended_col = false
- csv = Array.new
-
- loop do
- # add another read to the line
- unless parse = @io.gets(@row_sep)
- return nil
- end
-
- parse.sub!(@parsers[:line_end], "")
-
- if csv.empty?
- #
- # I believe a blank line should be an <tt>Array.new</tt>, not Ruby 1.8
- # CSV's <tt>[nil]</tt>
- #
- if parse.empty?
- @lineno += 1
- if @skip_blanks
- next
- elsif @unconverted_fields
- return add_unconverted_fields(Array.new, Array.new)
- elsif @use_headers
- return self.class::Row.new(Array.new, Array.new)
- else
- return Array.new
- end
- end
- end
-
- parts = parse.split(@col_sep, -1)
- if parts.empty?
- if in_extended_col
- csv[-1] << @col_sep # will be replaced with a @row_sep after the parts.each loop
- else
- csv << nil
- end
- end
-
- # This loop is the hot path of csv parsing. Some things may be non-dry
- # for a reason. Make sure to benchmark when refactoring.
- parts.each do |part|
- if in_extended_col
- # If we are continuing a previous column
- if part[-1] == @quote_char && part.count(@quote_char) % 2 != 0
- # extended column ends
- csv.last << part[0..-2]
- if csv.last =~ @parsers[:stray_quote]
- raise MalformedCSVError,
- "Missing or stray quote in line #{lineno + 1}"
- end
- csv.last.gsub!(@quote_char * 2, @quote_char)
- in_extended_col = false
- else
- csv.last << part
- csv.last << @col_sep
- end
- elsif part[0] == @quote_char
- # If we are staring a new quoted column
- if part[-1] != @quote_char || part.count(@quote_char) % 2 != 0
- # start an extended column
- csv << part[1..-1]
- csv.last << @col_sep
- in_extended_col = true
- else
- # regular quoted column
- csv << part[1..-2]
- if csv.last =~ @parsers[:stray_quote]
- raise MalformedCSVError,
- "Missing or stray quote in line #{lineno + 1}"
- end
- csv.last.gsub!(@quote_char * 2, @quote_char)
- end
- elsif part =~ @parsers[:quote_or_nl]
- # Unquoted field with bad characters.
- if part =~ @parsers[:nl_or_lf]
- raise MalformedCSVError, "Unquoted fields do not allow " +
- "\\r or \\n (line #{lineno + 1})."
- else
- raise MalformedCSVError, "Illegal quoting in line #{lineno + 1}."
- end
- else
- # Regular ole unquoted field.
- csv << (part.empty? ? nil : part)
- end
- end
-
- # Replace tacked on @col_sep with @row_sep if we are still in an extended
- # column.
- csv[-1][-1] = @row_sep if in_extended_col
-
- if in_extended_col
- # if we're at eof?(), a quoted field wasn't closed...
- if @io.eof?
- raise MalformedCSVError,
- "Unclosed quoted field on line #{lineno + 1}."
- elsif @field_size_limit and csv.last.size >= @field_size_limit
- raise MalformedCSVError, "Field size exceeded on line #{lineno + 1}."
- end
- # otherwise, we need to loop and pull some more data to complete the row
- else
- @lineno += 1
-
- # save fields unconverted fields, if needed...
- unconverted = csv.dup if @unconverted_fields
-
- # convert fields, if needed...
- csv = convert_fields(csv) unless @use_headers or @converters.empty?
- # parse out header rows and handle CSV::Row conversions...
- csv = parse_headers(csv) if @use_headers
-
- # inject unconverted fields and accessor, if requested...
- if @unconverted_fields and not csv.respond_to? :unconverted_fields
- add_unconverted_fields(csv, unconverted)
- end
-
- # return the results
- break csv
- end
- end
- end
- alias_method :gets, :shift
- alias_method :readline, :shift
-
- #
- # Returns a simplified description of the key CSV attributes in an
- # ASCII compatible String.
- #
- def inspect
- str = ["<#", self.class.to_s, " io_type:"]
- # show type of wrapped IO
- if @io == $stdout then str << "$stdout"
- elsif @io == $stdin then str << "$stdin"
- elsif @io == $stderr then str << "$stderr"
- else str << @io.class.to_s
- end
- # show IO.path(), if available
- if @io.respond_to?(:path) and (p = @io.path)
- str << " io_path:" << p.inspect
- end
- # show encoding
- str << " encoding:" << @encoding.name
- # show other attributes
- %w[ lineno col_sep row_sep
- quote_char skip_blanks ].each do |attr_name|
- if a = instance_variable_get("@#{attr_name}")
- str << " " << attr_name << ":" << a.inspect
- end
- end
- if @use_headers
- str << " headers:" << headers.inspect
- end
- str << ">"
- begin
- str.join('')
- rescue # any encoding error
- str.map do |s|
- e = Encoding::Converter.asciicompat_encoding(s.encoding)
- e ? s.encode(e) : s.force_encoding("ASCII-8BIT")
- end.join('')
- end
- end
-
- private
-
- #
- # Stores the indicated separators for later use.
- #
- # If auto-discovery was requested for <tt>@row_sep</tt>, this method will read
- # ahead in the <tt>@io</tt> and try to find one. +ARGF+, +STDIN+, +STDOUT+,
- # +STDERR+ and any stream open for output only with a default
- # <tt>@row_sep</tt> of <tt>$INPUT_RECORD_SEPARATOR</tt> (<tt>$/</tt>).
- #
- # This method also establishes the quoting rules used for CSV output.
- #
- def init_separators(options)
- # store the selected separators
- @col_sep = options.delete(:col_sep).to_s.encode(@encoding)
- @row_sep = options.delete(:row_sep) # encode after resolving :auto
- @quote_char = options.delete(:quote_char).to_s.encode(@encoding)
-
- if @quote_char.length != 1
- raise ArgumentError, ":quote_char has to be a single character String"
- end
-
- #
- # automatically discover row separator when requested
- # (not fully encoding safe)
- #
- if @row_sep == :auto
- if [ARGF, STDIN, STDOUT, STDERR].include?(@io) or
- (defined?(Zlib) and @io.class == Zlib::GzipWriter)
- @row_sep = $INPUT_RECORD_SEPARATOR
- else
- begin
- #
- # remember where we were (pos() will raise an axception if @io is pipe
- # or not opened for reading)
- #
- saved_pos = @io.pos
- while @row_sep == :auto
- #
- # if we run out of data, it's probably a single line
- # (ensure will set default value)
- #
- break unless sample = @io.gets(nil, 1024)
- # extend sample if we're unsure of the line ending
- if sample.end_with? encode_str("\r")
- sample << (@io.gets(nil, 1) || "")
- end
-
- # try to find a standard separator
- if sample =~ encode_re("\r\n?|\n")
- @row_sep = $&
- break
- end
- end
-
- # tricky seek() clone to work around GzipReader's lack of seek()
- @io.rewind
- # reset back to the remembered position
- while saved_pos > 1024 # avoid loading a lot of data into memory
- @io.read(1024)
- saved_pos -= 1024
- end
- @io.read(saved_pos) if saved_pos.nonzero?
- rescue IOError # not opened for reading
- # do nothing: ensure will set default
- rescue NoMethodError # Zlib::GzipWriter doesn't have some IO methods
- # do nothing: ensure will set default
- rescue SystemCallError # pipe
- # do nothing: ensure will set default
- ensure
- #
- # set default if we failed to detect
- # (stream not opened for reading, a pipe, or a single line of data)
- #
- @row_sep = $INPUT_RECORD_SEPARATOR if @row_sep == :auto
- end
- end
- end
- @row_sep = @row_sep.to_s.encode(@encoding)
-
- # establish quoting rules
- @force_quotes = options.delete(:force_quotes)
- do_quote = lambda do |field|
- field = String(field)
- encoded_quote = @quote_char.encode(field.encoding)
- encoded_quote +
- field.gsub(encoded_quote, encoded_quote * 2) +
- encoded_quote
- end
- quotable_chars = encode_str("\r\n", @col_sep, @quote_char)
- @quote = if @force_quotes
- do_quote
- else
- lambda do |field|
- if field.nil? # represent +nil+ fields as empty unquoted fields
- ""
- else
- field = String(field) # Stringify fields
- # represent empty fields as empty quoted fields
- if field.empty? or
- field.count(quotable_chars).nonzero?
- do_quote.call(field)
- else
- field # unquoted field
- end
- end
- end
- end
- end
-
- # Pre-compiles parsers and stores them by name for access during reads.
- def init_parsers(options)
- # store the parser behaviors
- @skip_blanks = options.delete(:skip_blanks)
- @field_size_limit = options.delete(:field_size_limit)
-
- # prebuild Regexps for faster parsing
- esc_row_sep = escape_re(@row_sep)
- esc_quote = escape_re(@quote_char)
- @parsers = {
- # for detecting parse errors
- quote_or_nl: encode_re("[", esc_quote, "\r\n]"),
- nl_or_lf: encode_re("[\r\n]"),
- stray_quote: encode_re( "[^", esc_quote, "]", esc_quote,
- "[^", esc_quote, "]" ),
- # safer than chomp!()
- line_end: encode_re(esc_row_sep, "\\z"),
- # illegal unquoted characters
- return_newline: encode_str("\r\n")
- }
- end
-
- #
- # Loads any converters requested during construction.
- #
- # If +field_name+ is set <tt>:converters</tt> (the default) field converters
- # are set. When +field_name+ is <tt>:header_converters</tt> header converters
- # are added instead.
- #
- # The <tt>:unconverted_fields</tt> option is also actived for
- # <tt>:converters</tt> calls, if requested.
- #
- def init_converters(options, field_name = :converters)
- if field_name == :converters
- @unconverted_fields = options.delete(:unconverted_fields)
- end
-
- instance_variable_set("@#{field_name}", Array.new)
-
- # find the correct method to add the converters
- convert = method(field_name.to_s.sub(/ers\Z/, ""))
-
- # load converters
- unless options[field_name].nil?
- # allow a single converter not wrapped in an Array
- unless options[field_name].is_a? Array
- options[field_name] = [options[field_name]]
- end
- # load each converter...
- options[field_name].each do |converter|
- if converter.is_a? Proc # custom code block
- convert.call(&converter)
- else # by name
- convert.call(converter)
- end
- end
- end
-
- options.delete(field_name)
- end
-
- # Stores header row settings and loads header converters, if needed.
- def init_headers(options)
- @use_headers = options.delete(:headers)
- @return_headers = options.delete(:return_headers)
- @write_headers = options.delete(:write_headers)
-
- # headers must be delayed until shift(), in case they need a row of content
- @headers = nil
-
- init_converters(options, :header_converters)
- end
-
- #
- # The actual work method for adding converters, used by both CSV.convert() and
- # CSV.header_convert().
- #
- # This method requires the +var_name+ of the instance variable to place the
- # converters in, the +const+ Hash to lookup named converters in, and the
- # normal parameters of the CSV.convert() and CSV.header_convert() methods.
- #
- def add_converter(var_name, const, name = nil, &converter)
- if name.nil? # custom converter
- instance_variable_get("@#{var_name}") << converter
- else # named converter
- combo = const[name]
- case combo
- when Array # combo converter
- combo.each do |converter_name|
- add_converter(var_name, const, converter_name)
- end
- else # individual named converter
- instance_variable_get("@#{var_name}") << combo
- end
- end
- end
-
- #
- # Processes +fields+ with <tt>@converters</tt>, or <tt>@header_converters</tt>
- # if +headers+ is passed as +true+, returning the converted field set. Any
- # converter that changes the field into something other than a String halts
- # the pipeline of conversion for that field. This is primarily an efficiency
- # shortcut.
- #
- def convert_fields(fields, headers = false)
- # see if we are converting headers or fields
- converters = headers ? @header_converters : @converters
-
- fields.map.with_index do |field, index|
- converters.each do |converter|
- field = if converter.arity == 1 # straight field converter
- converter[field]
- else # FieldInfo converter
- header = @use_headers && !headers ? @headers[index] : nil
- converter[field, FieldInfo.new(index, lineno, header)]
- end
- break unless field.is_a? String # short-curcuit pipeline for speed
- end
- field # final state of each field, converted or original
- end
- end
-
- #
- # This method is used to turn a finished +row+ into a CSV::Row. Header rows
- # are also dealt with here, either by returning a CSV::Row with identical
- # headers and fields (save that the fields do not go through the converters)
- # or by reading past them to return a field row. Headers are also saved in
- # <tt>@headers</tt> for use in future rows.
- #
- # When +nil+, +row+ is assumed to be a header row not based on an actual row
- # of the stream.
- #
- def parse_headers(row = nil)
- if @headers.nil? # header row
- @headers = case @use_headers # save headers
- # Array of headers
- when Array then @use_headers
- # CSV header String
- when String
- self.class.parse_line( @use_headers,
- col_sep: @col_sep,
- row_sep: @row_sep,
- quote_char: @quote_char )
- # first row is headers
- else row
- end
-
- # prepare converted and unconverted copies
- row = @headers if row.nil?
- @headers = convert_fields(@headers, true)
-
- if @return_headers # return headers
- return self.class::Row.new(@headers, row, true)
- elsif not [Array, String].include? @use_headers.class # skip to field row
- return shift
- end
- end
-
- self.class::Row.new(@headers, convert_fields(row)) # field row
- end
-
- #
- # This method injects an instance variable <tt>unconverted_fields</tt> into
- # +row+ and an accessor method for +row+ called unconverted_fields(). The
- # variable is set to the contents of +fields+.
- #
- def add_unconverted_fields(row, fields)
- class << row
- attr_reader :unconverted_fields
- end
- row.instance_eval { @unconverted_fields = fields }
- row
- end
-
- #
- # This method is an encoding safe version of Regexp::escape(). It will escape
- # any characters that would change the meaning of a regular expression in the
- # encoding of +str+. Regular expression characters that cannot be transcoded
- # to the target encoding will be skipped and no escaping will be performed if
- # a backslash cannot be transcoded.
- #
- def escape_re(str)
- str.gsub(@re_chars) {|c| @re_esc + c}
- end
-
- #
- # Builds a regular expression in <tt>@encoding</tt>. All +chunks+ will be
- # transcoded to that encoding.
- #
- def encode_re(*chunks)
- Regexp.new(encode_str(*chunks))
- end
-
- #
- # Builds a String in <tt>@encoding</tt>. All +chunks+ will be transcoded to
- # that encoding.
- #
- def encode_str(*chunks)
- chunks.map { |chunk| chunk.encode(@encoding.name) }.join('')
- end
-
- private
-
- #
- # Returns the encoding of the internal IO object or the +default+ if the
- # encoding cannot be determined.
- #
- def raw_encoding(default = Encoding::ASCII_8BIT)
- if @io.respond_to? :internal_encoding
- @io.internal_encoding || @io.external_encoding
- elsif @io.is_a? StringIO
- @io.string.encoding
- elsif @io.respond_to? :encoding
- @io.encoding
- else
- default
- end
- end
-end
-
-# Another name for CSV::instance().
-def CSV(*args, &block)
- CSV.instance(*args, &block)
-end
-
-class Array
- # Equivalent to <tt>CSV::generate_line(self, options)</tt>.
- def to_csv(options = Hash.new)
- CSV.generate_line(self, options)
- end
-end
-
-class String
- # Equivalent to <tt>CSV::parse_line(self, options)</tt>.
- def parse_csv(options = Hash.new)
- CSV.parse_line(self, options)
- end
-end
diff --git a/ruby_1_9_3/lib/debug.rb b/ruby_1_9_3/lib/debug.rb
deleted file mode 100644
index e99f69826a..0000000000
--- a/ruby_1_9_3/lib/debug.rb
+++ /dev/null
@@ -1,907 +0,0 @@
-# Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
-# Copyright (C) 2000 Information-technology Promotion Agency, Japan
-# Copyright (C) 2000-2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>
-
-require 'continuation'
-
-if $SAFE > 0
- STDERR.print "-r debug.rb is not available in safe mode\n"
- exit 1
-end
-
-require 'tracer'
-require 'pp'
-
-class Tracer
- def Tracer.trace_func(*vars)
- Single.trace_func(*vars)
- end
-end
-
-SCRIPT_LINES__ = {} unless defined? SCRIPT_LINES__
-
-class DEBUGGER__
- MUTEX = Mutex.new
-
- class Context
- DEBUG_LAST_CMD = []
-
- begin
- require 'readline'
- def readline(prompt, hist)
- Readline::readline(prompt, hist)
- end
- rescue LoadError
- def readline(prompt, hist)
- STDOUT.print prompt
- STDOUT.flush
- line = STDIN.gets
- exit unless line
- line.chomp!
- line
- end
- USE_READLINE = false
- end
-
- def initialize
- if Thread.current == Thread.main
- @stop_next = 1
- else
- @stop_next = 0
- end
- @last_file = nil
- @file = nil
- @line = nil
- @no_step = nil
- @frames = []
- @finish_pos = 0
- @trace = false
- @catch = "StandardError"
- @suspend_next = false
- end
-
- def stop_next(n=1)
- @stop_next = n
- end
-
- def set_suspend
- @suspend_next = true
- end
-
- def clear_suspend
- @suspend_next = false
- end
-
- def suspend_all
- DEBUGGER__.suspend
- end
-
- def resume_all
- DEBUGGER__.resume
- end
-
- def check_suspend
- while MUTEX.synchronize {
- if @suspend_next
- DEBUGGER__.waiting.push Thread.current
- @suspend_next = false
- true
- end
- }
- end
- end
-
- def trace?
- @trace
- end
-
- def set_trace(arg)
- @trace = arg
- end
-
- def stdout
- DEBUGGER__.stdout
- end
-
- def break_points
- DEBUGGER__.break_points
- end
-
- def display
- DEBUGGER__.display
- end
-
- def context(th)
- DEBUGGER__.context(th)
- end
-
- def set_trace_all(arg)
- DEBUGGER__.set_trace(arg)
- end
-
- def set_last_thread(th)
- DEBUGGER__.set_last_thread(th)
- end
-
- def debug_eval(str, binding)
- begin
- eval(str, binding)
- rescue StandardError, ScriptError => e
- at = eval("caller(1)", binding)
- stdout.printf "%s:%s\n", at.shift, e.to_s.sub(/\(eval\):1:(in `.*?':)?/, '')
- for i in at
- stdout.printf "\tfrom %s\n", i
- end
- throw :debug_error
- end
- end
-
- def debug_silent_eval(str, binding)
- begin
- eval(str, binding)
- rescue StandardError, ScriptError
- nil
- end
- end
-
- def var_list(ary, binding)
- ary.sort!
- for v in ary
- stdout.printf " %s => %s\n", v, eval(v.to_s, binding).inspect
- end
- end
-
- def debug_variable_info(input, binding)
- case input
- when /^\s*g(?:lobal)?\s*$/
- var_list(global_variables, binding)
-
- when /^\s*l(?:ocal)?\s*$/
- var_list(eval("local_variables", binding), binding)
-
- when /^\s*i(?:nstance)?\s+/
- obj = debug_eval($', binding)
- var_list(obj.instance_variables, obj.instance_eval{binding()})
-
- when /^\s*c(?:onst(?:ant)?)?\s+/
- obj = debug_eval($', binding)
- unless obj.kind_of? Module
- stdout.print "Should be Class/Module: ", $', "\n"
- else
- var_list(obj.constants, obj.module_eval{binding()})
- end
- end
- end
-
- def debug_method_info(input, binding)
- case input
- when /^i(:?nstance)?\s+/
- obj = debug_eval($', binding)
-
- len = 0
- for v in obj.methods.sort
- len += v.size + 1
- if len > 70
- len = v.size + 1
- stdout.print "\n"
- end
- stdout.print v, " "
- end
- stdout.print "\n"
-
- else
- obj = debug_eval(input, binding)
- unless obj.kind_of? Module
- stdout.print "Should be Class/Module: ", input, "\n"
- else
- len = 0
- for v in obj.instance_methods(false).sort
- len += v.size + 1
- if len > 70
- len = v.size + 1
- stdout.print "\n"
- end
- stdout.print v, " "
- end
- stdout.print "\n"
- end
- end
- end
-
- def thnum
- num = DEBUGGER__.instance_eval{@thread_list[Thread.current]}
- unless num
- DEBUGGER__.make_thread_list
- num = DEBUGGER__.instance_eval{@thread_list[Thread.current]}
- end
- num
- end
-
- def debug_command(file, line, id, binding)
- MUTEX.lock
- unless defined?($debugger_restart) and $debugger_restart
- callcc{|c| $debugger_restart = c}
- end
- set_last_thread(Thread.current)
- frame_pos = 0
- binding_file = file
- binding_line = line
- previous_line = nil
- if ENV['EMACS']
- stdout.printf "\032\032%s:%d:\n", binding_file, binding_line
- else
- stdout.printf "%s:%d:%s", binding_file, binding_line,
- line_at(binding_file, binding_line)
- end
- @frames[0] = [binding, file, line, id]
- display_expressions(binding)
- prompt = true
- while prompt and input = readline("(rdb:%d) "%thnum(), true)
- catch(:debug_error) do
- if input == ""
- next unless DEBUG_LAST_CMD[0]
- input = DEBUG_LAST_CMD[0]
- stdout.print input, "\n"
- else
- DEBUG_LAST_CMD[0] = input
- end
-
- case input
- when /^\s*tr(?:ace)?(?:\s+(on|off))?(?:\s+(all))?$/
- if defined?( $2 )
- if $1 == 'on'
- set_trace_all true
- else
- set_trace_all false
- end
- elsif defined?( $1 )
- if $1 == 'on'
- set_trace true
- else
- set_trace false
- end
- end
- if trace?
- stdout.print "Trace on.\n"
- else
- stdout.print "Trace off.\n"
- end
-
- when /^\s*b(?:reak)?\s+(?:(.+):)?([^.:]+)$/
- pos = $2
- if $1
- klass = debug_silent_eval($1, binding)
- file = $1
- end
- if pos =~ /^\d+$/
- pname = pos
- pos = pos.to_i
- else
- pname = pos = pos.intern.id2name
- end
- break_points.push [true, 0, klass || file, pos]
- stdout.printf "Set breakpoint %d at %s:%s\n", break_points.size, klass || file, pname
-
- when /^\s*b(?:reak)?\s+(.+)[#.]([^.:]+)$/
- pos = $2.intern.id2name
- klass = debug_eval($1, binding)
- break_points.push [true, 0, klass, pos]
- stdout.printf "Set breakpoint %d at %s.%s\n", break_points.size, klass, pos
-
- when /^\s*wat(?:ch)?\s+(.+)$/
- exp = $1
- break_points.push [true, 1, exp]
- stdout.printf "Set watchpoint %d:%s\n", break_points.size, exp
-
- when /^\s*b(?:reak)?$/
- if break_points.find{|b| b[1] == 0}
- n = 1
- stdout.print "Breakpoints:\n"
- break_points.each do |b|
- if b[0] and b[1] == 0
- stdout.printf " %d %s:%s\n", n, b[2], b[3]
- end
- n += 1
- end
- end
- if break_points.find{|b| b[1] == 1}
- n = 1
- stdout.print "\n"
- stdout.print "Watchpoints:\n"
- for b in break_points
- if b[0] and b[1] == 1
- stdout.printf " %d %s\n", n, b[2]
- end
- n += 1
- end
- end
- if break_points.size == 0
- stdout.print "No breakpoints\n"
- else
- stdout.print "\n"
- end
-
- when /^\s*del(?:ete)?(?:\s+(\d+))?$/
- pos = $1
- unless pos
- input = readline("Clear all breakpoints? (y/n) ", false)
- if input == "y"
- for b in break_points
- b[0] = false
- end
- end
- else
- pos = pos.to_i
- if break_points[pos-1]
- break_points[pos-1][0] = false
- else
- stdout.printf "Breakpoint %d is not defined\n", pos
- end
- end
-
- when /^\s*disp(?:lay)?\s+(.+)$/
- exp = $1
- display.push [true, exp]
- stdout.printf "%d: ", display.size
- display_expression(exp, binding)
-
- when /^\s*disp(?:lay)?$/
- display_expressions(binding)
-
- when /^\s*undisp(?:lay)?(?:\s+(\d+))?$/
- pos = $1
- unless pos
- input = readline("Clear all expressions? (y/n) ", false)
- if input == "y"
- for d in display
- d[0] = false
- end
- end
- else
- pos = pos.to_i
- if display[pos-1]
- display[pos-1][0] = false
- else
- stdout.printf "Display expression %d is not defined\n", pos
- end
- end
-
- when /^\s*c(?:ont)?$/
- prompt = false
-
- when /^\s*s(?:tep)?(?:\s+(\d+))?$/
- if $1
- lev = $1.to_i
- else
- lev = 1
- end
- @stop_next = lev
- prompt = false
-
- when /^\s*n(?:ext)?(?:\s+(\d+))?$/
- if $1
- lev = $1.to_i
- else
- lev = 1
- end
- @stop_next = lev
- @no_step = @frames.size - frame_pos
- prompt = false
-
- when /^\s*w(?:here)?$/, /^\s*f(?:rame)?$/
- display_frames(frame_pos)
-
- when /^\s*l(?:ist)?(?:\s+(.+))?$/
- if not $1
- b = previous_line ? previous_line + 10 : binding_line - 5
- e = b + 9
- elsif $1 == '-'
- b = previous_line ? previous_line - 10 : binding_line - 5
- e = b + 9
- else
- b, e = $1.split(/[-,]/)
- if e
- b = b.to_i
- e = e.to_i
- else
- b = b.to_i - 5
- e = b + 9
- end
- end
- previous_line = b
- display_list(b, e, binding_file, binding_line)
-
- when /^\s*up(?:\s+(\d+))?$/
- previous_line = nil
- if $1
- lev = $1.to_i
- else
- lev = 1
- end
- frame_pos += lev
- if frame_pos >= @frames.size
- frame_pos = @frames.size - 1
- stdout.print "At toplevel\n"
- end
- binding, binding_file, binding_line = @frames[frame_pos]
- stdout.print format_frame(frame_pos)
-
- when /^\s*down(?:\s+(\d+))?$/
- previous_line = nil
- if $1
- lev = $1.to_i
- else
- lev = 1
- end
- frame_pos -= lev
- if frame_pos < 0
- frame_pos = 0
- stdout.print "At stack bottom\n"
- end
- binding, binding_file, binding_line = @frames[frame_pos]
- stdout.print format_frame(frame_pos)
-
- when /^\s*fin(?:ish)?$/
- if frame_pos == @frames.size
- stdout.print "\"finish\" not meaningful in the outermost frame.\n"
- else
- @finish_pos = @frames.size - frame_pos
- frame_pos = 0
- prompt = false
- end
-
- when /^\s*cat(?:ch)?(?:\s+(.+))?$/
- if $1
- excn = $1
- if excn == 'off'
- @catch = nil
- stdout.print "Clear catchpoint.\n"
- else
- @catch = excn
- stdout.printf "Set catchpoint %s.\n", @catch
- end
- else
- if @catch
- stdout.printf "Catchpoint %s.\n", @catch
- else
- stdout.print "No catchpoint.\n"
- end
- end
-
- when /^\s*q(?:uit)?$/
- input = readline("Really quit? (y/n) ", false)
- if input == "y"
- exit! # exit -> exit!: No graceful way to stop threads...
- end
-
- when /^\s*v(?:ar)?\s+/
- debug_variable_info($', binding)
-
- when /^\s*m(?:ethod)?\s+/
- debug_method_info($', binding)
-
- when /^\s*th(?:read)?\s+/
- if DEBUGGER__.debug_thread_info($', binding) == :cont
- prompt = false
- end
-
- when /^\s*pp\s+/
- PP.pp(debug_eval($', binding), stdout)
-
- when /^\s*p\s+/
- stdout.printf "%s\n", debug_eval($', binding).inspect
-
- when /^\s*r(?:estart)?$/
- $debugger_restart.call
-
- when /^\s*h(?:elp)?$/
- debug_print_help()
-
- else
- v = debug_eval(input, binding)
- stdout.printf "%s\n", v.inspect
- end
- end
- end
- MUTEX.unlock
- resume_all
- end
-
- def debug_print_help
- stdout.print <<EOHELP
-Debugger help v.-0.002b
-Commands
- b[reak] [file:|class:]<line|method>
- b[reak] [class.]<line|method>
- set breakpoint to some position
- wat[ch] <expression> set watchpoint to some expression
- cat[ch] (<exception>|off) set catchpoint to an exception
- b[reak] list breakpoints
- cat[ch] show catchpoint
- del[ete][ nnn] delete some or all breakpoints
- disp[lay] <expression> add expression into display expression list
- undisp[lay][ nnn] delete one particular or all display expressions
- c[ont] run until program ends or hit breakpoint
- s[tep][ nnn] step (into methods) one line or till line nnn
- n[ext][ nnn] go over one line or till line nnn
- w[here] display frames
- f[rame] alias for where
- l[ist][ (-|nn-mm)] list program, - lists backwards
- nn-mm lists given lines
- up[ nn] move to higher frame
- down[ nn] move to lower frame
- fin[ish] return to outer frame
- tr[ace] (on|off) set trace mode of current thread
- tr[ace] (on|off) all set trace mode of all threads
- q[uit] exit from debugger
- v[ar] g[lobal] show global variables
- v[ar] l[ocal] show local variables
- v[ar] i[nstance] <object> show instance variables of object
- v[ar] c[onst] <object> show constants of object
- m[ethod] i[nstance] <obj> show methods of object
- m[ethod] <class|module> show instance methods of class or module
- th[read] l[ist] list all threads
- th[read] c[ur[rent]] show current thread
- th[read] [sw[itch]] <nnn> switch thread context to nnn
- th[read] stop <nnn> stop thread nnn
- th[read] resume <nnn> resume thread nnn
- p expression evaluate expression and print its value
- h[elp] print this help
- <everything else> evaluate
-EOHELP
- end
-
- def display_expressions(binding)
- n = 1
- for d in display
- if d[0]
- stdout.printf "%d: ", n
- display_expression(d[1], binding)
- end
- n += 1
- end
- end
-
- def display_expression(exp, binding)
- stdout.printf "%s = %s\n", exp, debug_silent_eval(exp, binding).to_s
- end
-
- def frame_set_pos(file, line)
- if @frames[0]
- @frames[0][1] = file
- @frames[0][2] = line
- end
- end
-
- def display_frames(pos)
- 0.upto(@frames.size - 1) do |n|
- if n == pos
- stdout.print "--> "
- else
- stdout.print " "
- end
- stdout.print format_frame(n)
- end
- end
-
- def format_frame(pos)
- _, file, line, id = @frames[pos]
- sprintf "#%d %s:%s%s\n", pos + 1, file, line,
- (id ? ":in `#{id.id2name}'" : "")
- end
-
- def display_list(b, e, file, line)
- stdout.printf "[%d, %d] in %s\n", b, e, file
- if lines = SCRIPT_LINES__[file] and lines != true
- b.upto(e) do |n|
- if n > 0 && lines[n-1]
- if n == line
- stdout.printf "=> %d %s\n", n, lines[n-1].chomp
- else
- stdout.printf " %d %s\n", n, lines[n-1].chomp
- end
- end
- end
- else
- stdout.printf "No sourcefile available for %s\n", file
- end
- end
-
- def line_at(file, line)
- lines = SCRIPT_LINES__[file]
- if lines
- return "\n" if lines == true
- line = lines[line-1]
- return "\n" unless line
- return line
- end
- return "\n"
- end
-
- def debug_funcname(id)
- if id.nil?
- "toplevel"
- else
- id.id2name
- end
- end
-
- def check_break_points(file, klass, pos, binding, id)
- return false if break_points.empty?
- n = 1
- for b in break_points
- if b[0] # valid
- if b[1] == 0 # breakpoint
- if (b[2] == file and b[3] == pos) or
- (klass and b[2] == klass and b[3] == pos)
- stdout.printf "Breakpoint %d, %s at %s:%s\n", n, debug_funcname(id), file, pos
- return true
- end
- elsif b[1] == 1 # watchpoint
- if debug_silent_eval(b[2], binding)
- stdout.printf "Watchpoint %d, %s at %s:%s\n", n, debug_funcname(id), file, pos
- return true
- end
- end
- end
- n += 1
- end
- return false
- end
-
- def excn_handle(file, line, id, binding)
- if $!.class <= SystemExit
- set_trace_func nil
- exit
- end
-
- if @catch and ($!.class.ancestors.find { |e| e.to_s == @catch })
- stdout.printf "%s:%d: `%s' (%s)\n", file, line, $!, $!.class
- fs = @frames.size
- tb = caller(0)[-fs..-1]
- if tb
- for i in tb
- stdout.printf "\tfrom %s\n", i
- end
- end
- suspend_all
- debug_command(file, line, id, binding)
- end
- end
-
- def trace_func(event, file, line, id, binding, klass)
- Tracer.trace_func(event, file, line, id, binding, klass) if trace?
- context(Thread.current).check_suspend
- @file = file
- @line = line
- case event
- when 'line'
- frame_set_pos(file, line)
- if !@no_step or @frames.size == @no_step
- @stop_next -= 1
- @stop_next = -1 if @stop_next < 0
- elsif @frames.size < @no_step
- @stop_next = 0 # break here before leaving...
- else
- # nothing to do. skipped.
- end
- if @stop_next == 0 or check_break_points(file, nil, line, binding, id)
- @no_step = nil
- suspend_all
- debug_command(file, line, id, binding)
- end
-
- when 'call'
- @frames.unshift [binding, file, line, id]
- if check_break_points(file, klass, id.id2name, binding, id)
- suspend_all
- debug_command(file, line, id, binding)
- end
-
- when 'c-call'
- frame_set_pos(file, line)
-
- when 'class'
- @frames.unshift [binding, file, line, id]
-
- when 'return', 'end'
- if @frames.size == @finish_pos
- @stop_next = 1
- @finish_pos = 0
- end
- @frames.shift
-
- when 'raise'
- excn_handle(file, line, id, binding)
-
- end
- @last_file = file
- end
- end
-
- trap("INT") { DEBUGGER__.interrupt }
- @last_thread = Thread::main
- @max_thread = 1
- @thread_list = {Thread::main => 1}
- @break_points = []
- @display = []
- @waiting = []
- @stdout = STDOUT
-
- class << DEBUGGER__
- def stdout
- @stdout
- end
-
- def stdout=(s)
- @stdout = s
- end
-
- def display
- @display
- end
-
- def break_points
- @break_points
- end
-
- def waiting
- @waiting
- end
-
- def set_trace( arg )
- MUTEX.synchronize do
- make_thread_list
- for th, in @thread_list
- context(th).set_trace arg
- end
- end
- arg
- end
-
- def set_last_thread(th)
- @last_thread = th
- end
-
- def suspend
- MUTEX.synchronize do
- make_thread_list
- for th, in @thread_list
- next if th == Thread.current
- context(th).set_suspend
- end
- end
- # Schedule other threads to suspend as soon as possible.
- Thread.pass
- end
-
- def resume
- MUTEX.synchronize do
- make_thread_list
- @thread_list.each do |th,|
- next if th == Thread.current
- context(th).clear_suspend
- end
- waiting.each do |th|
- th.run
- end
- waiting.clear
- end
- # Schedule other threads to restart as soon as possible.
- Thread.pass
- end
-
- def context(thread=Thread.current)
- c = thread[:__debugger_data__]
- unless c
- thread[:__debugger_data__] = c = Context.new
- end
- c
- end
-
- def interrupt
- context(@last_thread).stop_next
- end
-
- def get_thread(num)
- th = @thread_list.key(num)
- unless th
- @stdout.print "No thread ##{num}\n"
- throw :debug_error
- end
- th
- end
-
- def thread_list(num)
- th = get_thread(num)
- if th == Thread.current
- @stdout.print "+"
- else
- @stdout.print " "
- end
- @stdout.printf "%d ", num
- @stdout.print th.inspect, "\t"
- file = context(th).instance_eval{@file}
- if file
- @stdout.print file,":",context(th).instance_eval{@line}
- end
- @stdout.print "\n"
- end
-
- def thread_list_all
- for th in @thread_list.values.sort
- thread_list(th)
- end
- end
-
- def make_thread_list
- hash = {}
- for th in Thread::list
- if @thread_list.key? th
- hash[th] = @thread_list[th]
- else
- @max_thread += 1
- hash[th] = @max_thread
- end
- end
- @thread_list = hash
- end
-
- def debug_thread_info(input, binding)
- case input
- when /^l(?:ist)?/
- make_thread_list
- thread_list_all
-
- when /^c(?:ur(?:rent)?)?$/
- make_thread_list
- thread_list(@thread_list[Thread.current])
-
- when /^(?:sw(?:itch)?\s+)?(\d+)/
- make_thread_list
- th = get_thread($1.to_i)
- if th == Thread.current
- @stdout.print "It's the current thread.\n"
- else
- thread_list(@thread_list[th])
- context(th).stop_next
- th.run
- return :cont
- end
-
- when /^stop\s+(\d+)/
- make_thread_list
- th = get_thread($1.to_i)
- if th == Thread.current
- @stdout.print "It's the current thread.\n"
- elsif th.stop?
- @stdout.print "Already stopped.\n"
- else
- thread_list(@thread_list[th])
- context(th).suspend
- end
-
- when /^resume\s+(\d+)/
- make_thread_list
- th = get_thread($1.to_i)
- if th == Thread.current
- @stdout.print "It's the current thread.\n"
- elsif !th.stop?
- @stdout.print "Already running."
- else
- thread_list(@thread_list[th])
- th.run
- end
- end
- end
- end
-
- stdout.printf "Debug.rb\n"
- stdout.printf "Emacs support available.\n\n"
- RubyVM::InstructionSequence.compile_option = {
- trace_instruction: true
- }
- set_trace_func proc { |event, file, line, id, binding, klass, *rest|
- DEBUGGER__.context.trace_func event, file, line, id, binding, klass
- }
-end
diff --git a/ruby_1_9_3/lib/delegate.rb b/ruby_1_9_3/lib/delegate.rb
deleted file mode 100644
index 2086a721f9..0000000000
--- a/ruby_1_9_3/lib/delegate.rb
+++ /dev/null
@@ -1,392 +0,0 @@
-# = delegate -- Support for the Delegation Pattern
-#
-# Documentation by James Edward Gray II and Gavin Sinclair
-
-##
-# This library provides three different ways to delegate method calls to an
-# object. The easiest to use is SimpleDelegator. Pass an object to the
-# constructor and all methods supported by the object will be delegated. This
-# object can be changed later.
-#
-# Going a step further, the top level DelegateClass method allows you to easily
-# setup delegation through class inheritance. This is considerably more
-# flexible and thus probably the most common use for this library.
-#
-# Finally, if you need full control over the delegation scheme, you can inherit
-# from the abstract class Delegator and customize as needed. (If you find
-# yourself needing this control, have a look at Forwardable which is also in
-# the standard library. It may suit your needs better.)
-#
-# SimpleDelegator's implementation serves as a nice example if the use of
-# Delegator:
-#
-# class SimpleDelegator < Delegator
-# def initialize(obj)
-# super # pass obj to Delegator constructor, required
-# @delegate_sd_obj = obj # store obj for future use
-# end
-#
-# def __getobj__
-# @delegate_sd_obj # return object we are delegating to, required
-# end
-#
-# def __setobj__(obj)
-# @delegate_sd_obj = obj # change delegation object,
-# # a feature we're providing
-# end
-# end
-#
-# == Notes
-#
-# Be advised, RDoc will not detect delegated methods.
-#
-class Delegator < BasicObject
- kernel = ::Kernel.dup
- kernel.class_eval do
- [:to_s,:inspect,:=~,:!~,:===,:<=>,:eql?,:hash].each do |m|
- undef_method m
- end
- end
- include kernel
-
- # :stopdoc:
- def self.const_missing(n)
- ::Object.const_get(n)
- end
- # :startdoc:
-
- #
- # Pass in the _obj_ to delegate method calls to. All methods supported by
- # _obj_ will be delegated to.
- #
- def initialize(obj)
- __setobj__(obj)
- end
-
- #
- # Handles the magic of delegation through \_\_getobj\_\_.
- #
- def method_missing(m, *args, &block)
- target = self.__getobj__
- begin
- target.respond_to?(m) ? target.__send__(m, *args, &block) : super(m, *args, &block)
- ensure
- $@.delete_if {|t| %r"\A#{Regexp.quote(__FILE__)}:#{__LINE__-2}:"o =~ t} if $@
- end
- end
-
- #
- # Checks for a method provided by this the delegate object by forwarding the
- # call through \_\_getobj\_\_.
- #
- def respond_to_missing?(m, include_private)
- r = self.__getobj__.respond_to?(m, include_private)
- if r && include_private && !self.__getobj__.respond_to?(m, false)
- warn "#{caller(3)[0]}: delegator does not forward private method \##{m}"
- return false
- end
- r
- end
-
- #
- # Returns the methods available to this delegate object as the union
- # of this object's and \_\_getobj\_\_ methods.
- #
- def methods
- __getobj__.methods | super
- end
-
- #
- # Returns the methods available to this delegate object as the union
- # of this object's and \_\_getobj\_\_ public methods.
- #
- def public_methods(all=true)
- __getobj__.public_methods(all) | super
- end
-
- #
- # Returns the methods available to this delegate object as the union
- # of this object's and \_\_getobj\_\_ protected methods.
- #
- def protected_methods(all=true)
- __getobj__.protected_methods(all) | super
- end
-
- # Note: no need to specialize private_methods, since they are not forwarded
-
- #
- # Returns true if two objects are considered of equal value.
- #
- def ==(obj)
- return true if obj.equal?(self)
- self.__getobj__ == obj
- end
-
- #
- # Returns true if two objects are not considered of equal value.
- #
- def !=(obj)
- return false if obj.equal?(self)
- __getobj__ != obj
- end
-
- def !
- !__getobj__
- end
-
- #
- # This method must be overridden by subclasses and should return the object
- # method calls are being delegated to.
- #
- def __getobj__
- raise NotImplementedError, "need to define `__getobj__'"
- end
-
- #
- # This method must be overridden by subclasses and change the object delegate
- # to _obj_.
- #
- def __setobj__(obj)
- raise NotImplementedError, "need to define `__setobj__'"
- end
-
- #
- # Serialization support for the object returned by \_\_getobj\_\_.
- #
- def marshal_dump
- ivars = instance_variables.reject {|var| /\A@delegate_/ =~ var}
- [
- :__v2__,
- ivars, ivars.map{|var| instance_variable_get(var)},
- __getobj__
- ]
- end
-
- #
- # Reinitializes delegation from a serialized object.
- #
- def marshal_load(data)
- version, vars, values, obj = data
- if version == :__v2__
- vars.each_with_index{|var, i| instance_variable_set(var, values[i])}
- __setobj__(obj)
- else
- __setobj__(data)
- end
- end
-
- def initialize_clone(obj) # :nodoc:
- self.__setobj__(obj.__getobj__.clone)
- end
- def initialize_dup(obj) # :nodoc:
- self.__setobj__(obj.__getobj__.dup)
- end
- private :initialize_clone, :initialize_dup
-
- ##
- # :method: trust
- # Trust both the object returned by \_\_getobj\_\_ and self.
- #
-
- ##
- # :method: untrust
- # Untrust both the object returned by \_\_getobj\_\_ and self.
- #
-
- ##
- # :method: taint
- # Taint both the object returned by \_\_getobj\_\_ and self.
- #
-
- ##
- # :method: untaint
- # Untaint both the object returned by \_\_getobj\_\_ and self.
- #
-
- ##
- # :method: freeze
- # Freeze both the object returned by \_\_getobj\_\_ and self.
- #
-
- [:trust, :untrust, :taint, :untaint, :freeze].each do |method|
- define_method method do
- __getobj__.send(method)
- super()
- end
- end
-
- @delegator_api = self.public_instance_methods
- def self.public_api # :nodoc:
- @delegator_api
- end
-end
-
-##
-# A concrete implementation of Delegator, this class provides the means to
-# delegate all supported method calls to the object passed into the constructor
-# and even to change the object being delegated to at a later time with
-# #__setobj__.
-#
-# Here's a simple example that takes advantage of the fact that
-# SimpleDelegator's delegation object can be changed at any time.
-#
-# class Stats
-# def initialize
-# @source = SimpleDelegator.new([])
-# end
-#
-# def stats(records)
-# @source.__setobj__(records)
-#
-# "Elements: #{@source.size}\n" +
-# " Non-Nil: #{@source.compact.size}\n" +
-# " Unique: #{@source.uniq.size}\n"
-# end
-# end
-#
-# s = Stats.new
-# puts s.stats(%w{James Edward Gray II})
-# puts
-# puts s.stats([1, 2, 3, nil, 4, 5, 1, 2])
-#
-# Prints:
-#
-# Elements: 4
-# Non-Nil: 4
-# Unique: 4
-#
-# Elements: 8
-# Non-Nil: 7
-# Unique: 6
-#
-class SimpleDelegator<Delegator
- # Returns the current object method calls are being delegated to.
- def __getobj__
- @delegate_sd_obj
- end
-
- #
- # Changes the delegate object to _obj_.
- #
- # It's important to note that this does *not* cause SimpleDelegator's methods
- # to change. Because of this, you probably only want to change delegation
- # to objects of the same type as the original delegate.
- #
- # Here's an example of changing the delegation object.
- #
- # names = SimpleDelegator.new(%w{James Edward Gray II})
- # puts names[1] # => Edward
- # names.__setobj__(%w{Gavin Sinclair})
- # puts names[1] # => Sinclair
- #
- def __setobj__(obj)
- raise ArgumentError, "cannot delegate to self" if self.equal?(obj)
- @delegate_sd_obj = obj
- end
-end
-
-# :stopdoc:
-def Delegator.delegating_block(mid)
- lambda do |*args, &block|
- target = self.__getobj__
- begin
- target.__send__(mid, *args, &block)
- ensure
- $@.delete_if {|t| /\A#{Regexp.quote(__FILE__)}:#{__LINE__-2}:/o =~ t} if $@
- end
- end
-end
-# :startdoc:
-
-#
-# The primary interface to this library. Use to setup delegation when defining
-# your class.
-#
-# class MyClass < DelegateClass(ClassToDelegateTo) # Step 1
-# def initialize
-# super(obj_of_ClassToDelegateTo) # Step 2
-# end
-# end
-#
-# Here's a sample of use from Tempfile which is really a File object with a
-# few special rules about storage location and when the File should be
-# deleted. That makes for an almost textbook perfect example of how to use
-# delegation.
-#
-# class Tempfile < DelegateClass(File)
-# # constant and class member data initialization...
-#
-# def initialize(basename, tmpdir=Dir::tmpdir)
-# # build up file path/name in var tmpname...
-#
-# @tmpfile = File.open(tmpname, File::RDWR|File::CREAT|File::EXCL, 0600)
-#
-# # ...
-#
-# super(@tmpfile)
-#
-# # below this point, all methods of File are supported...
-# end
-#
-# # ...
-# end
-#
-def DelegateClass(superclass)
- klass = Class.new(Delegator)
- methods = superclass.instance_methods
- methods -= ::Delegator.public_api
- methods -= [:to_s,:inspect,:=~,:!~,:===]
- klass.module_eval do
- def __getobj__ # :nodoc:
- @delegate_dc_obj
- end
- def __setobj__(obj) # :nodoc:
- raise ArgumentError, "cannot delegate to self" if self.equal?(obj)
- @delegate_dc_obj = obj
- end
- methods.each do |method|
- define_method(method, Delegator.delegating_block(method))
- end
- end
- klass.define_singleton_method :public_instance_methods do |all=true|
- super(all) - superclass.protected_instance_methods
- end
- klass.define_singleton_method :protected_instance_methods do |all=true|
- super(all) | superclass.protected_instance_methods
- end
- return klass
-end
-
-# :enddoc:
-
-if __FILE__ == $0
- class ExtArray<DelegateClass(Array)
- def initialize()
- super([])
- end
- end
-
- ary = ExtArray.new
- p ary.class
- ary.push 25
- p ary
- ary.push 42
- ary.each {|x| p x}
-
- foo = Object.new
- def foo.test
- 25
- end
- def foo.iter
- yield self
- end
- def foo.error
- raise 'this is OK'
- end
- foo2 = SimpleDelegator.new(foo)
- p foo2
- foo2.instance_eval{print "foo\n"}
- p foo.test == foo2.test # => true
- p foo2.iter{[55,true]} # => true
- foo2.error # raise error!
-end
diff --git a/ruby_1_9_3/lib/drb.rb b/ruby_1_9_3/lib/drb.rb
deleted file mode 100644
index 93cc811e14..0000000000
--- a/ruby_1_9_3/lib/drb.rb
+++ /dev/null
@@ -1,2 +0,0 @@
-require 'drb/drb'
-
diff --git a/ruby_1_9_3/lib/drb/acl.rb b/ruby_1_9_3/lib/drb/acl.rb
deleted file mode 100644
index 29a378199f..0000000000
--- a/ruby_1_9_3/lib/drb/acl.rb
+++ /dev/null
@@ -1,250 +0,0 @@
-# Copyright (c) 2000,2002,2003 Masatoshi SEKI
-#
-# acl.rb is copyrighted free software by Masatoshi SEKI.
-# You can redistribute it and/or modify it under the same terms as Ruby.
-
-require 'ipaddr'
-
-##
-# Simple Access Control Lists.
-#
-# Access control lists are composed of "allow" and "deny" halves to control
-# access. Use "all" or "*" to match any address. To match a specific address
-# use any address or address mask that IPAddr can understand.
-#
-# Example:
-#
-# list = %w[
-# deny all
-# allow 192.168.1.1
-# allow ::ffff:192.168.1.2
-# allow 192.168.1.3
-# ]
-#
-# # From Socket#peeraddr, see also ACL#allow_socket?
-# addr = ["AF_INET", 10, "lc630", "192.168.1.3"]
-#
-# acl = ACL.new
-# p acl.allow_addr?(addr) # => true
-#
-# acl = ACL.new(list, ACL::DENY_ALLOW)
-# p acl.allow_addr?(addr) # => true
-
-class ACL
-
- ##
- # The current version of ACL
-
- VERSION=["2.0.0"]
-
- ##
- # An entry in an ACL
-
- class ACLEntry
-
- ##
- # Creates a new entry using +str+.
- #
- # +str+ may be "*" or "all" to match any address, an IP address string
- # to match a specific address, an IP address mask per IPAddr, or one
- # containing "*" to match part of an IPv4 address.
-
- def initialize(str)
- if str == '*' or str == 'all'
- @pat = [:all]
- elsif str.include?('*')
- @pat = [:name, dot_pat(str)]
- else
- begin
- @pat = [:ip, IPAddr.new(str)]
- rescue ArgumentError
- @pat = [:name, dot_pat(str)]
- end
- end
- end
-
- private
-
- ##
- # Creates a regular expression to match IPv4 addresses
-
- def dot_pat_str(str)
- list = str.split('.').collect { |s|
- (s == '*') ? '.+' : s
- }
- list.join("\\.")
- end
-
- private
-
- ##
- # Creates a Regexp to match an address.
-
- def dot_pat(str)
- exp = "^" + dot_pat_str(str) + "$"
- Regexp.new(exp)
- end
-
- public
-
- ##
- # Matches +addr+ against this entry.
-
- def match(addr)
- case @pat[0]
- when :all
- true
- when :ip
- begin
- ipaddr = IPAddr.new(addr[3])
- ipaddr = ipaddr.ipv4_mapped if @pat[1].ipv6? && ipaddr.ipv4?
- rescue ArgumentError
- return false
- end
- (@pat[1].include?(ipaddr)) ? true : false
- when :name
- (@pat[1] =~ addr[2]) ? true : false
- else
- false
- end
- end
- end
-
- ##
- # A list of ACLEntry objects. Used to implement the allow and deny halves
- # of an ACL
-
- class ACLList
-
- ##
- # Creates an empty ACLList
-
- def initialize
- @list = []
- end
-
- public
-
- ##
- # Matches +addr+ against each ACLEntry in this list.
-
- def match(addr)
- @list.each do |e|
- return true if e.match(addr)
- end
- false
- end
-
- public
-
- ##
- # Adds +str+ as an ACLEntry in this list
-
- def add(str)
- @list.push(ACLEntry.new(str))
- end
-
- end
-
- ##
- # Default to deny
-
- DENY_ALLOW = 0
-
- ##
- # Default to allow
-
- ALLOW_DENY = 1
-
- ##
- # Creates a new ACL from +list+ with an evaluation +order+ of DENY_ALLOW or
- # ALLOW_DENY.
- #
- # An ACL +list+ is an Array of "allow" or "deny" and an address or address
- # mask or "all" or "*" to match any address:
- #
- # %w[
- # deny all
- # allow 192.0.2.2
- # allow 192.0.2.128/26
- # ]
-
- def initialize(list=nil, order = DENY_ALLOW)
- @order = order
- @deny = ACLList.new
- @allow = ACLList.new
- install_list(list) if list
- end
-
- public
-
- ##
- # Allow connections from Socket +soc+?
-
- def allow_socket?(soc)
- allow_addr?(soc.peeraddr)
- end
-
- public
-
- ##
- # Allow connections from addrinfo +addr+? It must be formatted like
- # Socket#peeraddr:
- #
- # ["AF_INET", 10, "lc630", "192.0.2.1"]
-
- def allow_addr?(addr)
- case @order
- when DENY_ALLOW
- return true if @allow.match(addr)
- return false if @deny.match(addr)
- return true
- when ALLOW_DENY
- return false if @deny.match(addr)
- return true if @allow.match(addr)
- return false
- else
- false
- end
- end
-
- public
-
- ##
- # Adds +list+ of ACL entries to this ACL.
-
- def install_list(list)
- i = 0
- while i < list.size
- permission, domain = list.slice(i,2)
- case permission.downcase
- when 'allow'
- @allow.add(domain)
- when 'deny'
- @deny.add(domain)
- else
- raise "Invalid ACL entry #{list.to_s}"
- end
- i += 2
- end
- end
-
-end
-
-if __FILE__ == $0
- # example
- list = %w(deny all
- allow 192.168.1.1
- allow ::ffff:192.168.1.2
- allow 192.168.1.3
- )
-
- addr = ["AF_INET", 10, "lc630", "192.168.1.3"]
-
- acl = ACL.new
- p acl.allow_addr?(addr)
-
- acl = ACL.new(list, ACL::DENY_ALLOW)
- p acl.allow_addr?(addr)
-end
-
diff --git a/ruby_1_9_3/lib/drb/drb.rb b/ruby_1_9_3/lib/drb/drb.rb
deleted file mode 100644
index 69456b1db2..0000000000
--- a/ruby_1_9_3/lib/drb/drb.rb
+++ /dev/null
@@ -1,1774 +0,0 @@
-#
-# = drb/drb.rb
-#
-# Distributed Ruby: _dRuby_ version 2.0.4
-#
-# Copyright (c) 1999-2003 Masatoshi SEKI. You can redistribute it and/or
-# modify it under the same terms as Ruby.
-#
-# Author:: Masatoshi SEKI
-#
-# Documentation:: William Webber (william@williamwebber.com)
-#
-# == Overview
-#
-# dRuby is a distributed object system for Ruby. It allows an object in one
-# Ruby process to invoke methods on an object in another Ruby process on the
-# same or a different machine.
-#
-# The Ruby standard library contains the core classes of the dRuby package.
-# However, the full package also includes access control lists and the
-# Rinda tuple-space distributed task management system, as well as a
-# large number of samples. The full dRuby package can be downloaded from
-# the dRuby home page (see *References*).
-#
-# For an introduction and examples of usage see the documentation to the
-# DRb module.
-#
-# == References
-#
-# [http://www2a.biglobe.ne.jp/~seki/ruby/druby.html]
-# The dRuby home page, in Japanese. Contains the full dRuby package
-# and links to other Japanese-language sources.
-#
-# [http://www2a.biglobe.ne.jp/~seki/ruby/druby.en.html]
-# The English version of the dRuby home page.
-#
-# [http://www.chadfowler.com/ruby/drb.html]
-# A quick tutorial introduction to using dRuby by Chad Fowler.
-#
-# [http://www.linux-mag.com/2002-09/ruby_05.html]
-# A tutorial introduction to dRuby in Linux Magazine by Dave Thomas.
-# Includes a discussion of Rinda.
-#
-# [http://www.eng.cse.dmu.ac.uk/~hgs/ruby/dRuby/]
-# Links to English-language Ruby material collected by Hugh Sasse.
-#
-# [http://www.rubycentral.com/book/ospace.html]
-# The chapter from *Programming* *Ruby* by Dave Thomas and Andy Hunt
-# which discusses dRuby.
-#
-# [http://www.clio.ne.jp/home/web-i31s/Flotuard/Ruby/PRC2K_seki/dRuby.en.html]
-# Translation of presentation on Ruby by Masatoshi Seki.
-
-require 'socket'
-require 'thread'
-require 'fcntl'
-require 'drb/eq'
-
-#
-# == Overview
-#
-# dRuby is a distributed object system for Ruby. It is written in
-# pure Ruby and uses its own protocol. No add-in services are needed
-# beyond those provided by the Ruby runtime, such as TCP sockets. It
-# does not rely on or interoperate with other distributed object
-# systems such as CORBA, RMI, or .NET.
-#
-# dRuby allows methods to be called in one Ruby process upon a Ruby
-# object located in another Ruby process, even on another machine.
-# References to objects can be passed between processes. Method
-# arguments and return values are dumped and loaded in marshalled
-# format. All of this is done transparently to both the caller of the
-# remote method and the object that it is called upon.
-#
-# An object in a remote process is locally represented by a
-# DRb::DRbObject instance. This acts as a sort of proxy for the
-# remote object. Methods called upon this DRbObject instance are
-# forwarded to its remote object. This is arranged dynamically at run
-# time. There are no statically declared interfaces for remote
-# objects, such as CORBA's IDL.
-#
-# dRuby calls made into a process are handled by a DRb::DRbServer
-# instance within that process. This reconstitutes the method call,
-# invokes it upon the specified local object, and returns the value to
-# the remote caller. Any object can receive calls over dRuby. There
-# is no need to implement a special interface, or mixin special
-# functionality. Nor, in the general case, does an object need to
-# explicitly register itself with a DRbServer in order to receive
-# dRuby calls.
-#
-# One process wishing to make dRuby calls upon another process must
-# somehow obtain an initial reference to an object in the remote
-# process by some means other than as the return value of a remote
-# method call, as there is initially no remote object reference it can
-# invoke a method upon. This is done by attaching to the server by
-# URI. Each DRbServer binds itself to a URI such as
-# 'druby://example.com:8787'. A DRbServer can have an object attached
-# to it that acts as the server's *front* *object*. A DRbObject can
-# be explicitly created from the server's URI. This DRbObject's
-# remote object will be the server's front object. This front object
-# can then return references to other Ruby objects in the DRbServer's
-# process.
-#
-# Method calls made over dRuby behave largely the same as normal Ruby
-# method calls made within a process. Method calls with blocks are
-# supported, as are raising exceptions. In addition to a method's
-# standard errors, a dRuby call may also raise one of the
-# dRuby-specific errors, all of which are subclasses of DRb::DRbError.
-#
-# Any type of object can be passed as an argument to a dRuby call or
-# returned as its return value. By default, such objects are dumped
-# or marshalled at the local end, then loaded or unmarshalled at the
-# remote end. The remote end therefore receives a copy of the local
-# object, not a distributed reference to it; methods invoked upon this
-# copy are executed entirely in the remote process, not passed on to
-# the local original. This has semantics similar to pass-by-value.
-#
-# However, if an object cannot be marshalled, a dRuby reference to it
-# is passed or returned instead. This will turn up at the remote end
-# as a DRbObject instance. All methods invoked upon this remote proxy
-# are forwarded to the local object, as described in the discussion of
-# DRbObjects. This has semantics similar to the normal Ruby
-# pass-by-reference.
-#
-# The easiest way to signal that we want an otherwise marshallable
-# object to be passed or returned as a DRbObject reference, rather
-# than marshalled and sent as a copy, is to include the
-# DRb::DRbUndumped mixin module.
-#
-# dRuby supports calling remote methods with blocks. As blocks (or
-# rather the Proc objects that represent them) are not marshallable,
-# the block executes in the local, not the remote, context. Each
-# value yielded to the block is passed from the remote object to the
-# local block, then the value returned by each block invocation is
-# passed back to the remote execution context to be collected, before
-# the collected values are finally returned to the local context as
-# the return value of the method invocation.
-#
-# == Examples of usage
-#
-# For more dRuby samples, see the +samples+ directory in the full
-# dRuby distribution.
-#
-# === dRuby in client/server mode
-#
-# This illustrates setting up a simple client-server drb
-# system. Run the server and client code in different terminals,
-# starting the server code first.
-#
-# ==== Server code
-#
-# require 'drb/drb'
-#
-# # The URI for the server to connect to
-# URI="druby://localhost:8787"
-#
-# class TimeServer
-#
-# def get_current_time
-# return Time.now
-# end
-#
-# end
-#
-# # The object that handles requests on the server
-# FRONT_OBJECT=TimeServer.new
-#
-# $SAFE = 1 # disable eval() and friends
-#
-# DRb.start_service(URI, FRONT_OBJECT)
-# # Wait for the drb server thread to finish before exiting.
-# DRb.thread.join
-#
-# ==== Client code
-#
-# require 'drb/drb'
-#
-# # The URI to connect to
-# SERVER_URI="druby://localhost:8787"
-#
-# # Start a local DRbServer to handle callbacks.
-# #
-# # Not necessary for this small example, but will be required
-# # as soon as we pass a non-marshallable object as an argument
-# # to a dRuby call.
-# DRb.start_service
-#
-# timeserver = DRbObject.new_with_uri(SERVER_URI)
-# puts timeserver.get_current_time
-#
-# === Remote objects under dRuby
-#
-# This example illustrates returning a reference to an object
-# from a dRuby call. The Logger instances live in the server
-# process. References to them are returned to the client process,
-# where methods can be invoked upon them. These methods are
-# executed in the server process.
-#
-# ==== Server code
-#
-# require 'drb/drb'
-#
-# URI="druby://localhost:8787"
-#
-# class Logger
-#
-# # Make dRuby send Logger instances as dRuby references,
-# # not copies.
-# include DRb::DRbUndumped
-#
-# def initialize(n, fname)
-# @name = n
-# @filename = fname
-# end
-#
-# def log(message)
-# File.open(@filename, "a") do |f|
-# f.puts("#{Time.now}: #{@name}: #{message}")
-# end
-# end
-#
-# end
-#
-# # We have a central object for creating and retrieving loggers.
-# # This retains a local reference to all loggers created. This
-# # is so an existing logger can be looked up by name, but also
-# # to prevent loggers from being garbage collected. A dRuby
-# # reference to an object is not sufficient to prevent it being
-# # garbage collected!
-# class LoggerFactory
-#
-# def initialize(bdir)
-# @basedir = bdir
-# @loggers = {}
-# end
-#
-# def get_logger(name)
-# if !@loggers.has_key? name
-# # make the filename safe, then declare it to be so
-# fname = name.gsub(/[.\/]/, "_").untaint
-# @loggers[name] = Logger.new(name, @basedir + "/" + fname)
-# end
-# return @loggers[name]
-# end
-#
-# end
-#
-# FRONT_OBJECT=LoggerFactory.new("/tmp/dlog")
-#
-# $SAFE = 1 # disable eval() and friends
-#
-# DRb.start_service(URI, FRONT_OBJECT)
-# DRb.thread.join
-#
-# ==== Client code
-#
-# require 'drb/drb'
-#
-# SERVER_URI="druby://localhost:8787"
-#
-# DRb.start_service
-#
-# log_service=DRbObject.new_with_uri(SERVER_URI)
-#
-# ["loga", "logb", "logc"].each do |logname|
-#
-# logger=log_service.get_logger(logname)
-#
-# logger.log("Hello, world!")
-# logger.log("Goodbye, world!")
-# logger.log("=== EOT ===")
-#
-# end
-#
-# == Security
-#
-# As with all network services, security needs to be considered when
-# using dRuby. By allowing external access to a Ruby object, you are
-# not only allowing outside clients to call the methods you have
-# defined for that object, but by default to execute arbitrary Ruby
-# code on your server. Consider the following:
-#
-# # !!! UNSAFE CODE !!!
-# ro = DRbObject::new_with_uri("druby://your.server.com:8989")
-# class << ro
-# undef :instance_eval # force call to be passed to remote object
-# end
-# ro.instance_eval("`rm -rf *`")
-#
-# The dangers posed by instance_eval and friends are such that a
-# DRbServer should generally be run with $SAFE set to at least
-# level 1. This will disable eval() and related calls on strings
-# passed across the wire. The sample usage code given above follows
-# this practice.
-#
-# A DRbServer can be configured with an access control list to
-# selectively allow or deny access from specified IP addresses. The
-# main druby distribution provides the ACL class for this purpose. In
-# general, this mechanism should only be used alongside, rather than
-# as a replacement for, a good firewall.
-#
-# == dRuby internals
-#
-# dRuby is implemented using three main components: a remote method
-# call marshaller/unmarshaller; a transport protocol; and an
-# ID-to-object mapper. The latter two can be directly, and the first
-# indirectly, replaced, in order to provide different behaviour and
-# capabilities.
-#
-# Marshalling and unmarshalling of remote method calls is performed by
-# a DRb::DRbMessage instance. This uses the Marshal module to dump
-# the method call before sending it over the transport layer, then
-# reconstitute it at the other end. There is normally no need to
-# replace this component, and no direct way is provided to do so.
-# However, it is possible to implement an alternative marshalling
-# scheme as part of an implementation of the transport layer.
-#
-# The transport layer is responsible for opening client and server
-# network connections and forwarding dRuby request across them.
-# Normally, it uses DRb::DRbMessage internally to manage marshalling
-# and unmarshalling. The transport layer is managed by
-# DRb::DRbProtocol. Multiple protocols can be installed in
-# DRbProtocol at the one time; selection between them is determined by
-# the scheme of a dRuby URI. The default transport protocol is
-# selected by the scheme 'druby:', and implemented by
-# DRb::DRbTCPSocket. This uses plain TCP/IP sockets for
-# communication. An alternative protocol, using UNIX domain sockets,
-# is implemented by DRb::DRbUNIXSocket in the file drb/unix.rb, and
-# selected by the scheme 'drbunix:'. A sample implementation over
-# HTTP can be found in the samples accompanying the main dRuby
-# distribution.
-#
-# The ID-to-object mapping component maps dRuby object ids to the
-# objects they refer to, and vice versa. The implementation to use
-# can be specified as part of a DRb::DRbServer's configuration. The
-# default implementation is provided by DRb::DRbIdConv. It uses an
-# object's ObjectSpace id as its dRuby id. This means that the dRuby
-# reference to that object only remains meaningful for the lifetime of
-# the object's process and the lifetime of the object within that
-# process. A modified implementation is provided by DRb::TimerIdConv
-# in the file drb/timeridconv.rb. This implementation retains a local
-# reference to all objects exported over dRuby for a configurable
-# period of time (defaulting to ten minutes), to prevent them being
-# garbage-collected within this time. Another sample implementation
-# is provided in sample/name.rb in the main dRuby distribution. This
-# allows objects to specify their own id or "name". A dRuby reference
-# can be made persistent across processes by having each process
-# register an object using the same dRuby name.
-#
-module DRb
-
- # Superclass of all errors raised in the DRb module.
- class DRbError < RuntimeError; end
-
- # Error raised when an error occurs on the underlying communication
- # protocol.
- class DRbConnError < DRbError; end
-
- # Class responsible for converting between an object and its id.
- #
- # This, the default implementation, uses an object's local ObjectSpace
- # __id__ as its id. This means that an object's identification over
- # drb remains valid only while that object instance remains alive
- # within the server runtime.
- #
- # For alternative mechanisms, see DRb::TimerIdConv in rdb/timeridconv.rb
- # and DRbNameIdConv in sample/name.rb in the full drb distribution.
- class DRbIdConv
-
- # Convert an object reference id to an object.
- #
- # This implementation looks up the reference id in the local object
- # space and returns the object it refers to.
- def to_obj(ref)
- ObjectSpace._id2ref(ref)
- end
-
- # Convert an object into a reference id.
- #
- # This implementation returns the object's __id__ in the local
- # object space.
- def to_id(obj)
- obj.nil? ? nil : obj.__id__
- end
- end
-
- # Mixin module making an object undumpable or unmarshallable.
- #
- # If an object which includes this module is returned by method
- # called over drb, then the object remains in the server space
- # and a reference to the object is returned, rather than the
- # object being marshalled and moved into the client space.
- module DRbUndumped
- def _dump(dummy) # :nodoc:
- raise TypeError, 'can\'t dump'
- end
- end
-
- # Error raised by the DRb module when an attempt is made to refer to
- # the context's current drb server but the context does not have one.
- # See #current_server.
- class DRbServerNotFound < DRbError; end
-
- # Error raised by the DRbProtocol module when it cannot find any
- # protocol implementation support the scheme specified in a URI.
- class DRbBadURI < DRbError; end
-
- # Error raised by a dRuby protocol when it doesn't support the
- # scheme specified in a URI. See DRb::DRbProtocol.
- class DRbBadScheme < DRbError; end
-
- # An exception wrapping a DRb::DRbUnknown object
- class DRbUnknownError < DRbError
-
- # Create a new DRbUnknownError for the DRb::DRbUnknown object +unknown+
- def initialize(unknown)
- @unknown = unknown
- super(unknown.name)
- end
-
- # Get the wrapped DRb::DRbUnknown object.
- attr_reader :unknown
-
- def self._load(s) # :nodoc:
- Marshal::load(s)
- end
-
- def _dump(lv) # :nodoc:
- Marshal::dump(@unknown)
- end
- end
-
- # An exception wrapping an error object
- class DRbRemoteError < DRbError
- def initialize(error)
- @reason = error.class.to_s
- super("#{error.message} (#{error.class})")
- set_backtrace(error.backtrace)
- end
-
- # the class of the error, as a string.
- attr_reader :reason
- end
-
- # Class wrapping a marshalled object whose type is unknown locally.
- #
- # If an object is returned by a method invoked over drb, but the
- # class of the object is unknown in the client namespace, or
- # the object is a constant unknown in the client namespace, then
- # the still-marshalled object is returned wrapped in a DRbUnknown instance.
- #
- # If this object is passed as an argument to a method invoked over
- # drb, then the wrapped object is passed instead.
- #
- # The class or constant name of the object can be read from the
- # +name+ attribute. The marshalled object is held in the +buf+
- # attribute.
- class DRbUnknown
-
- # Create a new DRbUnknown object.
- #
- # +buf+ is a string containing a marshalled object that could not
- # be unmarshalled. +err+ is the error message that was raised
- # when the unmarshalling failed. It is used to determine the
- # name of the unmarshalled object.
- def initialize(err, buf)
- case err.to_s
- when /uninitialized constant (\S+)/
- @name = $1
- when /undefined class\/module (\S+)/
- @name = $1
- else
- @name = nil
- end
- @buf = buf
- end
-
- # The name of the unknown thing.
- #
- # Class name for unknown objects; variable name for unknown
- # constants.
- attr_reader :name
-
- # Buffer contained the marshalled, unknown object.
- attr_reader :buf
-
- def self._load(s) # :nodoc:
- begin
- Marshal::load(s)
- rescue NameError, ArgumentError
- DRbUnknown.new($!, s)
- end
- end
-
- def _dump(lv) # :nodoc:
- @buf
- end
-
- # Attempt to load the wrapped marshalled object again.
- #
- # If the class of the object is now known locally, the object
- # will be unmarshalled and returned. Otherwise, a new
- # but identical DRbUnknown object will be returned.
- def reload
- self.class._load(@buf)
- end
-
- # Create a DRbUnknownError exception containing this object.
- def exception
- DRbUnknownError.new(self)
- end
- end
-
- class DRbArray
- def initialize(ary)
- @ary = ary.collect { |obj|
- if obj.kind_of? DRbUndumped
- DRbObject.new(obj)
- else
- begin
- Marshal.dump(obj)
- obj
- rescue
- DRbObject.new(obj)
- end
- end
- }
- end
-
- def self._load(s)
- Marshal::load(s)
- end
-
- def _dump(lv)
- Marshal.dump(@ary)
- end
- end
-
- # Handler for sending and receiving drb messages.
- #
- # This takes care of the low-level marshalling and unmarshalling
- # of drb requests and responses sent over the wire between server
- # and client. This relieves the implementor of a new drb
- # protocol layer with having to deal with these details.
- #
- # The user does not have to directly deal with this object in
- # normal use.
- class DRbMessage
- def initialize(config) # :nodoc:
- @load_limit = config[:load_limit]
- @argc_limit = config[:argc_limit]
- end
-
- def dump(obj, error=false) # :nodoc:
- obj = make_proxy(obj, error) if obj.kind_of? DRbUndumped
- begin
- str = Marshal::dump(obj)
- rescue
- str = Marshal::dump(make_proxy(obj, error))
- end
- [str.size].pack('N') + str
- end
-
- def load(soc) # :nodoc:
- begin
- sz = soc.read(4) # sizeof (N)
- rescue
- raise(DRbConnError, $!.message, $!.backtrace)
- end
- raise(DRbConnError, 'connection closed') if sz.nil?
- raise(DRbConnError, 'premature header') if sz.size < 4
- sz = sz.unpack('N')[0]
- raise(DRbConnError, "too large packet #{sz}") if @load_limit < sz
- begin
- str = soc.read(sz)
- rescue
- raise(DRbConnError, $!.message, $!.backtrace)
- end
- raise(DRbConnError, 'connection closed') if str.nil?
- raise(DRbConnError, 'premature marshal format(can\'t read)') if str.size < sz
- DRb.mutex.synchronize do
- begin
- save = Thread.current[:drb_untaint]
- Thread.current[:drb_untaint] = []
- Marshal::load(str)
- rescue NameError, ArgumentError
- DRbUnknown.new($!, str)
- ensure
- Thread.current[:drb_untaint].each do |x|
- x.untaint
- end
- Thread.current[:drb_untaint] = save
- end
- end
- end
-
- def send_request(stream, ref, msg_id, arg, b) # :nodoc:
- ary = []
- ary.push(dump(ref.__drbref))
- ary.push(dump(msg_id.id2name))
- ary.push(dump(arg.length))
- arg.each do |e|
- ary.push(dump(e))
- end
- ary.push(dump(b))
- stream.write(ary.join(''))
- rescue
- raise(DRbConnError, $!.message, $!.backtrace)
- end
-
- def recv_request(stream) # :nodoc:
- ref = load(stream)
- ro = DRb.to_obj(ref)
- msg = load(stream)
- argc = load(stream)
- raise(DRbConnError, "too many arguments") if @argc_limit < argc
- argv = Array.new(argc, nil)
- argc.times do |n|
- argv[n] = load(stream)
- end
- block = load(stream)
- return ro, msg, argv, block
- end
-
- def send_reply(stream, succ, result) # :nodoc:
- stream.write(dump(succ) + dump(result, !succ))
- rescue
- raise(DRbConnError, $!.message, $!.backtrace)
- end
-
- def recv_reply(stream) # :nodoc:
- succ = load(stream)
- result = load(stream)
- [succ, result]
- end
-
- private
- def make_proxy(obj, error=false)
- if error
- DRbRemoteError.new(obj)
- else
- DRbObject.new(obj)
- end
- end
- end
-
- # Module managing the underlying network protocol(s) used by drb.
- #
- # By default, drb uses the DRbTCPSocket protocol. Other protocols
- # can be defined. A protocol must define the following class methods:
- #
- # [open(uri, config)] Open a client connection to the server at +uri+,
- # using configuration +config+. Return a protocol
- # instance for this connection.
- # [open_server(uri, config)] Open a server listening at +uri+,
- # using configuration +config+. Return a
- # protocol instance for this listener.
- # [uri_option(uri, config)] Take a URI, possibly containing an option
- # component (e.g. a trailing '?param=val'),
- # and return a [uri, option] tuple.
- #
- # All of these methods should raise a DRbBadScheme error if the URI
- # does not identify the protocol they support (e.g. "druby:" for
- # the standard Ruby protocol). This is how the DRbProtocol module,
- # given a URI, determines which protocol implementation serves that
- # protocol.
- #
- # The protocol instance returned by #open_server must have the
- # following methods:
- #
- # [accept] Accept a new connection to the server. Returns a protocol
- # instance capable of communicating with the client.
- # [close] Close the server connection.
- # [uri] Get the URI for this server.
- #
- # The protocol instance returned by #open must have the following methods:
- #
- # [send_request (ref, msg_id, arg, b)]
- # Send a request to +ref+ with the given message id and arguments.
- # This is most easily implemented by calling DRbMessage.send_request,
- # providing a stream that sits on top of the current protocol.
- # [recv_reply]
- # Receive a reply from the server and return it as a [success-boolean,
- # reply-value] pair. This is most easily implemented by calling
- # DRb.recv_reply, providing a stream that sits on top of the
- # current protocol.
- # [alive?]
- # Is this connection still alive?
- # [close]
- # Close this connection.
- #
- # The protocol instance returned by #open_server().accept() must have
- # the following methods:
- #
- # [recv_request]
- # Receive a request from the client and return a [object, message,
- # args, block] tuple. This is most easily implemented by calling
- # DRbMessage.recv_request, providing a stream that sits on top of
- # the current protocol.
- # [send_reply(succ, result)]
- # Send a reply to the client. This is most easily implemented
- # by calling DRbMessage.send_reply, providing a stream that sits
- # on top of the current protocol.
- # [close]
- # Close this connection.
- #
- # A new protocol is registered with the DRbProtocol module using
- # the add_protocol method.
- #
- # For examples of other protocols, see DRbUNIXSocket in drb/unix.rb,
- # and HTTP0 in sample/http0.rb and sample/http0serv.rb in the full
- # drb distribution.
- module DRbProtocol
-
- # Add a new protocol to the DRbProtocol module.
- def add_protocol(prot)
- @protocol.push(prot)
- end
- module_function :add_protocol
-
- # Open a client connection to +uri+ with the configuration +config+.
- #
- # The DRbProtocol module asks each registered protocol in turn to
- # try to open the URI. Each protocol signals that it does not handle that
- # URI by raising a DRbBadScheme error. If no protocol recognises the
- # URI, then a DRbBadURI error is raised. If a protocol accepts the
- # URI, but an error occurs in opening it, a DRbConnError is raised.
- def open(uri, config, first=true)
- @protocol.each do |prot|
- begin
- return prot.open(uri, config)
- rescue DRbBadScheme
- rescue DRbConnError
- raise($!)
- rescue
- raise(DRbConnError, "#{uri} - #{$!.inspect}")
- end
- end
- if first && (config[:auto_load] != false)
- auto_load(uri, config)
- return open(uri, config, false)
- end
- raise DRbBadURI, 'can\'t parse uri:' + uri
- end
- module_function :open
-
- # Open a server listening for connections at +uri+ with
- # configuration +config+.
- #
- # The DRbProtocol module asks each registered protocol in turn to
- # try to open a server at the URI. Each protocol signals that it does
- # not handle that URI by raising a DRbBadScheme error. If no protocol
- # recognises the URI, then a DRbBadURI error is raised. If a protocol
- # accepts the URI, but an error occurs in opening it, the underlying
- # error is passed on to the caller.
- def open_server(uri, config, first=true)
- @protocol.each do |prot|
- begin
- return prot.open_server(uri, config)
- rescue DRbBadScheme
- end
- end
- if first && (config[:auto_load] != false)
- auto_load(uri, config)
- return open_server(uri, config, false)
- end
- raise DRbBadURI, 'can\'t parse uri:' + uri
- end
- module_function :open_server
-
- # Parse +uri+ into a [uri, option] pair.
- #
- # The DRbProtocol module asks each registered protocol in turn to
- # try to parse the URI. Each protocol signals that it does not handle that
- # URI by raising a DRbBadScheme error. If no protocol recognises the
- # URI, then a DRbBadURI error is raised.
- def uri_option(uri, config, first=true)
- @protocol.each do |prot|
- begin
- uri, opt = prot.uri_option(uri, config)
- # opt = nil if opt == ''
- return uri, opt
- rescue DRbBadScheme
- end
- end
- if first && (config[:auto_load] != false)
- auto_load(uri, config)
- return uri_option(uri, config, false)
- end
- raise DRbBadURI, 'can\'t parse uri:' + uri
- end
- module_function :uri_option
-
- def auto_load(uri, config) # :nodoc:
- if uri =~ /^drb([a-z0-9]+):/
- require("drb/#{$1}") rescue nil
- end
- end
- module_function :auto_load
- end
-
- # The default drb protocol.
- #
- # Communicates over a TCP socket.
- class DRbTCPSocket
- private
- def self.parse_uri(uri)
- if uri =~ /^druby:\/\/(.*?):(\d+)(\?(.*))?$/
- host = $1
- port = $2.to_i
- option = $4
- [host, port, option]
- else
- raise(DRbBadScheme, uri) unless uri =~ /^druby:/
- raise(DRbBadURI, 'can\'t parse uri:' + uri)
- end
- end
-
- public
-
- # Open a client connection to +uri+ using configuration +config+.
- def self.open(uri, config)
- host, port, = parse_uri(uri)
- host.untaint
- port.untaint
- soc = TCPSocket.open(host, port)
- self.new(uri, soc, config)
- end
-
- def self.getservername
- host = Socket::gethostname
- begin
- Socket::gethostbyname(host)[0]
- rescue
- 'localhost'
- end
- end
-
- def self.open_server_inaddr_any(host, port)
- infos = Socket::getaddrinfo(host, nil,
- Socket::AF_UNSPEC,
- Socket::SOCK_STREAM,
- 0,
- Socket::AI_PASSIVE)
- families = Hash[*infos.collect { |af, *_| af }.uniq.zip([]).flatten]
- return TCPServer.open('0.0.0.0', port) if families.has_key?('AF_INET')
- return TCPServer.open('::', port) if families.has_key?('AF_INET6')
- return TCPServer.open(port)
- end
-
- # Open a server listening for connections at +uri+ using
- # configuration +config+.
- def self.open_server(uri, config)
- uri = 'druby://:0' unless uri
- host, port, _ = parse_uri(uri)
- config = {:tcp_original_host => host}.update(config)
- if host.size == 0
- host = getservername
- soc = open_server_inaddr_any(host, port)
- else
- soc = TCPServer.open(host, port)
- end
- port = soc.addr[1] if port == 0
- config[:tcp_port] = port
- uri = "druby://#{host}:#{port}"
- self.new(uri, soc, config)
- end
-
- # Parse +uri+ into a [uri, option] pair.
- def self.uri_option(uri, config)
- host, port, option = parse_uri(uri)
- return "druby://#{host}:#{port}", option
- end
-
- # Create a new DRbTCPSocket instance.
- #
- # +uri+ is the URI we are connected to.
- # +soc+ is the tcp socket we are bound to. +config+ is our
- # configuration.
- def initialize(uri, soc, config={})
- @uri = uri
- @socket = soc
- @config = config
- @acl = config[:tcp_acl]
- @msg = DRbMessage.new(config)
- set_sockopt(@socket)
- end
-
- # Get the URI that we are connected to.
- attr_reader :uri
-
- # Get the address of our TCP peer (the other end of the socket
- # we are bound to.
- def peeraddr
- @socket.peeraddr
- end
-
- # Get the socket.
- def stream; @socket; end
-
- # On the client side, send a request to the server.
- def send_request(ref, msg_id, arg, b)
- @msg.send_request(stream, ref, msg_id, arg, b)
- end
-
- # On the server side, receive a request from the client.
- def recv_request
- @msg.recv_request(stream)
- end
-
- # On the server side, send a reply to the client.
- def send_reply(succ, result)
- @msg.send_reply(stream, succ, result)
- end
-
- # On the client side, receive a reply from the server.
- def recv_reply
- @msg.recv_reply(stream)
- end
-
- public
-
- # Close the connection.
- #
- # If this is an instance returned by #open_server, then this stops
- # listening for new connections altogether. If this is an instance
- # returned by #open or by #accept, then it closes this particular
- # client-server session.
- def close
- if @socket
- @socket.close
- @socket = nil
- end
- end
-
- # On the server side, for an instance returned by #open_server,
- # accept a client connection and return a new instance to handle
- # the server's side of this client-server session.
- def accept
- while true
- s = @socket.accept
- break if (@acl ? @acl.allow_socket?(s) : true)
- s.close
- end
- if @config[:tcp_original_host].to_s.size == 0
- uri = "druby://#{s.addr[3]}:#{@config[:tcp_port]}"
- else
- uri = @uri
- end
- self.class.new(uri, s, @config)
- end
-
- # Check to see if this connection is alive.
- def alive?
- return false unless @socket
- if IO.select([@socket], nil, nil, 0)
- close
- return false
- end
- true
- end
-
- def set_sockopt(soc) # :nodoc:
- soc.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
- soc.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) if defined? Fcntl::FD_CLOEXEC
- end
- end
-
- module DRbProtocol
- @protocol = [DRbTCPSocket] # default
- end
-
- class DRbURIOption # :nodoc: I don't understand the purpose of this class...
- def initialize(option)
- @option = option.to_s
- end
- attr :option
- def to_s; @option; end
-
- def ==(other)
- return false unless DRbURIOption === other
- @option == other.option
- end
-
- def hash
- @option.hash
- end
-
- alias eql? ==
- end
-
- # Object wrapping a reference to a remote drb object.
- #
- # Method calls on this object are relayed to the remote
- # object that this object is a stub for.
- class DRbObject
-
- # Unmarshall a marshalled DRbObject.
- #
- # If the referenced object is located within the local server, then
- # the object itself is returned. Otherwise, a new DRbObject is
- # created to act as a stub for the remote referenced object.
- def self._load(s)
- uri, ref = Marshal.load(s)
-
- if DRb.here?(uri)
- obj = DRb.to_obj(ref)
- if ((! obj.tainted?) && Thread.current[:drb_untaint])
- Thread.current[:drb_untaint].push(obj)
- end
- return obj
- end
-
- self.new_with(uri, ref)
- end
-
- def self.new_with(uri, ref)
- it = self.allocate
- it.instance_variable_set('@uri', uri)
- it.instance_variable_set('@ref', ref)
- it
- end
-
- # Create a new DRbObject from a URI alone.
- def self.new_with_uri(uri)
- self.new(nil, uri)
- end
-
- # Marshall this object.
- #
- # The URI and ref of the object are marshalled.
- def _dump(lv)
- Marshal.dump([@uri, @ref])
- end
-
- # Create a new remote object stub.
- #
- # +obj+ is the (local) object we want to create a stub for. Normally
- # this is +nil+. +uri+ is the URI of the remote object that this
- # will be a stub for.
- def initialize(obj, uri=nil)
- @uri = nil
- @ref = nil
- if obj.nil?
- return if uri.nil?
- @uri, option = DRbProtocol.uri_option(uri, DRb.config)
- @ref = DRbURIOption.new(option) unless option.nil?
- else
- @uri = uri ? uri : (DRb.uri rescue nil)
- @ref = obj ? DRb.to_id(obj) : nil
- end
- end
-
- # Get the URI of the remote object.
- def __drburi
- @uri
- end
-
- # Get the reference of the object, if local.
- def __drbref
- @ref
- end
-
- undef :to_s
- undef :to_a if respond_to?(:to_a)
-
- def respond_to?(msg_id, priv=false)
- case msg_id
- when :_dump
- true
- when :marshal_dump
- false
- else
- method_missing(:respond_to?, msg_id, priv)
- end
- end
-
- # Routes method calls to the referenced object.
- def method_missing(msg_id, *a, &b)
- if DRb.here?(@uri)
- obj = DRb.to_obj(@ref)
- DRb.current_server.check_insecure_method(obj, msg_id)
- return obj.__send__(msg_id, *a, &b)
- end
-
- succ, result = self.class.with_friend(@uri) do
- DRbConn.open(@uri) do |conn|
- conn.send_message(self, msg_id, a, b)
- end
- end
-
- if succ
- return result
- elsif DRbUnknown === result
- raise result
- else
- bt = self.class.prepare_backtrace(@uri, result)
- result.set_backtrace(bt + caller)
- raise result
- end
- end
-
- def self.with_friend(uri)
- friend = DRb.fetch_server(uri)
- return yield() unless friend
-
- save = Thread.current['DRb']
- Thread.current['DRb'] = { 'server' => friend }
- return yield
- ensure
- Thread.current['DRb'] = save if friend
- end
-
- def self.prepare_backtrace(uri, result)
- prefix = "(#{uri}) "
- bt = []
- result.backtrace.each do |x|
- break if /`__send__'$/ =~ x
- if /^\(druby:\/\// =~ x
- bt.push(x)
- else
- bt.push(prefix + x)
- end
- end
- bt
- end
-
- def pretty_print(q) # :nodoc:
- q.pp_object(self)
- end
-
- def pretty_print_cycle(q) # :nodoc:
- q.object_address_group(self) {
- q.breakable
- q.text '...'
- }
- end
- end
-
- # Class handling the connection between a DRbObject and the
- # server the real object lives on.
- #
- # This class maintains a pool of connections, to reduce the
- # overhead of starting and closing down connections for each
- # method call.
- #
- # This class is used internally by DRbObject. The user does
- # not normally need to deal with it directly.
- class DRbConn
- POOL_SIZE = 16 # :nodoc:
- @mutex = Mutex.new
- @pool = []
-
- def self.open(remote_uri) # :nodoc:
- begin
- conn = nil
-
- @mutex.synchronize do
- #FIXME
- new_pool = []
- @pool.each do |c|
- if conn.nil? and c.uri == remote_uri
- conn = c if c.alive?
- else
- new_pool.push c
- end
- end
- @pool = new_pool
- end
-
- conn = self.new(remote_uri) unless conn
- succ, result = yield(conn)
- return succ, result
-
- ensure
- if conn
- if succ
- @mutex.synchronize do
- @pool.unshift(conn)
- @pool.pop.close while @pool.size > POOL_SIZE
- end
- else
- conn.close
- end
- end
- end
- end
-
- def initialize(remote_uri) # :nodoc:
- @uri = remote_uri
- @protocol = DRbProtocol.open(remote_uri, DRb.config)
- end
- attr_reader :uri # :nodoc:
-
- def send_message(ref, msg_id, arg, block) # :nodoc:
- @protocol.send_request(ref, msg_id, arg, block)
- @protocol.recv_reply
- end
-
- def close # :nodoc:
- @protocol.close
- @protocol = nil
- end
-
- def alive? # :nodoc:
- return false unless @protocol
- @protocol.alive?
- end
- end
-
- # Class representing a drb server instance.
- #
- # A DRbServer must be running in the local process before any incoming
- # dRuby calls can be accepted, or any local objects can be passed as
- # dRuby references to remote processes, even if those local objects are
- # never actually called remotely. You do not need to start a DRbServer
- # in the local process if you are only making outgoing dRuby calls
- # passing marshalled parameters.
- #
- # Unless multiple servers are being used, the local DRbServer is normally
- # started by calling DRb.start_service.
- class DRbServer
- @@acl = nil
- @@idconv = DRbIdConv.new
- @@secondary_server = nil
- @@argc_limit = 256
- @@load_limit = 256 * 102400
- @@verbose = false
- @@safe_level = 0
-
- # Set the default value for the :argc_limit option.
- #
- # See #new(). The initial default value is 256.
- def self.default_argc_limit(argc)
- @@argc_limit = argc
- end
-
- # Set the default value for the :load_limit option.
- #
- # See #new(). The initial default value is 25 MB.
- def self.default_load_limit(sz)
- @@load_limit = sz
- end
-
- # Set the default value for the :acl option.
- #
- # See #new(). The initial default value is nil.
- def self.default_acl(acl)
- @@acl = acl
- end
-
- # Set the default value for the :id_conv option.
- #
- # See #new(). The initial default value is a DRbIdConv instance.
- def self.default_id_conv(idconv)
- @@idconv = idconv
- end
-
- def self.default_safe_level(level)
- @@safe_level = level
- end
-
- # Set the default value of the :verbose option.
- #
- # See #new(). The initial default value is false.
- def self.verbose=(on)
- @@verbose = on
- end
-
- # Get the default value of the :verbose option.
- def self.verbose
- @@verbose
- end
-
- def self.make_config(hash={}) # :nodoc:
- default_config = {
- :idconv => @@idconv,
- :verbose => @@verbose,
- :tcp_acl => @@acl,
- :load_limit => @@load_limit,
- :argc_limit => @@argc_limit,
- :safe_level => @@safe_level
- }
- default_config.update(hash)
- end
-
- # Create a new DRbServer instance.
- #
- # +uri+ is the URI to bind to. This is normally of the form
- # 'druby://<hostname>:<port>' where <hostname> is a hostname of
- # the local machine. If nil, then the system's default hostname
- # will be bound to, on a port selected by the system; these value
- # can be retrieved from the +uri+ attribute. 'druby:' specifies
- # the default dRuby transport protocol: another protocol, such
- # as 'drbunix:', can be specified instead.
- #
- # +front+ is the front object for the server, that is, the object
- # to which remote method calls on the server will be passed. If
- # nil, then the server will not accept remote method calls.
- #
- # If +config_or_acl+ is a hash, it is the configuration to
- # use for this server. The following options are recognised:
- #
- # :idconv :: an id-to-object conversion object. This defaults
- # to an instance of the class DRb::DRbIdConv.
- # :verbose :: if true, all unsuccessful remote calls on objects
- # in the server will be logged to $stdout. false
- # by default.
- # :tcp_acl :: the access control list for this server. See
- # the ACL class from the main dRuby distribution.
- # :load_limit :: the maximum message size in bytes accepted by
- # the server. Defaults to 25 MB (26214400).
- # :argc_limit :: the maximum number of arguments to a remote
- # method accepted by the server. Defaults to
- # 256.
- #
- # The default values of these options can be modified on
- # a class-wide basis by the class methods #default_argc_limit,
- # #default_load_limit, #default_acl, #default_id_conv,
- # and #verbose=
- #
- # If +config_or_acl+ is not a hash, but is not nil, it is
- # assumed to be the access control list for this server.
- # See the :tcp_acl option for more details.
- #
- # If no other server is currently set as the primary server,
- # this will become the primary server.
- #
- # The server will immediately start running in its own thread.
- def initialize(uri=nil, front=nil, config_or_acl=nil)
- if Hash === config_or_acl
- config = config_or_acl.dup
- else
- acl = config_or_acl || @@acl
- config = {
- :tcp_acl => acl
- }
- end
-
- @config = self.class.make_config(config)
-
- @protocol = DRbProtocol.open_server(uri, @config)
- @uri = @protocol.uri
- @exported_uri = [@uri]
-
- @front = front
- @idconv = @config[:idconv]
- @safe_level = @config[:safe_level]
-
- @grp = ThreadGroup.new
- @thread = run
-
- DRb.regist_server(self)
- end
-
- # The URI of this DRbServer.
- attr_reader :uri
-
- # The main thread of this DRbServer.
- #
- # This is the thread that listens for and accepts connections
- # from clients, not that handles each client's request-response
- # session.
- attr_reader :thread
-
- # The front object of the DRbServer.
- #
- # This object receives remote method calls made on the server's
- # URI alone, with an object id.
- attr_reader :front
-
- # The configuration of this DRbServer
- attr_reader :config
-
- attr_reader :safe_level
-
- # Set whether to operate in verbose mode.
- #
- # In verbose mode, failed calls are logged to stdout.
- def verbose=(v); @config[:verbose]=v; end
-
- # Get whether the server is in verbose mode.
- #
- # In verbose mode, failed calls are logged to stdout.
- def verbose; @config[:verbose]; end
-
- # Is this server alive?
- def alive?
- @thread.alive?
- end
-
- def here?(uri)
- @exported_uri.include?(uri)
- end
-
- # Stop this server.
- def stop_service
- DRb.remove_server(self)
- if Thread.current['DRb'] && Thread.current['DRb']['server'] == self
- Thread.current['DRb']['stop_service'] = true
- else
- @thread.kill.join
- end
- end
-
- # Convert a dRuby reference to the local object it refers to.
- def to_obj(ref)
- return front if ref.nil?
- return front[ref.to_s] if DRbURIOption === ref
- @idconv.to_obj(ref)
- end
-
- # Convert a local object to a dRuby reference.
- def to_id(obj)
- return nil if obj.__id__ == front.__id__
- @idconv.to_id(obj)
- end
-
- private
- def run
- Thread.start do
- begin
- while true
- main_loop
- end
- ensure
- @protocol.close if @protocol
- end
- end
- end
-
- # List of insecure methods.
- #
- # These methods are not callable via dRuby.
- INSECURE_METHOD = [
- :__send__
- ]
-
- # Has a method been included in the list of insecure methods?
- def insecure_method?(msg_id)
- INSECURE_METHOD.include?(msg_id)
- end
-
- # Coerce an object to a string, providing our own representation if
- # to_s is not defined for the object.
- def any_to_s(obj)
- obj.to_s + ":#{obj.class}"
- rescue
- sprintf("#<%s:0x%lx>", obj.class, obj.__id__)
- end
-
- # Check that a method is callable via dRuby.
- #
- # +obj+ is the object we want to invoke the method on. +msg_id+ is the
- # method name, as a Symbol.
- #
- # If the method is an insecure method (see #insecure_method?) a
- # SecurityError is thrown. If the method is private or undefined,
- # a NameError is thrown.
- def check_insecure_method(obj, msg_id)
- return true if Proc === obj && msg_id == :__drb_yield
- raise(ArgumentError, "#{any_to_s(msg_id)} is not a symbol") unless Symbol == msg_id.class
- raise(SecurityError, "insecure method `#{msg_id}'") if insecure_method?(msg_id)
-
- if obj.private_methods.include?(msg_id)
- desc = any_to_s(obj)
- raise NoMethodError, "private method `#{msg_id}' called for #{desc}"
- elsif obj.protected_methods.include?(msg_id)
- desc = any_to_s(obj)
- raise NoMethodError, "protected method `#{msg_id}' called for #{desc}"
- else
- true
- end
- end
- public :check_insecure_method
-
- class InvokeMethod # :nodoc:
- def initialize(drb_server, client)
- @drb_server = drb_server
- @safe_level = drb_server.safe_level
- @client = client
- end
-
- def perform
- @result = nil
- @succ = false
- setup_message
-
- if $SAFE < @safe_level
- info = Thread.current['DRb']
- if @block
- @result = Thread.new {
- Thread.current['DRb'] = info
- $SAFE = @safe_level
- perform_with_block
- }.value
- else
- @result = Thread.new {
- Thread.current['DRb'] = info
- $SAFE = @safe_level
- perform_without_block
- }.value
- end
- else
- if @block
- @result = perform_with_block
- else
- @result = perform_without_block
- end
- end
- @succ = true
- if @msg_id == :to_ary && @result.class == Array
- @result = DRbArray.new(@result)
- end
- return @succ, @result
- rescue StandardError, ScriptError, Interrupt
- @result = $!
- return @succ, @result
- end
-
- private
- def init_with_client
- obj, msg, argv, block = @client.recv_request
- @obj = obj
- @msg_id = msg.intern
- @argv = argv
- @block = block
- end
-
- def check_insecure_method
- @drb_server.check_insecure_method(@obj, @msg_id)
- end
-
- def setup_message
- init_with_client
- check_insecure_method
- end
-
- def perform_without_block
- if Proc === @obj && @msg_id == :__drb_yield
- if @argv.size == 1
- ary = @argv
- else
- ary = [@argv]
- end
- ary.collect(&@obj)[0]
- else
- @obj.__send__(@msg_id, *@argv)
- end
- end
-
- end
-
- if RUBY_VERSION >= '1.8'
- require 'drb/invokemethod'
- class InvokeMethod
- include InvokeMethod18Mixin
- end
- else
- require 'drb/invokemethod16'
- class InvokeMethod
- include InvokeMethod16Mixin
- end
- end
-
- # The main loop performed by a DRbServer's internal thread.
- #
- # Accepts a connection from a client, and starts up its own
- # thread to handle it. This thread loops, receiving requests
- # from the client, invoking them on a local object, and
- # returning responses, until the client closes the connection
- # or a local method call fails.
- def main_loop
- Thread.start(@protocol.accept) do |client|
- @grp.add Thread.current
- Thread.current['DRb'] = { 'client' => client ,
- 'server' => self }
- DRb.mutex.synchronize do
- client_uri = client.uri
- @exported_uri << client_uri unless @exported_uri.include?(client_uri)
- end
- loop do
- begin
- succ = false
- invoke_method = InvokeMethod.new(self, client)
- succ, result = invoke_method.perform
- if !succ && verbose
- p result
- result.backtrace.each do |x|
- puts x
- end
- end
- client.send_reply(succ, result) rescue nil
- ensure
- client.close unless succ
- if Thread.current['DRb']['stop_service']
- Thread.new { stop_service }
- end
- break unless succ
- end
- end
- end
- end
- end
-
- @primary_server = nil
-
- # Start a dRuby server locally.
- #
- # The new dRuby server will become the primary server, even
- # if another server is currently the primary server.
- #
- # +uri+ is the URI for the server to bind to. If nil,
- # the server will bind to random port on the default local host
- # name and use the default dRuby protocol.
- #
- # +front+ is the server's front object. This may be nil.
- #
- # +config+ is the configuration for the new server. This may
- # be nil.
- #
- # See DRbServer::new.
- def start_service(uri=nil, front=nil, config=nil)
- @primary_server = DRbServer.new(uri, front, config)
- end
- module_function :start_service
-
- # The primary local dRuby server.
- #
- # This is the server created by the #start_service call.
- attr_accessor :primary_server
- module_function :primary_server=, :primary_server
-
- # Get the 'current' server.
- #
- # In the context of execution taking place within the main
- # thread of a dRuby server (typically, as a result of a remote
- # call on the server or one of its objects), the current
- # server is that server. Otherwise, the current server is
- # the primary server.
- #
- # If the above rule fails to find a server, a DRbServerNotFound
- # error is raised.
- def current_server
- drb = Thread.current['DRb']
- server = (drb && drb['server']) ? drb['server'] : @primary_server
- raise DRbServerNotFound unless server
- return server
- end
- module_function :current_server
-
- # Stop the local dRuby server.
- #
- # This operates on the primary server. If there is no primary
- # server currently running, it is a noop.
- def stop_service
- @primary_server.stop_service if @primary_server
- @primary_server = nil
- end
- module_function :stop_service
-
- # Get the URI defining the local dRuby space.
- #
- # This is the URI of the current server. See #current_server.
- def uri
- drb = Thread.current['DRb']
- client = (drb && drb['client'])
- if client
- uri = client.uri
- return uri if uri
- end
- current_server.uri
- end
- module_function :uri
-
- # Is +uri+ the URI for the current local server?
- def here?(uri)
- current_server.here?(uri) rescue false
- # (current_server.uri rescue nil) == uri
- end
- module_function :here?
-
- # Get the configuration of the current server.
- #
- # If there is no current server, this returns the default configuration.
- # See #current_server and DRbServer::make_config.
- def config
- current_server.config
- rescue
- DRbServer.make_config
- end
- module_function :config
-
- # Get the front object of the current server.
- #
- # This raises a DRbServerNotFound error if there is no current server.
- # See #current_server.
- def front
- current_server.front
- end
- module_function :front
-
- # Convert a reference into an object using the current server.
- #
- # This raises a DRbServerNotFound error if there is no current server.
- # See #current_server.
- def to_obj(ref)
- current_server.to_obj(ref)
- end
-
- # Get a reference id for an object using the current server.
- #
- # This raises a DRbServerNotFound error if there is no current server.
- # See #current_server.
- def to_id(obj)
- current_server.to_id(obj)
- end
- module_function :to_id
- module_function :to_obj
-
- # Get the thread of the primary server.
- #
- # This returns nil if there is no primary server. See #primary_server.
- def thread
- @primary_server ? @primary_server.thread : nil
- end
- module_function :thread
-
- # Set the default id conv object.
- #
- # See DRbServer#default_id_conv.
- def install_id_conv(idconv)
- DRbServer.default_id_conv(idconv)
- end
- module_function :install_id_conv
-
- # Set the default acl.
- #
- # See DRb::DRbServer.default_acl.
- def install_acl(acl)
- DRbServer.default_acl(acl)
- end
- module_function :install_acl
-
- @mutex = Mutex.new
- def mutex
- @mutex
- end
- module_function :mutex
-
- @server = {}
- def regist_server(server)
- @server[server.uri] = server
- mutex.synchronize do
- @primary_server = server unless @primary_server
- end
- end
- module_function :regist_server
-
- def remove_server(server)
- @server.delete(server.uri)
- end
- module_function :remove_server
-
- def fetch_server(uri)
- @server[uri]
- end
- module_function :fetch_server
-end
-
-# :stopdoc:
-DRbObject = DRb::DRbObject
-DRbUndumped = DRb::DRbUndumped
-DRbIdConv = DRb::DRbIdConv
diff --git a/ruby_1_9_3/lib/drb/eq.rb b/ruby_1_9_3/lib/drb/eq.rb
deleted file mode 100644
index 6328c81202..0000000000
--- a/ruby_1_9_3/lib/drb/eq.rb
+++ /dev/null
@@ -1,14 +0,0 @@
-module DRb
- class DRbObject
- def ==(other)
- return false unless DRbObject === other
- (@ref == other.__drbref) && (@uri == other.__drburi)
- end
-
- def hash
- [@uri, @ref].hash
- end
-
- alias eql? ==
- end
-end
diff --git a/ruby_1_9_3/lib/drb/extserv.rb b/ruby_1_9_3/lib/drb/extserv.rb
deleted file mode 100644
index bb11211cd1..0000000000
--- a/ruby_1_9_3/lib/drb/extserv.rb
+++ /dev/null
@@ -1,71 +0,0 @@
-=begin
- external service
- Copyright (c) 2000,2002 Masatoshi SEKI
-=end
-
-require 'drb/drb'
-require 'monitor'
-
-module DRb
- class ExtServ
- include MonitorMixin
- include DRbUndumped
-
- def initialize(there, name, server=nil)
- super()
- @server = server || DRb::primary_server
- @name = name
- ro = DRbObject.new(nil, there)
- synchronize do
- @invoker = ro.regist(name, DRbObject.new(self, @server.uri))
- end
- end
- attr_reader :server
-
- def front
- DRbObject.new(nil, @server.uri)
- end
-
- def stop_service
- synchronize do
- @invoker.unregist(@name)
- server = @server
- @server = nil
- server.stop_service
- true
- end
- end
-
- def alive?
- @server ? @server.alive? : false
- end
- end
-end
-
-if __FILE__ == $0
- class Foo
- include DRbUndumped
-
- def initialize(str)
- @str = str
- end
-
- def hello(it)
- "#{it}: #{self}"
- end
-
- def to_s
- @str
- end
- end
-
- cmd = ARGV.shift
- case cmd
- when 'itest1', 'itest2'
- front = Foo.new(cmd)
- manager = DRb::DRbServer.new(nil, front)
- es = DRb::ExtServ.new(ARGV.shift, ARGV.shift, manager)
- es.server.thread.join
- end
-end
-
diff --git a/ruby_1_9_3/lib/drb/extservm.rb b/ruby_1_9_3/lib/drb/extservm.rb
deleted file mode 100644
index 8a7fc316af..0000000000
--- a/ruby_1_9_3/lib/drb/extservm.rb
+++ /dev/null
@@ -1,93 +0,0 @@
-=begin
- external service manager
- Copyright (c) 2000 Masatoshi SEKI
-=end
-
-require 'drb/drb'
-require 'thread'
-require 'monitor'
-
-module DRb
- class ExtServManager
- include DRbUndumped
- include MonitorMixin
-
- @@command = {}
-
- def self.command
- @@command
- end
-
- def self.command=(cmd)
- @@command = cmd
- end
-
- def initialize
- super()
- @cond = new_cond
- @servers = {}
- @waiting = []
- @queue = Queue.new
- @thread = invoke_thread
- @uri = nil
- end
- attr_accessor :uri
-
- def service(name)
- synchronize do
- while true
- server = @servers[name]
- return server if server && server.alive?
- invoke_service(name)
- @cond.wait
- end
- end
- end
-
- def regist(name, ro)
- synchronize do
- @servers[name] = ro
- @cond.signal
- end
- self
- end
-
- def unregist(name)
- synchronize do
- @servers.delete(name)
- end
- end
-
- private
- def invoke_thread
- Thread.new do
- while true
- name = @queue.pop
- invoke_service_command(name, @@command[name])
- end
- end
- end
-
- def invoke_service(name)
- @queue.push(name)
- end
-
- def invoke_service_command(name, command)
- raise "invalid command. name: #{name}" unless command
- synchronize do
- return if @servers.include?(name)
- @servers[name] = false
- end
- uri = @uri || DRb.uri
- if command.respond_to? :to_ary
- command = command.to_ary + [uri, name]
- pid = spawn(*command)
- else
- pid = spawn("#{command} #{uri} #{name}")
- end
- th = Process.detach(pid)
- th[:drb_service] = name
- th
- end
- end
-end
diff --git a/ruby_1_9_3/lib/drb/gw.rb b/ruby_1_9_3/lib/drb/gw.rb
deleted file mode 100644
index b7a5f5383f..0000000000
--- a/ruby_1_9_3/lib/drb/gw.rb
+++ /dev/null
@@ -1,122 +0,0 @@
-require 'drb/drb'
-require 'monitor'
-
-module DRb
- class GWIdConv < DRbIdConv
- def to_obj(ref)
- if Array === ref && ref[0] == :DRbObject
- return DRbObject.new_with(ref[1], ref[2])
- end
- super(ref)
- end
- end
-
- class GW
- include MonitorMixin
- def initialize
- super()
- @hash = {}
- end
-
- def [](key)
- synchronize do
- @hash[key]
- end
- end
-
- def []=(key, v)
- synchronize do
- @hash[key] = v
- end
- end
- end
-
- class DRbObject
- def self._load(s)
- uri, ref = Marshal.load(s)
- if DRb.uri == uri
- return ref ? DRb.to_obj(ref) : DRb.front
- end
-
- self.new_with(DRb.uri, [:DRbObject, uri, ref])
- end
-
- def _dump(lv)
- if DRb.uri == @uri
- if Array === @ref && @ref[0] == :DRbObject
- Marshal.dump([@ref[1], @ref[2]])
- else
- Marshal.dump([@uri, @ref]) # ??
- end
- else
- Marshal.dump([DRb.uri, [:DRbObject, @uri, @ref]])
- end
- end
- end
-end
-
-=begin
-DRb.install_id_conv(DRb::GWIdConv.new)
-
-front = DRb::GW.new
-
-s1 = DRb::DRbServer.new('drbunix:/tmp/gw_b_a', front)
-s2 = DRb::DRbServer.new('drbunix:/tmp/gw_b_c', front)
-
-s1.thread.join
-s2.thread.join
-=end
-
-=begin
-# foo.rb
-
-require 'drb/drb'
-
-class Foo
- include DRbUndumped
- def initialize(name, peer=nil)
- @name = name
- @peer = peer
- end
-
- def ping(obj)
- puts "#{@name}: ping: #{obj.inspect}"
- @peer.ping(self) if @peer
- end
-end
-=end
-
-=begin
-# gw_a.rb
-require 'drb/unix'
-require 'foo'
-
-obj = Foo.new('a')
-DRb.start_service("drbunix:/tmp/gw_a", obj)
-
-robj = DRbObject.new_with_uri('drbunix:/tmp/gw_b_a')
-robj[:a] = obj
-
-DRb.thread.join
-=end
-
-=begin
-# gw_c.rb
-require 'drb/unix'
-require 'foo'
-
-foo = Foo.new('c', nil)
-
-DRb.start_service("drbunix:/tmp/gw_c", nil)
-
-robj = DRbObject.new_with_uri("drbunix:/tmp/gw_b_c")
-
-puts "c->b"
-a = robj[:a]
-sleep 2
-
-a.ping(foo)
-
-DRb.thread.join
-=end
-
diff --git a/ruby_1_9_3/lib/drb/invokemethod.rb b/ruby_1_9_3/lib/drb/invokemethod.rb
deleted file mode 100644
index 353dbd00d8..0000000000
--- a/ruby_1_9_3/lib/drb/invokemethod.rb
+++ /dev/null
@@ -1,34 +0,0 @@
-# for ruby-1.8.0
-
-module DRb
- class DRbServer
- module InvokeMethod18Mixin
- def block_yield(x)
- if x.size == 1 && x[0].class == Array
- x[0] = DRbArray.new(x[0])
- end
- @block.call(*x)
- end
-
- def perform_with_block
- @obj.__send__(@msg_id, *@argv) do |*x|
- jump_error = nil
- begin
- block_value = block_yield(x)
- rescue LocalJumpError
- jump_error = $!
- end
- if jump_error
- case jump_error.reason
- when :break
- break(jump_error.exit_value)
- else
- raise jump_error
- end
- end
- block_value
- end
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/drb/observer.rb b/ruby_1_9_3/lib/drb/observer.rb
deleted file mode 100644
index 149426db7b..0000000000
--- a/ruby_1_9_3/lib/drb/observer.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-require 'observer'
-
-module DRb
- module DRbObservable
- include Observable
-
- def notify_observers(*arg)
- if defined? @observer_state and @observer_state
- if defined? @observer_peers
- @observer_peers.each do |observer, method|
- begin
- observer.send(method, *arg)
- rescue
- delete_observer(observer)
- end
- end
- end
- @observer_state = false
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/drb/ssl.rb b/ruby_1_9_3/lib/drb/ssl.rb
deleted file mode 100644
index 2b6a2376ef..0000000000
--- a/ruby_1_9_3/lib/drb/ssl.rb
+++ /dev/null
@@ -1,194 +0,0 @@
-require 'socket'
-require 'openssl'
-require 'drb/drb'
-require 'singleton'
-
-module DRb
-
- class DRbSSLSocket < DRbTCPSocket
-
- class SSLConfig
-
- DEFAULT = {
- :SSLCertificate => nil,
- :SSLPrivateKey => nil,
- :SSLClientCA => nil,
- :SSLCACertificatePath => nil,
- :SSLCACertificateFile => nil,
- :SSLVerifyMode => ::OpenSSL::SSL::VERIFY_NONE,
- :SSLVerifyDepth => nil,
- :SSLVerifyCallback => nil, # custom verification
- :SSLCertificateStore => nil,
- # Must specify if you use auto generated certificate.
- :SSLCertName => nil, # e.g. [["CN","fqdn.example.com"]]
- :SSLCertComment => "Generated by Ruby/OpenSSL"
- }
-
- def initialize(config)
- @config = config
- @cert = config[:SSLCertificate]
- @pkey = config[:SSLPrivateKey]
- @ssl_ctx = nil
- end
-
- def [](key);
- @config[key] || DEFAULT[key]
- end
-
- def connect(tcp)
- ssl = ::OpenSSL::SSL::SSLSocket.new(tcp, @ssl_ctx)
- ssl.sync = true
- ssl.connect
- ssl
- end
-
- def accept(tcp)
- ssl = OpenSSL::SSL::SSLSocket.new(tcp, @ssl_ctx)
- ssl.sync = true
- ssl.accept
- ssl
- end
-
- def setup_certificate
- if @cert && @pkey
- return
- end
-
- rsa = OpenSSL::PKey::RSA.new(1024){|p, n|
- next unless self[:verbose]
- case p
- when 0; $stderr.putc "." # BN_generate_prime
- when 1; $stderr.putc "+" # BN_generate_prime
- when 2; $stderr.putc "*" # searching good prime,
- # n = #of try,
- # but also data from BN_generate_prime
- when 3; $stderr.putc "\n" # found good prime, n==0 - p, n==1 - q,
- # but also data from BN_generate_prime
- else; $stderr.putc "*" # BN_generate_prime
- end
- }
-
- cert = OpenSSL::X509::Certificate.new
- cert.version = 3
- cert.serial = 0
- name = OpenSSL::X509::Name.new(self[:SSLCertName])
- cert.subject = name
- cert.issuer = name
- cert.not_before = Time.now
- cert.not_after = Time.now + (365*24*60*60)
- cert.public_key = rsa.public_key
-
- ef = OpenSSL::X509::ExtensionFactory.new(nil,cert)
- cert.extensions = [
- ef.create_extension("basicConstraints","CA:FALSE"),
- ef.create_extension("subjectKeyIdentifier", "hash") ]
- ef.issuer_certificate = cert
- cert.add_extension(ef.create_extension("authorityKeyIdentifier",
- "keyid:always,issuer:always"))
- if comment = self[:SSLCertComment]
- cert.add_extension(ef.create_extension("nsComment", comment))
- end
- cert.sign(rsa, OpenSSL::Digest::SHA1.new)
-
- @cert = cert
- @pkey = rsa
- end
-
- def setup_ssl_context
- ctx = ::OpenSSL::SSL::SSLContext.new
- ctx.cert = @cert
- ctx.key = @pkey
- ctx.client_ca = self[:SSLClientCA]
- ctx.ca_path = self[:SSLCACertificatePath]
- ctx.ca_file = self[:SSLCACertificateFile]
- ctx.verify_mode = self[:SSLVerifyMode]
- ctx.verify_depth = self[:SSLVerifyDepth]
- ctx.verify_callback = self[:SSLVerifyCallback]
- ctx.cert_store = self[:SSLCertificateStore]
- @ssl_ctx = ctx
- end
- end
-
- def self.parse_uri(uri)
- if uri =~ /^drbssl:\/\/(.*?):(\d+)(\?(.*))?$/
- host = $1
- port = $2.to_i
- option = $4
- [host, port, option]
- else
- raise(DRbBadScheme, uri) unless uri =~ /^drbssl:/
- raise(DRbBadURI, 'can\'t parse uri:' + uri)
- end
- end
-
- def self.open(uri, config)
- host, port, = parse_uri(uri)
- host.untaint
- port.untaint
- soc = TCPSocket.open(host, port)
- ssl_conf = SSLConfig::new(config)
- ssl_conf.setup_ssl_context
- ssl = ssl_conf.connect(soc)
- self.new(uri, ssl, ssl_conf, true)
- end
-
- def self.open_server(uri, config)
- uri = 'drbssl://:0' unless uri
- host, port, = parse_uri(uri)
- if host.size == 0
- host = getservername
- soc = open_server_inaddr_any(host, port)
- else
- soc = TCPServer.open(host, port)
- end
- port = soc.addr[1] if port == 0
- @uri = "drbssl://#{host}:#{port}"
-
- ssl_conf = SSLConfig.new(config)
- ssl_conf.setup_certificate
- ssl_conf.setup_ssl_context
- self.new(@uri, soc, ssl_conf, false)
- end
-
- def self.uri_option(uri, config)
- host, port, option = parse_uri(uri)
- return "drbssl://#{host}:#{port}", option
- end
-
- def initialize(uri, soc, config, is_established)
- @ssl = is_established ? soc : nil
- super(uri, soc.to_io, config)
- end
-
- def stream; @ssl; end
-
- def close
- if @ssl
- @ssl.close
- @ssl = nil
- end
- super
- end
-
- def accept
- begin
- while true
- soc = @socket.accept
- break if (@acl ? @acl.allow_socket?(soc) : true)
- soc.close
- end
- begin
- ssl = @config.accept(soc)
- ensure
- soc.close if $!
- end
- self.class.new(uri, ssl, @config, true)
- rescue OpenSSL::SSL::SSLError
- warn("#{__FILE__}:#{__LINE__}: warning: #{$!.message} (#{$!.class})") if @config[:verbose]
- retry
- end
- end
- end
-
- DRbProtocol.add_protocol(DRbSSLSocket)
-end
diff --git a/ruby_1_9_3/lib/drb/timeridconv.rb b/ruby_1_9_3/lib/drb/timeridconv.rb
deleted file mode 100644
index b460e2c987..0000000000
--- a/ruby_1_9_3/lib/drb/timeridconv.rb
+++ /dev/null
@@ -1,91 +0,0 @@
-require 'drb/drb'
-require 'monitor'
-
-module DRb
- class TimerIdConv < DRbIdConv
- class TimerHolder2
- include MonitorMixin
-
- class InvalidIndexError < RuntimeError; end
-
- def initialize(timeout=600)
- super()
- @sentinel = Object.new
- @gc = {}
- @curr = {}
- @renew = {}
- @timeout = timeout
- @keeper = keeper
- end
-
- def add(obj)
- synchronize do
- key = obj.__id__
- @curr[key] = obj
- return key
- end
- end
-
- def fetch(key, dv=@sentinel)
- synchronize do
- obj = peek(key)
- if obj == @sentinel
- return dv unless dv == @sentinel
- raise InvalidIndexError
- end
- @renew[key] = obj # KeepIt
- return obj
- end
- end
-
- def include?(key)
- synchronize do
- obj = peek(key)
- return false if obj == @sentinel
- true
- end
- end
-
- def peek(key)
- synchronize do
- return @curr.fetch(key, @renew.fetch(key, @gc.fetch(key, @sentinel)))
- end
- end
-
- private
- def alternate
- synchronize do
- @gc = @curr # GCed
- @curr = @renew
- @renew = {}
- end
- end
-
- def keeper
- Thread.new do
- loop do
- alternate
- sleep(@timeout)
- end
- end
- end
- end
-
- def initialize(timeout=600)
- @holder = TimerHolder2.new(timeout)
- end
-
- def to_obj(ref)
- return super if ref.nil?
- @holder.fetch(ref)
- rescue TimerHolder2::InvalidIndexError
- raise "invalid reference"
- end
-
- def to_id(obj)
- return @holder.add(obj)
- end
- end
-end
-
-# DRb.install_id_conv(TimerIdConv.new)
diff --git a/ruby_1_9_3/lib/drb/unix.rb b/ruby_1_9_3/lib/drb/unix.rb
deleted file mode 100644
index 6de5052451..0000000000
--- a/ruby_1_9_3/lib/drb/unix.rb
+++ /dev/null
@@ -1,108 +0,0 @@
-require 'socket'
-require 'drb/drb'
-require 'tmpdir'
-
-raise(LoadError, "UNIXServer is required") unless defined?(UNIXServer)
-
-module DRb
-
- class DRbUNIXSocket < DRbTCPSocket
- def self.parse_uri(uri)
- if /^drbunix:(.*?)(\?(.*))?$/ =~ uri
- filename = $1
- option = $3
- [filename, option]
- else
- raise(DRbBadScheme, uri) unless uri =~ /^drbunix:/
- raise(DRbBadURI, 'can\'t parse uri:' + uri)
- end
- end
-
- def self.open(uri, config)
- filename, = parse_uri(uri)
- filename.untaint
- soc = UNIXSocket.open(filename)
- self.new(uri, soc, config)
- end
-
- def self.open_server(uri, config)
- filename, = parse_uri(uri)
- if filename.size == 0
- soc = temp_server
- filename = soc.path
- uri = 'drbunix:' + soc.path
- else
- soc = UNIXServer.open(filename)
- end
- owner = config[:UNIXFileOwner]
- group = config[:UNIXFileGroup]
- if owner || group
- require 'etc'
- owner = Etc.getpwnam( owner ).uid if owner
- group = Etc.getgrnam( group ).gid if group
- File.chown owner, group, filename
- end
- mode = config[:UNIXFileMode]
- File.chmod(mode, filename) if mode
-
- self.new(uri, soc, config, true)
- end
-
- def self.uri_option(uri, config)
- filename, option = parse_uri(uri)
- return "drbunix:#{filename}", option
- end
-
- def initialize(uri, soc, config={}, server_mode = false)
- super(uri, soc, config)
- set_sockopt(@socket)
- @server_mode = server_mode
- @acl = nil
- end
-
- # import from tempfile.rb
- Max_try = 10
- private
- def self.temp_server
- tmpdir = Dir::tmpdir
- n = 0
- while true
- begin
- tmpname = sprintf('%s/druby%d.%d', tmpdir, $$, n)
- lock = tmpname + '.lock'
- unless File.exist?(tmpname) or File.exist?(lock)
- Dir.mkdir(lock)
- break
- end
- rescue
- raise "cannot generate tempfile `%s'" % tmpname if n >= Max_try
- #sleep(1)
- end
- n += 1
- end
- soc = UNIXServer.new(tmpname)
- Dir.rmdir(lock)
- soc
- end
-
- public
- def close
- return unless @socket
- path = @socket.path if @server_mode
- @socket.close
- File.unlink(path) if @server_mode
- @socket = nil
- end
-
- def accept
- s = @socket.accept
- self.class.new(nil, s, @config)
- end
-
- def set_sockopt(soc)
- soc.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) if defined? Fcntl::FD_CLOEXEC
- end
- end
-
- DRbProtocol.add_protocol(DRbUNIXSocket)
-end
diff --git a/ruby_1_9_3/lib/e2mmap.rb b/ruby_1_9_3/lib/e2mmap.rb
deleted file mode 100644
index 18a7ca003d..0000000000
--- a/ruby_1_9_3/lib/e2mmap.rb
+++ /dev/null
@@ -1,172 +0,0 @@
-#
-# e2mmap.rb - for ruby 1.1
-# $Release Version: 2.0$
-# $Revision: 1.10 $
-# by Keiju ISHITSUKA
-#
-# --
-# Usage:
-#
-# U1)
-# class Foo
-# extend Exception2MessageMapper
-# def_e2message ExistingExceptionClass, "message..."
-# def_exception :NewExceptionClass, "message..."[, superclass]
-# ...
-# end
-#
-# U2)
-# module Error
-# extend Exception2MessageMapper
-# def_e2meggage ExistingExceptionClass, "message..."
-# def_exception :NewExceptionClass, "message..."[, superclass]
-# ...
-# end
-# class Foo
-# include Error
-# ...
-# end
-#
-# foo = Foo.new
-# foo.Fail ....
-#
-# U3)
-# module Error
-# extend Exception2MessageMapper
-# def_e2message ExistingExceptionClass, "message..."
-# def_exception :NewExceptionClass, "message..."[, superclass]
-# ...
-# end
-# class Foo
-# extend Exception2MessageMapper
-# include Error
-# ...
-# end
-#
-# Foo.Fail NewExceptionClass, arg...
-# Foo.Fail ExistingExceptionClass, arg...
-#
-#
-module Exception2MessageMapper
- @RCS_ID='-$Id: e2mmap.rb,v 1.10 1999/02/17 12:33:17 keiju Exp keiju $-'
-
- E2MM = Exception2MessageMapper
-
- def E2MM.extend_object(cl)
- super
- cl.bind(self) unless cl < E2MM
- end
-
- def bind(cl)
- self.module_eval %[
- def Raise(err = nil, *rest)
- Exception2MessageMapper.Raise(self.class, err, *rest)
- end
- alias Fail Raise
-
- def self.included(mod)
- mod.extend Exception2MessageMapper
- end
- ]
- end
-
- # Fail(err, *rest)
- # err: exception
- # rest: message arguments
- #
- def Raise(err = nil, *rest)
- E2MM.Raise(self, err, *rest)
- end
- alias Fail Raise
- alias fail Raise
-
- # def_e2message(c, m)
- # c: exception
- # m: message_form
- # define exception c with message m.
- #
- def def_e2message(c, m)
- E2MM.def_e2message(self, c, m)
- end
-
- # def_exception(n, m, s)
- # n: exception_name
- # m: message_form
- # s: superclass(default: StandardError)
- # define exception named ``c'' with message m.
- #
- def def_exception(n, m, s = StandardError)
- E2MM.def_exception(self, n, m, s)
- end
-
- #
- # Private definitions.
- #
- # {[class, exp] => message, ...}
- @MessageMap = {}
-
- # E2MM.def_e2message(k, e, m)
- # k: class to define exception under.
- # e: exception
- # m: message_form
- # define exception c with message m.
- #
- def E2MM.def_e2message(k, c, m)
- E2MM.instance_eval{@MessageMap[[k, c]] = m}
- c
- end
-
- # E2MM.def_exception(k, n, m, s)
- # k: class to define exception under.
- # n: exception_name
- # m: message_form
- # s: superclass(default: StandardError)
- # define exception named ``c'' with message m.
- #
- def E2MM.def_exception(k, n, m, s = StandardError)
- n = n.id2name if n.kind_of?(Fixnum)
- e = Class.new(s)
- E2MM.instance_eval{@MessageMap[[k, e]] = m}
- k.const_set(n, e)
- end
-
- # Fail(klass, err, *rest)
- # klass: class to define exception under.
- # err: exception
- # rest: message arguments
- #
- def E2MM.Raise(klass = E2MM, err = nil, *rest)
- if form = e2mm_message(klass, err)
- b = $@.nil? ? caller(1) : $@
- #p $@
- #p __FILE__
- b.shift if b[0] =~ /^#{Regexp.quote(__FILE__)}:/
- raise err, sprintf(form, *rest), b
- else
- E2MM.Fail E2MM, ErrNotRegisteredException, err.inspect
- end
- end
- class << E2MM
- alias Fail Raise
- end
-
- def E2MM.e2mm_message(klass, exp)
- for c in klass.ancestors
- if mes = @MessageMap[[c,exp]]
- #p mes
- m = klass.instance_eval('"' + mes + '"')
- return m
- end
- end
- nil
- end
- class << self
- alias message e2mm_message
- end
-
- E2MM.def_exception(E2MM,
- :ErrNotRegisteredException,
- "not registerd exception(%s)")
-end
-
-
diff --git a/ruby_1_9_3/lib/erb.rb b/ruby_1_9_3/lib/erb.rb
deleted file mode 100644
index bb47943a86..0000000000
--- a/ruby_1_9_3/lib/erb.rb
+++ /dev/null
@@ -1,988 +0,0 @@
-# = ERB -- Ruby Templating
-#
-# Author:: Masatoshi SEKI
-# Documentation:: James Edward Gray II, Gavin Sinclair, and Simon Chiang
-#
-# See ERB for primary documentation and ERB::Util for a couple of utility
-# routines.
-#
-# Copyright (c) 1999-2000,2002,2003 Masatoshi SEKI
-#
-# You can redistribute it and/or modify it under the same terms as Ruby.
-
-#
-# = ERB -- Ruby Templating
-#
-# == Introduction
-#
-# ERB provides an easy to use but powerful templating system for Ruby. Using
-# ERB, actual Ruby code can be added to any plain text document for the
-# purposes of generating document information details and/or flow control.
-#
-# A very simple example is this:
-#
-# require 'erb'
-#
-# x = 42
-# template = ERB.new <<-EOF
-# The value of x is: <%= x %>
-# EOF
-# puts template.result(binding)
-#
-# <em>Prints:</em> The value of x is: 42
-#
-# More complex examples are given below.
-#
-#
-# == Recognized Tags
-#
-# ERB recognizes certain tags in the provided template and converts them based
-# on the rules below:
-#
-# <% Ruby code -- inline with output %>
-# <%= Ruby expression -- replace with result %>
-# <%# comment -- ignored -- useful in testing %>
-# % a line of Ruby code -- treated as <% line %> (optional -- see ERB.new)
-# %% replaced with % if first thing on a line and % processing is used
-# <%% or %%> -- replace with <% or %> respectively
-#
-# All other text is passed through ERB filtering unchanged.
-#
-#
-# == Options
-#
-# There are several settings you can change when you use ERB:
-# * the nature of the tags that are recognized;
-# * the value of <tt>$SAFE</tt> under which the template is run;
-# * the binding used to resolve local variables in the template.
-#
-# See the ERB.new and ERB#result methods for more detail.
-#
-# == Character encodings
-#
-# ERB (or ruby code generated by ERB) returns a string in the same
-# character encoding as the input string. When the input string has
-# a magic comment, however, it returns a string in the encoding specified
-# by the magic comment.
-#
-# # -*- coding: UTF-8 -*-
-# require 'erb'
-#
-# template = ERB.new <<EOF
-# <%#-*- coding: Big5 -*-%>
-# \_\_ENCODING\_\_ is <%= \_\_ENCODING\_\_ %>.
-# EOF
-# puts template.result
-#
-# <em>Prints:</em> \_\_ENCODING\_\_ is Big5.
-#
-#
-# == Examples
-#
-# === Plain Text
-#
-# ERB is useful for any generic templating situation. Note that in this example, we use the
-# convenient "% at start of line" tag, and we quote the template literally with
-# <tt>%q{...}</tt> to avoid trouble with the backslash.
-#
-# require "erb"
-#
-# # Create template.
-# template = %q{
-# From: James Edward Gray II <james@grayproductions.net>
-# To: <%= to %>
-# Subject: Addressing Needs
-#
-# <%= to[/\w+/] %>:
-#
-# Just wanted to send a quick note assuring that your needs are being
-# addressed.
-#
-# I want you to know that my team will keep working on the issues,
-# especially:
-#
-# <%# ignore numerous minor requests -- focus on priorities %>
-# % priorities.each do |priority|
-# * <%= priority %>
-# % end
-#
-# Thanks for your patience.
-#
-# James Edward Gray II
-# }.gsub(/^ /, '')
-#
-# message = ERB.new(template, 0, "%<>")
-#
-# # Set up template data.
-# to = "Community Spokesman <spokesman@ruby_community.org>"
-# priorities = [ "Run Ruby Quiz",
-# "Document Modules",
-# "Answer Questions on Ruby Talk" ]
-#
-# # Produce result.
-# email = message.result
-# puts email
-#
-# <i>Generates:</i>
-#
-# From: James Edward Gray II <james@grayproductions.net>
-# To: Community Spokesman <spokesman@ruby_community.org>
-# Subject: Addressing Needs
-#
-# Community:
-#
-# Just wanted to send a quick note assuring that your needs are being addressed.
-#
-# I want you to know that my team will keep working on the issues, especially:
-#
-# * Run Ruby Quiz
-# * Document Modules
-# * Answer Questions on Ruby Talk
-#
-# Thanks for your patience.
-#
-# James Edward Gray II
-#
-# === Ruby in HTML
-#
-# ERB is often used in <tt>.rhtml</tt> files (HTML with embedded Ruby). Notice the need in
-# this example to provide a special binding when the template is run, so that the instance
-# variables in the Product object can be resolved.
-#
-# require "erb"
-#
-# # Build template data class.
-# class Product
-# def initialize( code, name, desc, cost )
-# @code = code
-# @name = name
-# @desc = desc
-# @cost = cost
-#
-# @features = [ ]
-# end
-#
-# def add_feature( feature )
-# @features << feature
-# end
-#
-# # Support templating of member data.
-# def get_binding
-# binding
-# end
-#
-# # ...
-# end
-#
-# # Create template.
-# template = %{
-# <html>
-# <head><title>Ruby Toys -- <%= @name %></title></head>
-# <body>
-#
-# <h1><%= @name %> (<%= @code %>)</h1>
-# <p><%= @desc %></p>
-#
-# <ul>
-# <% @features.each do |f| %>
-# <li><b><%= f %></b></li>
-# <% end %>
-# </ul>
-#
-# <p>
-# <% if @cost < 10 %>
-# <b>Only <%= @cost %>!!!</b>
-# <% else %>
-# Call for a price, today!
-# <% end %>
-# </p>
-#
-# </body>
-# </html>
-# }.gsub(/^ /, '')
-#
-# rhtml = ERB.new(template)
-#
-# # Set up template data.
-# toy = Product.new( "TZ-1002",
-# "Rubysapien",
-# "Geek's Best Friend! Responds to Ruby commands...",
-# 999.95 )
-# toy.add_feature("Listens for verbal commands in the Ruby language!")
-# toy.add_feature("Ignores Perl, Java, and all C variants.")
-# toy.add_feature("Karate-Chop Action!!!")
-# toy.add_feature("Matz signature on left leg.")
-# toy.add_feature("Gem studded eyes... Rubies, of course!")
-#
-# # Produce result.
-# rhtml.run(toy.get_binding)
-#
-# <i>Generates (some blank lines removed):</i>
-#
-# <html>
-# <head><title>Ruby Toys -- Rubysapien</title></head>
-# <body>
-#
-# <h1>Rubysapien (TZ-1002)</h1>
-# <p>Geek's Best Friend! Responds to Ruby commands...</p>
-#
-# <ul>
-# <li><b>Listens for verbal commands in the Ruby language!</b></li>
-# <li><b>Ignores Perl, Java, and all C variants.</b></li>
-# <li><b>Karate-Chop Action!!!</b></li>
-# <li><b>Matz signature on left leg.</b></li>
-# <li><b>Gem studded eyes... Rubies, of course!</b></li>
-# </ul>
-#
-# <p>
-# Call for a price, today!
-# </p>
-#
-# </body>
-# </html>
-#
-#
-# == Notes
-#
-# There are a variety of templating solutions available in various Ruby projects:
-# * ERB's big brother, eRuby, works the same but is written in C for speed;
-# * Amrita (smart at producing HTML/XML);
-# * cs/Template (written in C for speed);
-# * RDoc, distributed with Ruby, uses its own template engine, which can be reused elsewhere;
-# * and others; search the RAA.
-#
-# Rails, the web application framework, uses ERB to create views.
-#
-class ERB
- Revision = '$Date:: $' #'
-
- # Returns revision information for the erb.rb module.
- def self.version
- "erb.rb [2.1.0 #{ERB::Revision.split[1]}]"
- end
-end
-
-#--
-# ERB::Compiler
-class ERB
- # = ERB::Compiler
- #
- # Compiles ERB templates into Ruby code; the compiled code produces the
- # template result when evaluated. ERB::Compiler provides hooks to define how
- # generated output is handled.
- #
- # Internally ERB does something like this to generate the code returned by
- # ERB#src:
- #
- # compiler = ERB::Compiler.new('<>')
- # compiler.pre_cmd = ["_erbout=''"]
- # compiler.put_cmd = "_erbout.concat"
- # compiler.insert_cmd = "_erbout.concat"
- # compiler.post_cmd = ["_erbout"]
- #
- # code, enc = compiler.compile("Got <%= obj %>!\n")
- # puts code
- #
- # <i>Generates</i>:
- #
- # #coding:UTF-8
- # _erbout=''; _erbout.concat "Got "; _erbout.concat(( obj ).to_s); _erbout.concat "!\n"; _erbout
- #
- # By default the output is sent to the print method. For example:
- #
- # compiler = ERB::Compiler.new('<>')
- # code, enc = compiler.compile("Got <%= obj %>!\n")
- # puts code
- #
- # <i>Generates</i>:
- #
- # #coding:UTF-8
- # print "Got "; print(( obj ).to_s); print "!\n"
- #
- # == Evaluation
- #
- # The compiled code can be used in any context where the names in the code
- # correctly resolve. Using the last example, each of these print 'Got It!'
- #
- # Evaluate using a variable:
- #
- # obj = 'It'
- # eval code
- #
- # Evaluate using an input:
- #
- # mod = Module.new
- # mod.module_eval %{
- # def get(obj)
- # #{code}
- # end
- # }
- # extend mod
- # get('It')
- #
- # Evaluate using an accessor:
- #
- # klass = Class.new Object
- # klass.class_eval %{
- # attr_accessor :obj
- # def initialize(obj)
- # @obj = obj
- # end
- # def get_it
- # #{code}
- # end
- # }
- # klass.new('It').get_it
- #
- # Good! See also ERB#def_method, ERB#def_module, and ERB#def_class.
- class Compiler # :nodoc:
- class PercentLine # :nodoc:
- def initialize(str)
- @value = str
- end
- attr_reader :value
- alias :to_s :value
-
- def empty?
- @value.empty?
- end
- end
-
- class Scanner # :nodoc:
- @scanner_map = {}
- def self.regist_scanner(klass, trim_mode, percent)
- @scanner_map[[trim_mode, percent]] = klass
- end
-
- def self.default_scanner=(klass)
- @default_scanner = klass
- end
-
- def self.make_scanner(src, trim_mode, percent)
- klass = @scanner_map.fetch([trim_mode, percent], @default_scanner)
- klass.new(src, trim_mode, percent)
- end
-
- def initialize(src, trim_mode, percent)
- @src = src
- @stag = nil
- end
- attr_accessor :stag
-
- def scan; end
- end
-
- class TrimScanner < Scanner # :nodoc:
- def initialize(src, trim_mode, percent)
- super
- @trim_mode = trim_mode
- @percent = percent
- if @trim_mode == '>'
- @scan_line = self.method(:trim_line1)
- elsif @trim_mode == '<>'
- @scan_line = self.method(:trim_line2)
- elsif @trim_mode == '-'
- @scan_line = self.method(:explicit_trim_line)
- else
- @scan_line = self.method(:scan_line)
- end
- end
- attr_accessor :stag
-
- def scan(&block)
- @stag = nil
- if @percent
- @src.each_line do |line|
- percent_line(line, &block)
- end
- else
- @scan_line.call(@src, &block)
- end
- nil
- end
-
- def percent_line(line, &block)
- if @stag || line[0] != ?%
- return @scan_line.call(line, &block)
- end
-
- line[0] = ''
- if line[0] == ?%
- @scan_line.call(line, &block)
- else
- yield(PercentLine.new(line.chomp))
- end
- end
-
- def scan_line(line)
- line.scan(/(.*?)(<%%|%%>|<%=|<%#|<%|%>|\n|\z)/m) do |tokens|
- tokens.each do |token|
- next if token.empty?
- yield(token)
- end
- end
- end
-
- def trim_line1(line)
- line.scan(/(.*?)(<%%|%%>|<%=|<%#|<%|%>\n|%>|\n|\z)/m) do |tokens|
- tokens.each do |token|
- next if token.empty?
- if token == "%>\n"
- yield('%>')
- yield(:cr)
- else
- yield(token)
- end
- end
- end
- end
-
- def trim_line2(line)
- head = nil
- line.scan(/(.*?)(<%%|%%>|<%=|<%#|<%|%>\n|%>|\n|\z)/m) do |tokens|
- tokens.each do |token|
- next if token.empty?
- head = token unless head
- if token == "%>\n"
- yield('%>')
- if is_erb_stag?(head)
- yield(:cr)
- else
- yield("\n")
- end
- head = nil
- else
- yield(token)
- head = nil if token == "\n"
- end
- end
- end
- end
-
- def explicit_trim_line(line)
- line.scan(/(.*?)(^[ \t]*<%\-|<%\-|<%%|%%>|<%=|<%#|<%|-%>\n|-%>|%>|\z)/m) do |tokens|
- tokens.each do |token|
- next if token.empty?
- if @stag.nil? && /[ \t]*<%-/ =~ token
- yield('<%')
- elsif @stag && token == "-%>\n"
- yield('%>')
- yield(:cr)
- elsif @stag && token == '-%>'
- yield('%>')
- else
- yield(token)
- end
- end
- end
- end
-
- ERB_STAG = %w(<%= <%# <%)
- def is_erb_stag?(s)
- ERB_STAG.member?(s)
- end
- end
-
- Scanner.default_scanner = TrimScanner
-
- class SimpleScanner < Scanner # :nodoc:
- def scan
- @src.scan(/(.*?)(<%%|%%>|<%=|<%#|<%|%>|\n|\z)/m) do |tokens|
- tokens.each do |token|
- next if token.empty?
- yield(token)
- end
- end
- end
- end
-
- Scanner.regist_scanner(SimpleScanner, nil, false)
-
- begin
- require 'strscan'
- class SimpleScanner2 < Scanner # :nodoc:
- def scan
- stag_reg = /(.*?)(<%%|<%=|<%#|<%|\z)/m
- etag_reg = /(.*?)(%%>|%>|\z)/m
- scanner = StringScanner.new(@src)
- while ! scanner.eos?
- scanner.scan(@stag ? etag_reg : stag_reg)
- yield(scanner[1])
- yield(scanner[2])
- end
- end
- end
- Scanner.regist_scanner(SimpleScanner2, nil, false)
-
- class ExplicitScanner < Scanner # :nodoc:
- def scan
- stag_reg = /(.*?)(^[ \t]*<%-|<%%|<%=|<%#|<%-|<%|\z)/m
- etag_reg = /(.*?)(%%>|-%>|%>|\z)/m
- scanner = StringScanner.new(@src)
- while ! scanner.eos?
- scanner.scan(@stag ? etag_reg : stag_reg)
- yield(scanner[1])
-
- elem = scanner[2]
- if /[ \t]*<%-/ =~ elem
- yield('<%')
- elsif elem == '-%>'
- yield('%>')
- yield(:cr) if scanner.scan(/(\n|\z)/)
- else
- yield(elem)
- end
- end
- end
- end
- Scanner.regist_scanner(ExplicitScanner, '-', false)
-
- rescue LoadError
- end
-
- class Buffer # :nodoc:
- def initialize(compiler, enc=nil)
- @compiler = compiler
- @line = []
- @script = enc ? "#coding:#{enc.to_s}\n" : ""
- @compiler.pre_cmd.each do |x|
- push(x)
- end
- end
- attr_reader :script
-
- def push(cmd)
- @line << cmd
- end
-
- def cr
- @script << (@line.join('; '))
- @line = []
- @script << "\n"
- end
-
- def close
- return unless @line
- @compiler.post_cmd.each do |x|
- push(x)
- end
- @script << (@line.join('; '))
- @line = nil
- end
- end
-
- def content_dump(s) # :nodoc:
- n = s.count("\n")
- if n > 0
- s.dump + "\n" * n
- else
- s.dump
- end
- end
-
- # Compiles an ERB template into Ruby code. Returns an array of the code
- # and encoding like ["code", Encoding].
- def compile(s)
- enc = s.encoding
- raise ArgumentError, "#{enc} is not ASCII compatible" if enc.dummy?
- s = s.dup.force_encoding("ASCII-8BIT") # don't use constant Enoding::ASCII_8BIT for miniruby
- enc = detect_magic_comment(s) || enc
- out = Buffer.new(self, enc)
-
- content = ''
- scanner = make_scanner(s)
- scanner.scan do |token|
- next if token.nil?
- next if token == ''
- if scanner.stag.nil?
- case token
- when PercentLine
- out.push("#{@put_cmd} #{content_dump(content)}") if content.size > 0
- content = ''
- out.push(token.to_s)
- out.cr
- when :cr
- out.cr
- when '<%', '<%=', '<%#'
- scanner.stag = token
- out.push("#{@put_cmd} #{content_dump(content)}") if content.size > 0
- content = ''
- when "\n"
- content << "\n"
- out.push("#{@put_cmd} #{content_dump(content)}")
- content = ''
- when '<%%'
- content << '<%'
- else
- content << token
- end
- else
- case token
- when '%>'
- case scanner.stag
- when '<%'
- if content[-1] == ?\n
- content.chop!
- out.push(content)
- out.cr
- else
- out.push(content)
- end
- when '<%='
- out.push("#{@insert_cmd}((#{content}).to_s)")
- when '<%#'
- # out.push("# #{content_dump(content)}")
- end
- scanner.stag = nil
- content = ''
- when '%%>'
- content << '%>'
- else
- content << token
- end
- end
- end
- out.push("#{@put_cmd} #{content_dump(content)}") if content.size > 0
- out.close
- return out.script, enc
- end
-
- def prepare_trim_mode(mode) # :nodoc:
- case mode
- when 1
- return [false, '>']
- when 2
- return [false, '<>']
- when 0
- return [false, nil]
- when String
- perc = mode.include?('%')
- if mode.include?('-')
- return [perc, '-']
- elsif mode.include?('<>')
- return [perc, '<>']
- elsif mode.include?('>')
- return [perc, '>']
- else
- [perc, nil]
- end
- else
- return [false, nil]
- end
- end
-
- def make_scanner(src) # :nodoc:
- Scanner.make_scanner(src, @trim_mode, @percent)
- end
-
- # Construct a new compiler using the trim_mode. See ERB#new for available
- # trim modes.
- def initialize(trim_mode)
- @percent, @trim_mode = prepare_trim_mode(trim_mode)
- @put_cmd = 'print'
- @insert_cmd = @put_cmd
- @pre_cmd = []
- @post_cmd = []
- end
- attr_reader :percent, :trim_mode
-
- # The command to handle text that ends with a newline
- attr_accessor :put_cmd
-
- # The command to handle text that is inserted prior to a newline
- attr_accessor :insert_cmd
-
- # An array of commands prepended to compiled code
- attr_accessor :pre_cmd
-
- # An array of commands appended to compiled code
- attr_accessor :post_cmd
-
- private
- def detect_magic_comment(s)
- if /\A<%#(.*)%>/ =~ s or (@percent and /\A%#(.*)/ =~ s)
- comment = $1
- comment = $1 if comment[/-\*-\s*(.*?)\s*-*-$/]
- if %r"coding\s*[=:]\s*([[:alnum:]\-_]+)" =~ comment
- enc = $1.sub(/-(?:mac|dos|unix)/i, '')
- enc = Encoding.find(enc)
- end
- end
- end
- end
-end
-
-#--
-# ERB
-class ERB
- #
- # Constructs a new ERB object with the template specified in _str_.
- #
- # An ERB object works by building a chunk of Ruby code that will output
- # the completed template when run. If _safe_level_ is set to a non-nil value,
- # ERB code will be run in a separate thread with <b>$SAFE</b> set to the
- # provided level.
- #
- # If _trim_mode_ is passed a String containing one or more of the following
- # modifiers, ERB will adjust its code generation as listed:
- #
- # % enables Ruby code processing for lines beginning with %
- # <> omit newline for lines starting with <% and ending in %>
- # > omit newline for lines ending in %>
- #
- # _eoutvar_ can be used to set the name of the variable ERB will build up
- # its output in. This is useful when you need to run multiple ERB
- # templates through the same binding and/or when you want to control where
- # output ends up. Pass the name of the variable to be used inside a String.
- #
- # === Example
- #
- # require "erb"
- #
- # # build data class
- # class Listings
- # PRODUCT = { :name => "Chicken Fried Steak",
- # :desc => "A well messages pattie, breaded and fried.",
- # :cost => 9.95 }
- #
- # attr_reader :product, :price
- #
- # def initialize( product = "", price = "" )
- # @product = product
- # @price = price
- # end
- #
- # def build
- # b = binding
- # # create and run templates, filling member data variables
- # ERB.new(<<-'END_PRODUCT'.gsub(/^\s+/, ""), 0, "", "@product").result b
- # <%= PRODUCT[:name] %>
- # <%= PRODUCT[:desc] %>
- # END_PRODUCT
- # ERB.new(<<-'END_PRICE'.gsub(/^\s+/, ""), 0, "", "@price").result b
- # <%= PRODUCT[:name] %> -- <%= PRODUCT[:cost] %>
- # <%= PRODUCT[:desc] %>
- # END_PRICE
- # end
- # end
- #
- # # setup template data
- # listings = Listings.new
- # listings.build
- #
- # puts listings.product + "\n" + listings.price
- #
- # _Generates_
- #
- # Chicken Fried Steak
- # A well messages pattie, breaded and fried.
- #
- # Chicken Fried Steak -- 9.95
- # A well messages pattie, breaded and fried.
- #
- def initialize(str, safe_level=nil, trim_mode=nil, eoutvar='_erbout')
- @safe_level = safe_level
- compiler = ERB::Compiler.new(trim_mode)
- set_eoutvar(compiler, eoutvar)
- @src, @enc = *compiler.compile(str)
- @filename = nil
- end
-
- # The Ruby code generated by ERB
- attr_reader :src
-
- # The optional _filename_ argument passed to Kernel#eval when the ERB code
- # is run
- attr_accessor :filename
-
- #
- # Can be used to set _eoutvar_ as described in ERB#new. It's probably easier
- # to just use the constructor though, since calling this method requires the
- # setup of an ERB _compiler_ object.
- #
- def set_eoutvar(compiler, eoutvar = '_erbout')
- compiler.put_cmd = "#{eoutvar}.concat"
- compiler.insert_cmd = "#{eoutvar}.concat"
-
- cmd = []
- cmd.push "#{eoutvar} = ''"
-
- compiler.pre_cmd = cmd
-
- cmd = []
- cmd.push("#{eoutvar}.force_encoding(__ENCODING__)")
-
- compiler.post_cmd = cmd
- end
-
- # Generate results and print them. (see ERB#result)
- def run(b=TOPLEVEL_BINDING)
- print self.result(b)
- end
-
- #
- # Executes the generated ERB code to produce a completed template, returning
- # the results of that code. (See ERB#new for details on how this process can
- # be affected by _safe_level_.)
- #
- # _b_ accepts a Binding or Proc object which is used to set the context of
- # code evaluation.
- #
- def result(b=TOPLEVEL_BINDING)
- if @safe_level
- proc {
- $SAFE = @safe_level
- eval(@src, b, (@filename || '(erb)'), 0)
- }.call
- else
- eval(@src, b, (@filename || '(erb)'), 0)
- end
- end
-
- # Define _methodname_ as instance method of _mod_ from compiled ruby source.
- #
- # example:
- # filename = 'example.rhtml' # 'arg1' and 'arg2' are used in example.rhtml
- # erb = ERB.new(File.read(filename))
- # erb.def_method(MyClass, 'render(arg1, arg2)', filename)
- # print MyClass.new.render('foo', 123)
- def def_method(mod, methodname, fname='(ERB)')
- src = self.src
- magic_comment = "#coding:#{@enc}\n"
- mod.module_eval do
- eval(magic_comment + "def #{methodname}\n" + src + "\nend\n", binding, fname, -2)
- end
- end
-
- # Create unnamed module, define _methodname_ as instance method of it, and return it.
- #
- # example:
- # filename = 'example.rhtml' # 'arg1' and 'arg2' are used in example.rhtml
- # erb = ERB.new(File.read(filename))
- # erb.filename = filename
- # MyModule = erb.def_module('render(arg1, arg2)')
- # class MyClass
- # include MyModule
- # end
- def def_module(methodname='erb')
- mod = Module.new
- def_method(mod, methodname, @filename || '(ERB)')
- mod
- end
-
- # Define unnamed class which has _methodname_ as instance method, and return it.
- #
- # example:
- # class MyClass_
- # def initialize(arg1, arg2)
- # @arg1 = arg1; @arg2 = arg2
- # end
- # end
- # filename = 'example.rhtml' # @arg1 and @arg2 are used in example.rhtml
- # erb = ERB.new(File.read(filename))
- # erb.filename = filename
- # MyClass = erb.def_class(MyClass_, 'render()')
- # print MyClass.new('foo', 123).render()
- def def_class(superklass=Object, methodname='result')
- cls = Class.new(superklass)
- def_method(cls, methodname, @filename || '(ERB)')
- cls
- end
-end
-
-#--
-# ERB::Util
-class ERB
- # A utility module for conversion routines, often handy in HTML generation.
- module Util
- public
- #
- # A utility method for escaping HTML tag characters in _s_.
- #
- # require "erb"
- # include ERB::Util
- #
- # puts html_escape("is a > 0 & a < 10?")
- #
- # _Generates_
- #
- # is a &gt; 0 &amp; a &lt; 10?
- #
- def html_escape(s)
- s.to_s.gsub(/&/, "&amp;").gsub(/\"/, "&quot;").gsub(/>/, "&gt;").gsub(/</, "&lt;")
- end
- alias h html_escape
- module_function :h
- module_function :html_escape
-
- #
- # A utility method for encoding the String _s_ as a URL.
- #
- # require "erb"
- # include ERB::Util
- #
- # puts url_encode("Programming Ruby: The Pragmatic Programmer's Guide")
- #
- # _Generates_
- #
- # Programming%20Ruby%3A%20%20The%20Pragmatic%20Programmer%27s%20Guide
- #
- def url_encode(s)
- s.to_s.dup.force_encoding("ASCII-8BIT").gsub(/[^a-zA-Z0-9_\-.]/n) {
- sprintf("%%%02X", $&.unpack("C")[0])
- }
- end
- alias u url_encode
- module_function :u
- module_function :url_encode
- end
-end
-
-#--
-# ERB::DefMethod
-class ERB
- # Utility module to define eRuby script as instance method.
- #
- # === Example
- #
- # example.rhtml:
- # <% for item in @items %>
- # <b><%= item %></b>
- # <% end %>
- #
- # example.rb:
- # require 'erb'
- # class MyClass
- # extend ERB::DefMethod
- # def_erb_method('render()', 'example.rhtml')
- # def initialize(items)
- # @items = items
- # end
- # end
- # print MyClass.new([10,20,30]).render()
- #
- # result:
- #
- # <b>10</b>
- #
- # <b>20</b>
- #
- # <b>30</b>
- #
- module DefMethod
- public
- # define _methodname_ as instance method of current module, using ERB
- # object or eRuby file
- def def_erb_method(methodname, erb_or_fname)
- if erb_or_fname.kind_of? String
- fname = erb_or_fname
- erb = ERB.new(File.read(fname))
- erb.def_method(self, methodname, fname)
- else
- erb = erb_or_fname
- erb.def_method(self, methodname, erb.filename || '(ERB)')
- end
- end
- module_function :def_erb_method
- end
-end
diff --git a/ruby_1_9_3/lib/fileutils.rb b/ruby_1_9_3/lib/fileutils.rb
deleted file mode 100644
index ee396e35cb..0000000000
--- a/ruby_1_9_3/lib/fileutils.rb
+++ /dev/null
@@ -1,1706 +0,0 @@
-#
-# = fileutils.rb
-#
-# Copyright (c) 2000-2007 Minero Aoki
-#
-# This program is free software.
-# You can distribute/modify this program under the same terms of ruby.
-#
-# == module FileUtils
-#
-# Namespace for several file utility methods for copying, moving, removing, etc.
-#
-# === Module Functions
-#
-# cd(dir, options)
-# cd(dir, options) {|dir| .... }
-# pwd()
-# mkdir(dir, options)
-# mkdir(list, options)
-# mkdir_p(dir, options)
-# mkdir_p(list, options)
-# rmdir(dir, options)
-# rmdir(list, options)
-# ln(old, new, options)
-# ln(list, destdir, options)
-# ln_s(old, new, options)
-# ln_s(list, destdir, options)
-# ln_sf(src, dest, options)
-# cp(src, dest, options)
-# cp(list, dir, options)
-# cp_r(src, dest, options)
-# cp_r(list, dir, options)
-# mv(src, dest, options)
-# mv(list, dir, options)
-# rm(list, options)
-# rm_r(list, options)
-# rm_rf(list, options)
-# install(src, dest, mode = <src's>, options)
-# chmod(mode, list, options)
-# chmod_R(mode, list, options)
-# chown(user, group, list, options)
-# chown_R(user, group, list, options)
-# touch(list, options)
-#
-# The <tt>options</tt> parameter is a hash of options, taken from the list
-# <tt>:force</tt>, <tt>:noop</tt>, <tt>:preserve</tt>, and <tt>:verbose</tt>.
-# <tt>:noop</tt> means that no changes are made. The other two are obvious.
-# Each method documents the options that it honours.
-#
-# All methods that have the concept of a "source" file or directory can take
-# either one file or a list of files in that argument. See the method
-# documentation for examples.
-#
-# There are some `low level' methods, which do not accept any option:
-#
-# copy_entry(src, dest, preserve = false, dereference = false)
-# copy_file(src, dest, preserve = false, dereference = true)
-# copy_stream(srcstream, deststream)
-# remove_entry(path, force = false)
-# remove_entry_secure(path, force = false)
-# remove_file(path, force = false)
-# compare_file(path_a, path_b)
-# compare_stream(stream_a, stream_b)
-# uptodate?(file, cmp_list)
-#
-# == module FileUtils::Verbose
-#
-# This module has all methods of FileUtils module, but it outputs messages
-# before acting. This equates to passing the <tt>:verbose</tt> flag to methods
-# in FileUtils.
-#
-# == module FileUtils::NoWrite
-#
-# This module has all methods of FileUtils module, but never changes
-# files/directories. This equates to passing the <tt>:noop</tt> flag to methods
-# in FileUtils.
-#
-# == module FileUtils::DryRun
-#
-# This module has all methods of FileUtils module, but never changes
-# files/directories. This equates to passing the <tt>:noop</tt> and
-# <tt>:verbose</tt> flags to methods in FileUtils.
-#
-
-module FileUtils
-
- def self.private_module_function(name) #:nodoc:
- module_function name
- private_class_method name
- end
-
- # This hash table holds command options.
- OPT_TABLE = {} #:nodoc: internal use only
-
- #
- # Options: (none)
- #
- # Returns the name of the current directory.
- #
- def pwd
- Dir.pwd
- end
- module_function :pwd
-
- alias getwd pwd
- module_function :getwd
-
- #
- # Options: verbose
- #
- # Changes the current directory to the directory +dir+.
- #
- # If this method is called with block, resumes to the old
- # working directory after the block execution finished.
- #
- # FileUtils.cd('/', :verbose => true) # chdir and report it
- #
- # FileUtils.cd('/') do # chdir
- # [...] # do something
- # end # return to original directory
- #
- def cd(dir, options = {}, &block) # :yield: dir
- fu_check_options options, OPT_TABLE['cd']
- fu_output_message "cd #{dir}" if options[:verbose]
- Dir.chdir(dir, &block)
- fu_output_message 'cd -' if options[:verbose] and block
- end
- module_function :cd
-
- alias chdir cd
- module_function :chdir
-
- OPT_TABLE['cd'] =
- OPT_TABLE['chdir'] = [:verbose]
-
- #
- # Options: (none)
- #
- # Returns true if +newer+ is newer than all +old_list+.
- # Non-existent files are older than any file.
- #
- # FileUtils.uptodate?('hello.o', %w(hello.c hello.h)) or \
- # system 'make hello.o'
- #
- def uptodate?(new, old_list, options = nil)
- raise ArgumentError, 'uptodate? does not accept any option' if options
-
- return false unless File.exist?(new)
- new_time = File.mtime(new)
- old_list.each do |old|
- if File.exist?(old)
- return false unless new_time > File.mtime(old)
- end
- end
- true
- end
- module_function :uptodate?
-
- #
- # Options: mode noop verbose
- #
- # Creates one or more directories.
- #
- # FileUtils.mkdir 'test'
- # FileUtils.mkdir %w( tmp data )
- # FileUtils.mkdir 'notexist', :noop => true # Does not really create.
- # FileUtils.mkdir 'tmp', :mode => 0700
- #
- def mkdir(list, options = {})
- fu_check_options options, OPT_TABLE['mkdir']
- list = fu_list(list)
- fu_output_message "mkdir #{options[:mode] ? ('-m %03o ' % options[:mode]) : ''}#{list.join ' '}" if options[:verbose]
- return if options[:noop]
-
- list.each do |dir|
- fu_mkdir dir, options[:mode]
- end
- end
- module_function :mkdir
-
- OPT_TABLE['mkdir'] = [:mode, :noop, :verbose]
-
- #
- # Options: mode noop verbose
- #
- # Creates a directory and all its parent directories.
- # For example,
- #
- # FileUtils.mkdir_p '/usr/local/lib/ruby'
- #
- # causes to make following directories, if it does not exist.
- # * /usr
- # * /usr/local
- # * /usr/local/lib
- # * /usr/local/lib/ruby
- #
- # You can pass several directories at a time in a list.
- #
- def mkdir_p(list, options = {})
- fu_check_options options, OPT_TABLE['mkdir_p']
- list = fu_list(list)
- fu_output_message "mkdir -p #{options[:mode] ? ('-m %03o ' % options[:mode]) : ''}#{list.join ' '}" if options[:verbose]
- return *list if options[:noop]
-
- list.map {|path| path.chomp(?/) }.each do |path|
- # optimize for the most common case
- begin
- fu_mkdir path, options[:mode]
- next
- rescue SystemCallError
- next if File.directory?(path)
- end
-
- stack = []
- until path == stack.last # dirname("/")=="/", dirname("C:/")=="C:/"
- stack.push path
- path = File.dirname(path)
- end
- stack.reverse_each do |dir|
- begin
- fu_mkdir dir, options[:mode]
- rescue SystemCallError
- raise unless File.directory?(dir)
- end
- end
- end
-
- return *list
- end
- module_function :mkdir_p
-
- alias mkpath mkdir_p
- alias makedirs mkdir_p
- module_function :mkpath
- module_function :makedirs
-
- OPT_TABLE['mkdir_p'] =
- OPT_TABLE['mkpath'] =
- OPT_TABLE['makedirs'] = [:mode, :noop, :verbose]
-
- def fu_mkdir(path, mode) #:nodoc:
- path = path.chomp(?/)
- if mode
- Dir.mkdir path, mode
- File.chmod mode, path
- else
- Dir.mkdir path
- end
- end
- private_module_function :fu_mkdir
-
- #
- # Options: noop, verbose
- #
- # Removes one or more directories.
- #
- # FileUtils.rmdir 'somedir'
- # FileUtils.rmdir %w(somedir anydir otherdir)
- # # Does not really remove directory; outputs message.
- # FileUtils.rmdir 'somedir', :verbose => true, :noop => true
- #
- def rmdir(list, options = {})
- fu_check_options options, OPT_TABLE['rmdir']
- list = fu_list(list)
- parents = options[:parents]
- fu_output_message "rmdir #{parents ? '-p ' : ''}#{list.join ' '}" if options[:verbose]
- return if options[:noop]
- list.each do |dir|
- begin
- Dir.rmdir(dir = dir.chomp(?/))
- if parents
- until (parent = File.dirname(dir)) == '.' or parent == dir
- Dir.rmdir(dir)
- end
- end
- rescue Errno::ENOTEMPTY, Errno::ENOENT
- end
- end
- end
- module_function :rmdir
-
- OPT_TABLE['rmdir'] = [:parents, :noop, :verbose]
-
- #
- # Options: force noop verbose
- #
- # <b><tt>ln(old, new, options = {})</tt></b>
- #
- # Creates a hard link +new+ which points to +old+.
- # If +new+ already exists and it is a directory, creates a link +new/old+.
- # If +new+ already exists and it is not a directory, raises Errno::EEXIST.
- # But if :force option is set, overwrite +new+.
- #
- # FileUtils.ln 'gcc', 'cc', :verbose => true
- # FileUtils.ln '/usr/bin/emacs21', '/usr/bin/emacs'
- #
- # <b><tt>ln(list, destdir, options = {})</tt></b>
- #
- # Creates several hard links in a directory, with each one pointing to the
- # item in +list+. If +destdir+ is not a directory, raises Errno::ENOTDIR.
- #
- # include FileUtils
- # cd '/sbin'
- # FileUtils.ln %w(cp mv mkdir), '/bin' # Now /sbin/cp and /bin/cp are linked.
- #
- def ln(src, dest, options = {})
- fu_check_options options, OPT_TABLE['ln']
- fu_output_message "ln#{options[:force] ? ' -f' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
- return if options[:noop]
- fu_each_src_dest0(src, dest) do |s,d|
- remove_file d, true if options[:force]
- File.link s, d
- end
- end
- module_function :ln
-
- alias link ln
- module_function :link
-
- OPT_TABLE['ln'] =
- OPT_TABLE['link'] = [:force, :noop, :verbose]
-
- #
- # Options: force noop verbose
- #
- # <b><tt>ln_s(old, new, options = {})</tt></b>
- #
- # Creates a symbolic link +new+ which points to +old+. If +new+ already
- # exists and it is a directory, creates a symbolic link +new/old+. If +new+
- # already exists and it is not a directory, raises Errno::EEXIST. But if
- # :force option is set, overwrite +new+.
- #
- # FileUtils.ln_s '/usr/bin/ruby', '/usr/local/bin/ruby'
- # FileUtils.ln_s 'verylongsourcefilename.c', 'c', :force => true
- #
- # <b><tt>ln_s(list, destdir, options = {})</tt></b>
- #
- # Creates several symbolic links in a directory, with each one pointing to the
- # item in +list+. If +destdir+ is not a directory, raises Errno::ENOTDIR.
- #
- # If +destdir+ is not a directory, raises Errno::ENOTDIR.
- #
- # FileUtils.ln_s Dir.glob('bin/*.rb'), '/home/aamine/bin'
- #
- def ln_s(src, dest, options = {})
- fu_check_options options, OPT_TABLE['ln_s']
- fu_output_message "ln -s#{options[:force] ? 'f' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
- return if options[:noop]
- fu_each_src_dest0(src, dest) do |s,d|
- remove_file d, true if options[:force]
- File.symlink s, d
- end
- end
- module_function :ln_s
-
- alias symlink ln_s
- module_function :symlink
-
- OPT_TABLE['ln_s'] =
- OPT_TABLE['symlink'] = [:force, :noop, :verbose]
-
- #
- # Options: noop verbose
- #
- # Same as
- # #ln_s(src, dest, :force)
- #
- def ln_sf(src, dest, options = {})
- fu_check_options options, OPT_TABLE['ln_sf']
- options = options.dup
- options[:force] = true
- ln_s src, dest, options
- end
- module_function :ln_sf
-
- OPT_TABLE['ln_sf'] = [:noop, :verbose]
-
- #
- # Options: preserve noop verbose
- #
- # Copies a file content +src+ to +dest+. If +dest+ is a directory,
- # copies +src+ to +dest/src+.
- #
- # If +src+ is a list of files, then +dest+ must be a directory.
- #
- # FileUtils.cp 'eval.c', 'eval.c.org'
- # FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6'
- # FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6', :verbose => true
- # FileUtils.cp 'symlink', 'dest' # copy content, "dest" is not a symlink
- #
- def cp(src, dest, options = {})
- fu_check_options options, OPT_TABLE['cp']
- fu_output_message "cp#{options[:preserve] ? ' -p' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
- return if options[:noop]
- fu_each_src_dest(src, dest) do |s, d|
- copy_file s, d, options[:preserve]
- end
- end
- module_function :cp
-
- alias copy cp
- module_function :copy
-
- OPT_TABLE['cp'] =
- OPT_TABLE['copy'] = [:preserve, :noop, :verbose]
-
- #
- # Options: preserve noop verbose dereference_root remove_destination
- #
- # Copies +src+ to +dest+. If +src+ is a directory, this method copies
- # all its contents recursively. If +dest+ is a directory, copies
- # +src+ to +dest/src+.
- #
- # +src+ can be a list of files.
- #
- # # Installing ruby library "mylib" under the site_ruby
- # FileUtils.rm_r site_ruby + '/mylib', :force
- # FileUtils.cp_r 'lib/', site_ruby + '/mylib'
- #
- # # Examples of copying several files to target directory.
- # FileUtils.cp_r %w(mail.rb field.rb debug/), site_ruby + '/tmail'
- # FileUtils.cp_r Dir.glob('*.rb'), '/home/aamine/lib/ruby', :noop => true, :verbose => true
- #
- # # If you want to copy all contents of a directory instead of the
- # # directory itself, c.f. src/x -> dest/x, src/y -> dest/y,
- # # use following code.
- # FileUtils.cp_r 'src/.', 'dest' # cp_r('src', 'dest') makes src/dest,
- # # but this doesn't.
- #
- def cp_r(src, dest, options = {})
- fu_check_options options, OPT_TABLE['cp_r']
- fu_output_message "cp -r#{options[:preserve] ? 'p' : ''}#{options[:remove_destination] ? ' --remove-destination' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
- return if options[:noop]
- options = options.dup
- options[:dereference_root] = true unless options.key?(:dereference_root)
- fu_each_src_dest(src, dest) do |s, d|
- copy_entry s, d, options[:preserve], options[:dereference_root], options[:remove_destination]
- end
- end
- module_function :cp_r
-
- OPT_TABLE['cp_r'] = [:preserve, :noop, :verbose,
- :dereference_root, :remove_destination]
-
- #
- # Copies a file system entry +src+ to +dest+.
- # If +src+ is a directory, this method copies its contents recursively.
- # This method preserves file types, c.f. symlink, directory...
- # (FIFO, device files and etc. are not supported yet)
- #
- # Both of +src+ and +dest+ must be a path name.
- # +src+ must exist, +dest+ must not exist.
- #
- # If +preserve+ is true, this method preserves owner, group, permissions
- # and modified time.
- #
- # If +dereference_root+ is true, this method dereference tree root.
- #
- # If +remove_destination+ is true, this method removes each destination file before copy.
- #
- def copy_entry(src, dest, preserve = false, dereference_root = false, remove_destination = false)
- Entry_.new(src, nil, dereference_root).traverse do |ent|
- destent = Entry_.new(dest, ent.rel, false)
- File.unlink destent.path if remove_destination && File.file?(destent.path)
- ent.copy destent.path
- ent.copy_metadata destent.path if preserve
- end
- end
- module_function :copy_entry
-
- #
- # Copies file contents of +src+ to +dest+.
- # Both of +src+ and +dest+ must be a path name.
- #
- def copy_file(src, dest, preserve = false, dereference = true)
- ent = Entry_.new(src, nil, dereference)
- ent.copy_file dest
- ent.copy_metadata dest if preserve
- end
- module_function :copy_file
-
- #
- # Copies stream +src+ to +dest+.
- # +src+ must respond to #read(n) and
- # +dest+ must respond to #write(str).
- #
- def copy_stream(src, dest)
- IO.copy_stream(src, dest)
- end
- module_function :copy_stream
-
- #
- # Options: force noop verbose
- #
- # Moves file(s) +src+ to +dest+. If +file+ and +dest+ exist on the different
- # disk partition, the file is copied then the original file is removed.
- #
- # FileUtils.mv 'badname.rb', 'goodname.rb'
- # FileUtils.mv 'stuff.rb', '/notexist/lib/ruby', :force => true # no error
- #
- # FileUtils.mv %w(junk.txt dust.txt), '/home/aamine/.trash/'
- # FileUtils.mv Dir.glob('test*.rb'), 'test', :noop => true, :verbose => true
- #
- def mv(src, dest, options = {})
- fu_check_options options, OPT_TABLE['mv']
- fu_output_message "mv#{options[:force] ? ' -f' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
- return if options[:noop]
- fu_each_src_dest(src, dest) do |s, d|
- destent = Entry_.new(d, nil, true)
- begin
- if destent.exist?
- if destent.directory?
- raise Errno::EEXIST, dest
- else
- destent.remove_file if rename_cannot_overwrite_file?
- end
- end
- begin
- File.rename s, d
- rescue Errno::EXDEV
- copy_entry s, d, true
- if options[:secure]
- remove_entry_secure s, options[:force]
- else
- remove_entry s, options[:force]
- end
- end
- rescue SystemCallError
- raise unless options[:force]
- end
- end
- end
- module_function :mv
-
- alias move mv
- module_function :move
-
- OPT_TABLE['mv'] =
- OPT_TABLE['move'] = [:force, :noop, :verbose, :secure]
-
- def rename_cannot_overwrite_file? #:nodoc:
- /cygwin|mswin|mingw|bccwin|emx/ =~ RUBY_PLATFORM
- end
- private_module_function :rename_cannot_overwrite_file?
-
- #
- # Options: force noop verbose
- #
- # Remove file(s) specified in +list+. This method cannot remove directories.
- # All StandardErrors are ignored when the :force option is set.
- #
- # FileUtils.rm %w( junk.txt dust.txt )
- # FileUtils.rm Dir.glob('*.so')
- # FileUtils.rm 'NotExistFile', :force => true # never raises exception
- #
- def rm(list, options = {})
- fu_check_options options, OPT_TABLE['rm']
- list = fu_list(list)
- fu_output_message "rm#{options[:force] ? ' -f' : ''} #{list.join ' '}" if options[:verbose]
- return if options[:noop]
-
- list.each do |path|
- remove_file path, options[:force]
- end
- end
- module_function :rm
-
- alias remove rm
- module_function :remove
-
- OPT_TABLE['rm'] =
- OPT_TABLE['remove'] = [:force, :noop, :verbose]
-
- #
- # Options: noop verbose
- #
- # Equivalent to
- #
- # #rm(list, :force => true)
- #
- def rm_f(list, options = {})
- fu_check_options options, OPT_TABLE['rm_f']
- options = options.dup
- options[:force] = true
- rm list, options
- end
- module_function :rm_f
-
- alias safe_unlink rm_f
- module_function :safe_unlink
-
- OPT_TABLE['rm_f'] =
- OPT_TABLE['safe_unlink'] = [:noop, :verbose]
-
- #
- # Options: force noop verbose secure
- #
- # remove files +list+[0] +list+[1]... If +list+[n] is a directory,
- # removes its all contents recursively. This method ignores
- # StandardError when :force option is set.
- #
- # FileUtils.rm_r Dir.glob('/tmp/*')
- # FileUtils.rm_r '/', :force => true # :-)
- #
- # WARNING: This method causes local vulnerability
- # if one of parent directories or removing directory tree are world
- # writable (including /tmp, whose permission is 1777), and the current
- # process has strong privilege such as Unix super user (root), and the
- # system has symbolic link. For secure removing, read the documentation
- # of #remove_entry_secure carefully, and set :secure option to true.
- # Default is :secure=>false.
- #
- # NOTE: This method calls #remove_entry_secure if :secure option is set.
- # See also #remove_entry_secure.
- #
- def rm_r(list, options = {})
- fu_check_options options, OPT_TABLE['rm_r']
- # options[:secure] = true unless options.key?(:secure)
- list = fu_list(list)
- fu_output_message "rm -r#{options[:force] ? 'f' : ''} #{list.join ' '}" if options[:verbose]
- return if options[:noop]
- list.each do |path|
- if options[:secure]
- remove_entry_secure path, options[:force]
- else
- remove_entry path, options[:force]
- end
- end
- end
- module_function :rm_r
-
- OPT_TABLE['rm_r'] = [:force, :noop, :verbose, :secure]
-
- #
- # Options: noop verbose secure
- #
- # Equivalent to
- #
- # #rm_r(list, :force => true)
- #
- # WARNING: This method causes local vulnerability.
- # Read the documentation of #rm_r first.
- #
- def rm_rf(list, options = {})
- fu_check_options options, OPT_TABLE['rm_rf']
- options = options.dup
- options[:force] = true
- rm_r list, options
- end
- module_function :rm_rf
-
- alias rmtree rm_rf
- module_function :rmtree
-
- OPT_TABLE['rm_rf'] =
- OPT_TABLE['rmtree'] = [:noop, :verbose, :secure]
-
- #
- # This method removes a file system entry +path+. +path+ shall be a
- # regular file, a directory, or something. If +path+ is a directory,
- # remove it recursively. This method is required to avoid TOCTTOU
- # (time-of-check-to-time-of-use) local security vulnerability of #rm_r.
- # #rm_r causes security hole when:
- #
- # * Parent directory is world writable (including /tmp).
- # * Removing directory tree includes world writable directory.
- # * The system has symbolic link.
- #
- # To avoid this security hole, this method applies special preprocess.
- # If +path+ is a directory, this method chown(2) and chmod(2) all
- # removing directories. This requires the current process is the
- # owner of the removing whole directory tree, or is the super user (root).
- #
- # WARNING: You must ensure that *ALL* parent directories cannot be
- # moved by other untrusted users. For example, parent directories
- # should not be owned by untrusted users, and should not be world
- # writable except when the sticky bit set.
- #
- # WARNING: Only the owner of the removing directory tree, or Unix super
- # user (root) should invoke this method. Otherwise this method does not
- # work.
- #
- # For details of this security vulnerability, see Perl's case:
- #
- # http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=CAN-2005-0448
- # http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=CAN-2004-0452
- #
- # For fileutils.rb, this vulnerability is reported in [ruby-dev:26100].
- #
- def remove_entry_secure(path, force = false)
- unless fu_have_symlink?
- remove_entry path, force
- return
- end
- fullpath = File.expand_path(path)
- st = File.lstat(fullpath)
- unless st.directory?
- File.unlink fullpath
- return
- end
- # is a directory.
- parent_st = File.stat(File.dirname(fullpath))
- unless parent_st.world_writable?
- remove_entry path, force
- return
- end
- unless parent_st.sticky?
- raise ArgumentError, "parent directory is world writable, FileUtils#remove_entry_secure does not work; abort: #{path.inspect} (parent directory mode #{'%o' % parent_st.mode})"
- end
- # freeze tree root
- euid = Process.euid
- File.open(fullpath + '/.') {|f|
- unless fu_stat_identical_entry?(st, f.stat)
- # symlink (TOC-to-TOU attack?)
- File.unlink fullpath
- return
- end
- f.chown euid, -1
- f.chmod 0700
- unless fu_stat_identical_entry?(st, File.lstat(fullpath))
- # TOC-to-TOU attack?
- File.unlink fullpath
- return
- end
- }
- # ---- tree root is frozen ----
- root = Entry_.new(path)
- root.preorder_traverse do |ent|
- if ent.directory?
- ent.chown euid, -1
- ent.chmod 0700
- end
- end
- root.postorder_traverse do |ent|
- begin
- ent.remove
- rescue
- raise unless force
- end
- end
- rescue
- raise unless force
- end
- module_function :remove_entry_secure
-
- def fu_have_symlink? #:nodoc:
- File.symlink nil, nil
- rescue NotImplementedError
- return false
- rescue
- return true
- end
- private_module_function :fu_have_symlink?
-
- def fu_stat_identical_entry?(a, b) #:nodoc:
- a.dev == b.dev and a.ino == b.ino
- end
- private_module_function :fu_stat_identical_entry?
-
- #
- # This method removes a file system entry +path+.
- # +path+ might be a regular file, a directory, or something.
- # If +path+ is a directory, remove it recursively.
- #
- # See also #remove_entry_secure.
- #
- def remove_entry(path, force = false)
- Entry_.new(path).postorder_traverse do |ent|
- begin
- ent.remove
- rescue
- raise unless force
- end
- end
- rescue
- raise unless force
- end
- module_function :remove_entry
-
- #
- # Removes a file +path+.
- # This method ignores StandardError if +force+ is true.
- #
- def remove_file(path, force = false)
- Entry_.new(path).remove_file
- rescue
- raise unless force
- end
- module_function :remove_file
-
- #
- # Removes a directory +dir+ and its contents recursively.
- # This method ignores StandardError if +force+ is true.
- #
- def remove_dir(path, force = false)
- remove_entry path, force # FIXME?? check if it is a directory
- end
- module_function :remove_dir
-
- #
- # Returns true if the contents of a file A and a file B are identical.
- #
- # FileUtils.compare_file('somefile', 'somefile') #=> true
- # FileUtils.compare_file('/bin/cp', '/bin/mv') #=> maybe false
- #
- def compare_file(a, b)
- return false unless File.size(a) == File.size(b)
- File.open(a, 'rb') {|fa|
- File.open(b, 'rb') {|fb|
- return compare_stream(fa, fb)
- }
- }
- end
- module_function :compare_file
-
- alias identical? compare_file
- alias cmp compare_file
- module_function :identical?
- module_function :cmp
-
- #
- # Returns true if the contents of a stream +a+ and +b+ are identical.
- #
- def compare_stream(a, b)
- bsize = fu_stream_blksize(a, b)
- sa = sb = nil
- while sa == sb
- sa = a.read(bsize)
- sb = b.read(bsize)
- unless sa and sb
- if sa.nil? and sb.nil?
- return true
- end
- end
- end
- false
- end
- module_function :compare_stream
-
- #
- # Options: mode preserve noop verbose
- #
- # If +src+ is not same as +dest+, copies it and changes the permission
- # mode to +mode+. If +dest+ is a directory, destination is +dest+/+src+.
- # This method removes destination before copy.
- #
- # FileUtils.install 'ruby', '/usr/local/bin/ruby', :mode => 0755, :verbose => true
- # FileUtils.install 'lib.rb', '/usr/local/lib/ruby/site_ruby', :verbose => true
- #
- def install(src, dest, options = {})
- fu_check_options options, OPT_TABLE['install']
- fu_output_message "install -c#{options[:preserve] && ' -p'}#{options[:mode] ? (' -m 0%o' % options[:mode]) : ''} #{[src,dest].flatten.join ' '}" if options[:verbose]
- return if options[:noop]
- fu_each_src_dest(src, dest) do |s, d, st|
- unless File.exist?(d) and compare_file(s, d)
- remove_file d, true
- copy_file s, d
- File.utime st.atime, st.mtime, d if options[:preserve]
- File.chmod options[:mode], d if options[:mode]
- end
- end
- end
- module_function :install
-
- OPT_TABLE['install'] = [:mode, :preserve, :noop, :verbose]
-
- def user_mask(target) #:nodoc:
- mask = 0
- target.each_byte do |byte_chr|
- case byte_chr.chr
- when "u"
- mask |= 04700
- when "g"
- mask |= 02070
- when "o"
- mask |= 01007
- when "a"
- mask |= 07777
- end
- end
- mask
- end
- private_module_function :user_mask
-
- def mode_mask(mode, path) #:nodoc:
- mask = 0
- mode.each_byte do |byte_chr|
- case byte_chr.chr
- when "r"
- mask |= 0444
- when "w"
- mask |= 0222
- when "x"
- mask |= 0111
- when "X"
- mask |= 0111 if FileTest::directory? path
- when "s"
- mask |= 06000
- when "t"
- mask |= 01000
- end
- end
- mask
- end
- private_module_function :mode_mask
-
- def symbolic_modes_to_i(modes, path) #:nodoc:
- current_mode = (File.stat(path).mode & 07777)
- modes.split(/,/).inject(0) do |mode, mode_sym|
- mode_sym = "a#{mode_sym}" if mode_sym =~ %r!^[+-=]!
- target, mode = mode_sym.split %r![+-=]!
- user_mask = user_mask(target)
- mode_mask = mode_mask(mode ? mode : "", path)
-
- case mode_sym
- when /=/
- current_mode &= ~(user_mask)
- current_mode |= user_mask & mode_mask
- when /\+/
- current_mode |= user_mask & mode_mask
- when /-/
- current_mode &= ~(user_mask & mode_mask)
- end
- end
- end
- private_module_function :symbolic_modes_to_i
-
- def fu_mode(mode, path) #:nodoc:
- mode.is_a?(String) ? symbolic_modes_to_i(mode, path) : mode
- end
- private_module_function :fu_mode
-
- #
- # Options: noop verbose
- #
- # Changes permission bits on the named files (in +list+) to the bit pattern
- # represented by +mode+.
- #
- # +mode+ is the symbolic and absolute mode can be used.
- #
- # Absolute mode is
- # FileUtils.chmod 0755, 'somecommand'
- # FileUtils.chmod 0644, %w(my.rb your.rb his.rb her.rb)
- # FileUtils.chmod 0755, '/usr/bin/ruby', :verbose => true
- #
- # Symbolic mode is
- # FileUtils.chmod "u=wrx,go=rx", 'somecommand'
- # FileUtils.chmod "u=wr,go=rr", %w(my.rb your.rb his.rb her.rb)
- # FileUtils.chmod "u=wrx,go=rx", '/usr/bin/ruby', :verbose => true
- #
- # "a" is user, group, other mask.
- # "u" is user's mask.
- # "g" is group's mask.
- # "o" is other's mask.
- # "w" is write permission.
- # "r" is read permission.
- # "x" is execute permission.
- # "s" is uid, gid.
- # "t" is sticky bit.
- # "+" is added to a class given the specified mode.
- # "-" Is removed from a given class given mode.
- # "=" Is the exact nature of the class will be given a specified mode.
-
- def chmod(mode, list, options = {})
- fu_check_options options, OPT_TABLE['chmod']
- list = fu_list(list)
- fu_output_message sprintf('chmod %o %s', mode, list.join(' ')) if options[:verbose]
- return if options[:noop]
- list.each do |path|
- Entry_.new(path).chmod(fu_mode(mode, path))
- end
- end
- module_function :chmod
-
- OPT_TABLE['chmod'] = [:noop, :verbose]
-
- #
- # Options: noop verbose force
- #
- # Changes permission bits on the named files (in +list+)
- # to the bit pattern represented by +mode+.
- #
- # FileUtils.chmod_R 0700, "/tmp/app.#{$$}"
- # FileUtils.chmod_R "u=wrx", "/tmp/app.#{$$}"
- #
- def chmod_R(mode, list, options = {})
- fu_check_options options, OPT_TABLE['chmod_R']
- list = fu_list(list)
- fu_output_message sprintf('chmod -R%s %o %s',
- (options[:force] ? 'f' : ''),
- mode, list.join(' ')) if options[:verbose]
- return if options[:noop]
- list.each do |root|
- Entry_.new(root).traverse do |ent|
- begin
- ent.chmod(fu_mode(mode, ent.path))
- rescue
- raise unless options[:force]
- end
- end
- end
- end
- module_function :chmod_R
-
- OPT_TABLE['chmod_R'] = [:noop, :verbose, :force]
-
- #
- # Options: noop verbose
- #
- # Changes owner and group on the named files (in +list+)
- # to the user +user+ and the group +group+. +user+ and +group+
- # may be an ID (Integer/String) or a name (String).
- # If +user+ or +group+ is nil, this method does not change
- # the attribute.
- #
- # FileUtils.chown 'root', 'staff', '/usr/local/bin/ruby'
- # FileUtils.chown nil, 'bin', Dir.glob('/usr/bin/*'), :verbose => true
- #
- def chown(user, group, list, options = {})
- fu_check_options options, OPT_TABLE['chown']
- list = fu_list(list)
- fu_output_message sprintf('chown %s%s',
- [user,group].compact.join(':') + ' ',
- list.join(' ')) if options[:verbose]
- return if options[:noop]
- uid = fu_get_uid(user)
- gid = fu_get_gid(group)
- list.each do |path|
- Entry_.new(path).chown uid, gid
- end
- end
- module_function :chown
-
- OPT_TABLE['chown'] = [:noop, :verbose]
-
- #
- # Options: noop verbose force
- #
- # Changes owner and group on the named files (in +list+)
- # to the user +user+ and the group +group+ recursively.
- # +user+ and +group+ may be an ID (Integer/String) or
- # a name (String). If +user+ or +group+ is nil, this
- # method does not change the attribute.
- #
- # FileUtils.chown_R 'www', 'www', '/var/www/htdocs'
- # FileUtils.chown_R 'cvs', 'cvs', '/var/cvs', :verbose => true
- #
- def chown_R(user, group, list, options = {})
- fu_check_options options, OPT_TABLE['chown_R']
- list = fu_list(list)
- fu_output_message sprintf('chown -R%s %s%s',
- (options[:force] ? 'f' : ''),
- [user,group].compact.join(':') + ' ',
- list.join(' ')) if options[:verbose]
- return if options[:noop]
- uid = fu_get_uid(user)
- gid = fu_get_gid(group)
- return unless uid or gid
- list.each do |root|
- Entry_.new(root).traverse do |ent|
- begin
- ent.chown uid, gid
- rescue
- raise unless options[:force]
- end
- end
- end
- end
- module_function :chown_R
-
- OPT_TABLE['chown_R'] = [:noop, :verbose, :force]
-
- begin
- require 'etc'
-
- def fu_get_uid(user) #:nodoc:
- return nil unless user
- case user
- when Integer
- user
- when /\A\d+\z/
- user.to_i
- else
- Etc.getpwnam(user).uid
- end
- end
- private_module_function :fu_get_uid
-
- def fu_get_gid(group) #:nodoc:
- return nil unless group
- case group
- when Integer
- group
- when /\A\d+\z/
- group.to_i
- else
- Etc.getgrnam(group).gid
- end
- end
- private_module_function :fu_get_gid
-
- rescue LoadError
- # need Win32 support???
-
- def fu_get_uid(user) #:nodoc:
- user # FIXME
- end
- private_module_function :fu_get_uid
-
- def fu_get_gid(group) #:nodoc:
- group # FIXME
- end
- private_module_function :fu_get_gid
- end
-
- #
- # Options: noop verbose
- #
- # Updates modification time (mtime) and access time (atime) of file(s) in
- # +list+. Files are created if they don't exist.
- #
- # FileUtils.touch 'timestamp'
- # FileUtils.touch Dir.glob('*.c'); system 'make'
- #
- def touch(list, options = {})
- fu_check_options options, OPT_TABLE['touch']
- list = fu_list(list)
- created = nocreate = options[:nocreate]
- t = options[:mtime]
- if options[:verbose]
- fu_output_message "touch #{nocreate ? '-c ' : ''}#{t ? t.strftime('-t %Y%m%d%H%M.%S ') : ''}#{list.join ' '}"
- end
- return if options[:noop]
- list.each do |path|
- created = nocreate
- begin
- File.utime(t, t, path)
- rescue Errno::ENOENT
- raise if created
- File.open(path, 'a') {
- ;
- }
- created = true
- retry if t
- end
- end
- end
- module_function :touch
-
- OPT_TABLE['touch'] = [:noop, :verbose, :mtime, :nocreate]
-
- private
-
- module StreamUtils_
- private
-
- def fu_windows?
- /mswin|mingw|bccwin|emx/ =~ RUBY_PLATFORM
- end
-
- def fu_copy_stream0(src, dest, blksize = nil) #:nodoc:
- IO.copy_stream(src, dest)
- end
-
- def fu_stream_blksize(*streams)
- streams.each do |s|
- next unless s.respond_to?(:stat)
- size = fu_blksize(s.stat)
- return size if size
- end
- fu_default_blksize()
- end
-
- def fu_blksize(st)
- s = st.blksize
- return nil unless s
- return nil if s == 0
- s
- end
-
- def fu_default_blksize
- 1024
- end
- end
-
- include StreamUtils_
- extend StreamUtils_
-
- class Entry_ #:nodoc: internal use only
- include StreamUtils_
-
- def initialize(a, b = nil, deref = false)
- @prefix = @rel = @path = nil
- if b
- @prefix = a
- @rel = b
- else
- @path = a
- end
- @deref = deref
- @stat = nil
- @lstat = nil
- end
-
- def inspect
- "\#<#{self.class} #{path()}>"
- end
-
- def path
- if @path
- File.path(@path)
- else
- join(@prefix, @rel)
- end
- end
-
- def prefix
- @prefix || @path
- end
-
- def rel
- @rel
- end
-
- def dereference?
- @deref
- end
-
- def exist?
- lstat! ? true : false
- end
-
- def file?
- s = lstat!
- s and s.file?
- end
-
- def directory?
- s = lstat!
- s and s.directory?
- end
-
- def symlink?
- s = lstat!
- s and s.symlink?
- end
-
- def chardev?
- s = lstat!
- s and s.chardev?
- end
-
- def blockdev?
- s = lstat!
- s and s.blockdev?
- end
-
- def socket?
- s = lstat!
- s and s.socket?
- end
-
- def pipe?
- s = lstat!
- s and s.pipe?
- end
-
- S_IF_DOOR = 0xD000
-
- def door?
- s = lstat!
- s and (s.mode & 0xF000 == S_IF_DOOR)
- end
-
- def entries
- opts = {}
- opts[:encoding] = ::Encoding::UTF_8 if fu_windows?
- Dir.entries(path(), opts)\
- .reject {|n| n == '.' or n == '..' }\
- .map {|n| Entry_.new(prefix(), join(rel(), n.untaint)) }
- end
-
- def stat
- return @stat if @stat
- if lstat() and lstat().symlink?
- @stat = File.stat(path())
- else
- @stat = lstat()
- end
- @stat
- end
-
- def stat!
- return @stat if @stat
- if lstat! and lstat!.symlink?
- @stat = File.stat(path())
- else
- @stat = lstat!
- end
- @stat
- rescue SystemCallError
- nil
- end
-
- def lstat
- if dereference?
- @lstat ||= File.stat(path())
- else
- @lstat ||= File.lstat(path())
- end
- end
-
- def lstat!
- lstat()
- rescue SystemCallError
- nil
- end
-
- def chmod(mode)
- if symlink?
- File.lchmod mode, path() if have_lchmod?
- else
- File.chmod mode, path()
- end
- end
-
- def chown(uid, gid)
- if symlink?
- File.lchown uid, gid, path() if have_lchown?
- else
- File.chown uid, gid, path()
- end
- end
-
- def copy(dest)
- case
- when file?
- copy_file dest
- when directory?
- if !File.exist?(dest) and descendant_diretory?(dest, path)
- raise ArgumentError, "cannot copy directory %s to itself %s" % [path, dest]
- end
- begin
- Dir.mkdir dest
- rescue
- raise unless File.directory?(dest)
- end
- when symlink?
- File.symlink File.readlink(path()), dest
- when chardev?
- raise "cannot handle device file" unless File.respond_to?(:mknod)
- mknod dest, ?c, 0666, lstat().rdev
- when blockdev?
- raise "cannot handle device file" unless File.respond_to?(:mknod)
- mknod dest, ?b, 0666, lstat().rdev
- when socket?
- raise "cannot handle socket" unless File.respond_to?(:mknod)
- mknod dest, nil, lstat().mode, 0
- when pipe?
- raise "cannot handle FIFO" unless File.respond_to?(:mkfifo)
- mkfifo dest, 0666
- when door?
- raise "cannot handle door: #{path()}"
- else
- raise "unknown file type: #{path()}"
- end
- end
-
- def copy_file(dest)
- File.open(path()) do |s|
- File.open(dest, 'wb', s.stat.mode) do |f|
- IO.copy_stream(s, f)
- end
- end
- end
-
- def copy_metadata(path)
- st = lstat()
- File.utime st.atime, st.mtime, path
- begin
- File.chown st.uid, st.gid, path
- rescue Errno::EPERM
- # clear setuid/setgid
- File.chmod st.mode & 01777, path
- else
- File.chmod st.mode, path
- end
- end
-
- def remove
- if directory?
- remove_dir1
- else
- remove_file
- end
- end
-
- def remove_dir1
- platform_support {
- Dir.rmdir path().chomp(?/)
- }
- end
-
- def remove_file
- platform_support {
- File.unlink path
- }
- end
-
- def platform_support
- return yield unless fu_windows?
- first_time_p = true
- begin
- yield
- rescue Errno::ENOENT
- raise
- rescue => err
- if first_time_p
- first_time_p = false
- begin
- File.chmod 0700, path() # Windows does not have symlink
- retry
- rescue SystemCallError
- end
- end
- raise err
- end
- end
-
- def preorder_traverse
- stack = [self]
- while ent = stack.pop
- yield ent
- stack.concat ent.entries.reverse if ent.directory?
- end
- end
-
- alias traverse preorder_traverse
-
- def postorder_traverse
- if directory?
- entries().each do |ent|
- ent.postorder_traverse do |e|
- yield e
- end
- end
- end
- yield self
- end
-
- private
-
- $fileutils_rb_have_lchmod = nil
-
- def have_lchmod?
- # This is not MT-safe, but it does not matter.
- if $fileutils_rb_have_lchmod == nil
- $fileutils_rb_have_lchmod = check_have_lchmod?
- end
- $fileutils_rb_have_lchmod
- end
-
- def check_have_lchmod?
- return false unless File.respond_to?(:lchmod)
- File.lchmod 0
- return true
- rescue NotImplementedError
- return false
- end
-
- $fileutils_rb_have_lchown = nil
-
- def have_lchown?
- # This is not MT-safe, but it does not matter.
- if $fileutils_rb_have_lchown == nil
- $fileutils_rb_have_lchown = check_have_lchown?
- end
- $fileutils_rb_have_lchown
- end
-
- def check_have_lchown?
- return false unless File.respond_to?(:lchown)
- File.lchown nil, nil
- return true
- rescue NotImplementedError
- return false
- end
-
- def join(dir, base)
- return File.path(dir) if not base or base == '.'
- return File.path(base) if not dir or dir == '.'
- File.join(dir, base)
- end
-
- if File::ALT_SEPARATOR
- DIRECTORY_TERM = "(?=[/#{Regexp.quote(File::ALT_SEPARATOR)}]|\\z)".freeze
- else
- DIRECTORY_TERM = "(?=/|\\z)".freeze
- end
- SYSCASE = File::FNM_SYSCASE.nonzero? ? "-i" : ""
-
- def descendant_diretory?(descendant, ascendant)
- /\A(?#{SYSCASE}:#{Regexp.quote(ascendant)})#{DIRECTORY_TERM}/ =~ File.dirname(descendant)
- end
- end # class Entry_
-
- def fu_list(arg) #:nodoc:
- [arg].flatten.map {|path| File.path(path) }
- end
- private_module_function :fu_list
-
- def fu_each_src_dest(src, dest) #:nodoc:
- fu_each_src_dest0(src, dest) do |s, d|
- raise ArgumentError, "same file: #{s} and #{d}" if fu_same?(s, d)
- yield s, d, File.stat(s)
- end
- end
- private_module_function :fu_each_src_dest
-
- def fu_each_src_dest0(src, dest) #:nodoc:
- if tmp = Array.try_convert(src)
- tmp.each do |s|
- s = File.path(s)
- yield s, File.join(dest, File.basename(s))
- end
- else
- src = File.path(src)
- if File.directory?(dest)
- yield src, File.join(dest, File.basename(src))
- else
- yield src, File.path(dest)
- end
- end
- end
- private_module_function :fu_each_src_dest0
-
- def fu_same?(a, b) #:nodoc:
- File.identical?(a, b)
- end
- private_module_function :fu_same?
-
- def fu_check_options(options, optdecl) #:nodoc:
- h = options.dup
- optdecl.each do |opt|
- h.delete opt
- end
- raise ArgumentError, "no such option: #{h.keys.join(' ')}" unless h.empty?
- end
- private_module_function :fu_check_options
-
- def fu_update_option(args, new) #:nodoc:
- if tmp = Hash.try_convert(args.last)
- args[-1] = tmp.dup.update(new)
- else
- args.push new
- end
- args
- end
- private_module_function :fu_update_option
-
- @fileutils_output = $stderr
- @fileutils_label = ''
-
- def fu_output_message(msg) #:nodoc:
- @fileutils_output ||= $stderr
- @fileutils_label ||= ''
- @fileutils_output.puts @fileutils_label + msg
- end
- private_module_function :fu_output_message
-
- #
- # Returns an Array of method names which have any options.
- #
- # p FileUtils.commands #=> ["chmod", "cp", "cp_r", "install", ...]
- #
- def FileUtils.commands
- OPT_TABLE.keys
- end
-
- #
- # Returns an Array of option names.
- #
- # p FileUtils.options #=> ["noop", "force", "verbose", "preserve", "mode"]
- #
- def FileUtils.options
- OPT_TABLE.values.flatten.uniq.map {|sym| sym.to_s }
- end
-
- #
- # Returns true if the method +mid+ have an option +opt+.
- #
- # p FileUtils.have_option?(:cp, :noop) #=> true
- # p FileUtils.have_option?(:rm, :force) #=> true
- # p FileUtils.have_option?(:rm, :perserve) #=> false
- #
- def FileUtils.have_option?(mid, opt)
- li = OPT_TABLE[mid.to_s] or raise ArgumentError, "no such method: #{mid}"
- li.include?(opt)
- end
-
- #
- # Returns an Array of option names of the method +mid+.
- #
- # p FileUtils.options(:rm) #=> ["noop", "verbose", "force"]
- #
- def FileUtils.options_of(mid)
- OPT_TABLE[mid.to_s].map {|sym| sym.to_s }
- end
-
- #
- # Returns an Array of method names which have the option +opt+.
- #
- # p FileUtils.collect_method(:preserve) #=> ["cp", "cp_r", "copy", "install"]
- #
- def FileUtils.collect_method(opt)
- OPT_TABLE.keys.select {|m| OPT_TABLE[m].include?(opt) }
- end
-
- LOW_METHODS = singleton_methods(false) - collect_method(:noop).map(&:intern)
- module LowMethods
- module_eval("private\n" + ::FileUtils::LOW_METHODS.map {|name| "def #{name}(*)end"}.join("\n"),
- __FILE__, __LINE__)
- end
-
- METHODS = singleton_methods() - [:private_module_function,
- :commands, :options, :have_option?, :options_of, :collect_method]
-
- #
- # This module has all methods of FileUtils module, but it outputs messages
- # before acting. This equates to passing the <tt>:verbose</tt> flag to
- # methods in FileUtils.
- #
- module Verbose
- include FileUtils
- @fileutils_output = $stderr
- @fileutils_label = ''
- ::FileUtils.collect_method(:verbose).each do |name|
- module_eval(<<-EOS, __FILE__, __LINE__ + 1)
- def #{name}(*args)
- super(*fu_update_option(args, :verbose => true))
- end
- private :#{name}
- EOS
- end
- extend self
- class << self
- ::FileUtils::METHODS.each do |m|
- public m
- end
- end
- end
-
- #
- # This module has all methods of FileUtils module, but never changes
- # files/directories. This equates to passing the <tt>:noop</tt> flag
- # to methods in FileUtils.
- #
- module NoWrite
- include FileUtils
- include LowMethods
- @fileutils_output = $stderr
- @fileutils_label = ''
- ::FileUtils.collect_method(:noop).each do |name|
- module_eval(<<-EOS, __FILE__, __LINE__ + 1)
- def #{name}(*args)
- super(*fu_update_option(args, :noop => true))
- end
- private :#{name}
- EOS
- end
- extend self
- class << self
- ::FileUtils::METHODS.each do |m|
- public m
- end
- end
- end
-
- #
- # This module has all methods of FileUtils module, but never changes
- # files/directories, with printing message before acting.
- # This equates to passing the <tt>:noop</tt> and <tt>:verbose</tt> flag
- # to methods in FileUtils.
- #
- module DryRun
- include FileUtils
- include LowMethods
- @fileutils_output = $stderr
- @fileutils_label = ''
- ::FileUtils.collect_method(:noop).each do |name|
- module_eval(<<-EOS, __FILE__, __LINE__ + 1)
- def #{name}(*args)
- super(*fu_update_option(args, :noop => true, :verbose => true))
- end
- private :#{name}
- EOS
- end
- extend self
- class << self
- ::FileUtils::METHODS.each do |m|
- public m
- end
- end
- end
-
-end
diff --git a/ruby_1_9_3/lib/find.rb b/ruby_1_9_3/lib/find.rb
deleted file mode 100644
index cd2d1bf38b..0000000000
--- a/ruby_1_9_3/lib/find.rb
+++ /dev/null
@@ -1,77 +0,0 @@
-#
-# find.rb: the Find module for processing all files under a given directory.
-#
-
-#
-# The +Find+ module supports the top-down traversal of a set of file paths.
-#
-# For example, to total the size of all files under your home directory,
-# ignoring anything in a "dot" directory (e.g. $HOME/.ssh):
-#
-# require 'find'
-#
-# total_size = 0
-#
-# Find.find(ENV["HOME"]) do |path|
-# if FileTest.directory?(path)
-# if File.basename(path)[0] == ?.
-# Find.prune # Don't look any further into this directory.
-# else
-# next
-# end
-# else
-# total_size += FileTest.size(path)
-# end
-# end
-#
-module Find
-
- #
- # Calls the associated block with the name of every file and directory listed
- # as arguments, then recursively on their subdirectories, and so on.
- #
- # See the +Find+ module documentation for an example.
- #
- def find(*paths) # :yield: path
- block_given? or return enum_for(__method__, *paths)
-
- paths.collect!{|d| raise Errno::ENOENT unless File.exist?(d); d.dup}
- while file = paths.shift
- catch(:prune) do
- yield file.dup.taint
- begin
- s = File.lstat(file)
- rescue Errno::ENOENT, Errno::EACCES, Errno::ENOTDIR, Errno::ELOOP, Errno::ENAMETOOLONG
- next
- end
- if s.directory? then
- begin
- fs = Dir.entries(file)
- rescue Errno::ENOENT, Errno::EACCES, Errno::ENOTDIR, Errno::ELOOP, Errno::ENAMETOOLONG
- next
- end
- fs.sort!
- fs.reverse_each {|f|
- next if f == "." or f == ".."
- f = File.join(file, f)
- paths.unshift f.untaint
- }
- end
- end
- end
- end
-
- #
- # Skips the current file or directory, restarting the loop with the next
- # entry. If the current file is a directory, that directory will not be
- # recursively entered. Meaningful only within the block associated with
- # Find::find.
- #
- # See the +Find+ module documentation for an example.
- #
- def prune
- throw :prune
- end
-
- module_function :find, :prune
-end
diff --git a/ruby_1_9_3/lib/forwardable.rb b/ruby_1_9_3/lib/forwardable.rb
deleted file mode 100644
index 2b71b904d0..0000000000
--- a/ruby_1_9_3/lib/forwardable.rb
+++ /dev/null
@@ -1,285 +0,0 @@
-#
-# forwardable.rb -
-# $Release Version: 1.1$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-# original definition by delegator.rb
-# Revised by Daniel J. Berger with suggestions from Florian Gross.
-#
-# Documentation by James Edward Gray II and Gavin Sinclair
-#
-# == Introduction
-#
-# This library allows you delegate method calls to an object, on a method by
-# method basis.
-#
-# == Notes
-#
-# Be advised, RDoc will not detect delegated methods.
-#
-# <b>forwardable.rb provides single-method delegation via the
-# def_delegator() and def_delegators() methods. For full-class
-# delegation via DelegateClass(), see delegate.rb.</b>
-#
-# == Examples
-#
-# === Forwardable
-#
-# Forwardable makes building a new class based on existing work, with a proper
-# interface, almost trivial. We want to rely on what has come before obviously,
-# but with delegation we can take just the methods we need and even rename them
-# as appropriate. In many cases this is preferable to inheritance, which gives
-# us the entire old interface, even if much of it isn't needed.
-#
-# class Queue
-# extend Forwardable
-#
-# def initialize
-# @q = [ ] # prepare delegate object
-# end
-#
-# # setup preferred interface, enq() and deq()...
-# def_delegator :@q, :push, :enq
-# def_delegator :@q, :shift, :deq
-#
-# # support some general Array methods that fit Queues well
-# def_delegators :@q, :clear, :first, :push, :shift, :size
-# end
-#
-# q = Queue.new
-# q.enq 1, 2, 3, 4, 5
-# q.push 6
-#
-# q.shift # => 1
-# while q.size > 0
-# puts q.deq
-# end
-#
-# q.enq "Ruby", "Perl", "Python"
-# puts q.first
-# q.clear
-# puts q.first
-#
-# <i>Prints:</i>
-#
-# 2
-# 3
-# 4
-# 5
-# 6
-# Ruby
-# nil
-#
-# SingleForwardable can be used to setup delegation at the object level as well.
-#
-# printer = String.new
-# printer.extend SingleForwardable # prepare object for delegation
-# printer.def_delegator "STDOUT", "puts" # add delegation for STDOUT.puts()
-# printer.puts "Howdy!"
-#
-# Also, SingleForwardable can be use to Class or Module.
-#
-# module Facade
-# extend SingleForwardable
-# def_delegator :Implementation, :service
-#
-# class Implementation
-# def service...
-# end
-# end
-#
-# If you want to use both Forwardable and SingleForwardable, you can
-# use methods def_instance_delegator and def_single_delegator, etc.
-#
-# If the object isn't a Module and Class, You can too extend
-# Forwardable module.
-# printer = String.new
-# printer.extend Forwardable # prepare object for delegation
-# printer.def_delegator "STDOUT", "puts" # add delegation for STDOUT.puts()
-# printer.puts "Howdy!"
-#
-# <i>Prints:</i>
-#
-# Howdy!
-
-#
-# The Forwardable module provides delegation of specified
-# methods to a designated object, using the methods #def_delegator
-# and #def_delegators.
-#
-# For example, say you have a class RecordCollection which
-# contains an array <tt>@records</tt>. You could provide the lookup method
-# #record_number(), which simply calls #[] on the <tt>@records</tt>
-# array, like this:
-#
-# class RecordCollection
-# extend Forwardable
-# def_delegator :@records, :[], :record_number
-# end
-#
-# Further, if you wish to provide the methods #size, #<<, and #map,
-# all of which delegate to @records, this is how you can do it:
-#
-# class RecordCollection
-# # extend Forwardable, but we did that above
-# def_delegators :@records, :size, :<<, :map
-# end
-# f = Foo.new
-# f.printf ...
-# f.gets
-# f.content_at(1)
-#
-# Also see the example at forwardable.rb.
-
-module Forwardable
- FORWARDABLE_VERSION = "1.1.0"
-
- @debug = nil
- class << self
- attr_accessor :debug
- end
-
- # Takes a hash as its argument. The key is a symbol or an array of
- # symbols. These symbols correspond to method names. The value is
- # the accessor to which the methods will be delegated.
- #
- # :call-seq:
- # delegate method => accessor
- # delegate [method, method, ...] => accessor
- #
- def instance_delegate(hash)
- hash.each{ |methods, accessor|
- methods = [methods] unless methods.respond_to?(:each)
- methods.each{ |method|
- def_instance_delegator(accessor, method)
- }
- }
- end
-
- #
- # Shortcut for defining multiple delegator methods, but with no
- # provision for using a different name. The following two code
- # samples have the same effect:
- #
- # def_delegators :@records, :size, :<<, :map
- #
- # def_delegator :@records, :size
- # def_delegator :@records, :<<
- # def_delegator :@records, :map
- #
- def def_instance_delegators(accessor, *methods)
- methods.delete("__send__")
- methods.delete("__id__")
- for method in methods
- def_instance_delegator(accessor, method)
- end
- end
-
- # Define +method+ as delegator instance method with an optional
- # alias name +ali+. Method calls to +ali+ will be delegated to
- # +accessor.method+.
- #
- # class MyQueue
- # extend Forwardable
- # attr_reader :queue
- # def initialize
- # @queue = []
- # end
- #
- # def_delegator :@queue, :push, :mypush
- # end
- #
- # q = MyQueue.new
- # q.mypush 42
- # q.queue #=> [42]
- # q.push 23 #=> NoMethodError
- #
- def def_instance_delegator(accessor, method, ali = method)
- line_no = __LINE__; str = %{
- def #{ali}(*args, &block)
- begin
- #{accessor}.__send__(:#{method}, *args, &block)
- rescue Exception
- $@.delete_if{|s| %r"#{Regexp.quote(__FILE__)}"o =~ s} unless Forwardable::debug
- ::Kernel::raise
- end
- end
- }
- # If it's not a class or module, it's an instance
- begin
- module_eval(str, __FILE__, line_no)
- rescue
- instance_eval(str, __FILE__, line_no)
- end
-
- end
-
- alias delegate instance_delegate
- alias def_delegators def_instance_delegators
- alias def_delegator def_instance_delegator
-end
-
-#
-# Usage of The SingleForwardable is like Fowadable module.
-#
-module SingleForwardable
- # Takes a hash as its argument. The key is a symbol or an array of
- # symbols. These symbols correspond to method names. The value is
- # the accessor to which the methods will be delegated.
- #
- # :call-seq:
- # delegate method => accessor
- # delegate [method, method, ...] => accessor
- #
- def single_delegate(hash)
- hash.each{ |methods, accessor|
- methods = [methods] unless methods.respond_to?(:each)
- methods.each{ |method|
- def_single_delegator(accessor, method)
- }
- }
- end
-
- #
- # Shortcut for defining multiple delegator methods, but with no
- # provision for using a different name. The following two code
- # samples have the same effect:
- #
- # def_delegators :@records, :size, :<<, :map
- #
- # def_delegator :@records, :size
- # def_delegator :@records, :<<
- # def_delegator :@records, :map
- #
- def def_single_delegators(accessor, *methods)
- methods.delete("__send__")
- methods.delete("__id__")
- for method in methods
- def_single_delegator(accessor, method)
- end
- end
-
- #
- # Defines a method _method_ which delegates to _obj_ (i.e. it calls
- # the method of the same name in _obj_). If _new_name_ is
- # provided, it is used as the name for the delegate method.
- #
- def def_single_delegator(accessor, method, ali = method)
- str = %{
- def #{ali}(*args, &block)
- begin
- #{accessor}.__send__(:#{method}, *args, &block)
- rescue Exception
- $@.delete_if{|s| %r"#{Regexp.quote(__FILE__)}"o =~ s} unless Forwardable::debug
- ::Kernel::raise
- end
- end
- }
-
- instance_eval(str, __FILE__, __LINE__)
- end
-
- alias delegate single_delegate
- alias def_delegators def_single_delegators
- alias def_delegator def_single_delegator
-end
diff --git a/ruby_1_9_3/lib/getoptlong.rb b/ruby_1_9_3/lib/getoptlong.rb
deleted file mode 100644
index 259382e8ec..0000000000
--- a/ruby_1_9_3/lib/getoptlong.rb
+++ /dev/null
@@ -1,612 +0,0 @@
-#
-# GetoptLong for Ruby
-#
-# Copyright (C) 1998, 1999, 2000 Motoyuki Kasahara.
-#
-# You may redistribute and/or modify this library under the same license
-# terms as Ruby.
-#
-# See GetoptLong for documentation.
-#
-# Additional documents and the latest version of `getoptlong.rb' can be
-# found at http://www.sra.co.jp/people/m-kasahr/ruby/getoptlong/
-
-# The GetoptLong class allows you to parse command line options similarly to
-# the GNU getopt_long() C library call. Note, however, that GetoptLong is a
-# pure Ruby implementation.
-#
-# GetoptLong allows for POSIX-style options like <tt>--file</tt> as well
-# as single letter options like <tt>-f</tt>
-#
-# The empty option <tt>--</tt> (two minus symbols) is used to end option
-# processing. This can be particularly important if options have optional
-# arguments.
-#
-# Here is a simple example of usage:
-#
-# require 'getoptlong'
-#
-# opts = GetoptLong.new(
-# [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
-# [ '--repeat', '-n', GetoptLong::REQUIRED_ARGUMENT ],
-# [ '--name', GetoptLong::OPTIONAL_ARGUMENT ]
-# )
-#
-# dir = nil
-# name = nil
-# repetitions = 1
-# opts.each do |opt, arg|
-# case opt
-# when '--help'
-# puts <<-EOF
-# hello [OPTION] ... DIR
-#
-# -h, --help:
-# show help
-#
-# --repeat x, -n x:
-# repeat x times
-#
-# --name [name]:
-# greet user by name, if name not supplied default is John
-#
-# DIR: The directory in which to issue the greeting.
-# EOF
-# when '--repeat'
-# repetitions = arg.to_i
-# when '--name'
-# if arg == ''
-# name = 'John'
-# else
-# name = arg
-# end
-# end
-# end
-#
-# if ARGV.length != 1
-# puts "Missing dir argument (try --help)"
-# exit 0
-# end
-#
-# dir = ARGV.shift
-#
-# Dir.chdir(dir)
-# for i in (1..repetitions)
-# print "Hello"
-# if name
-# print ", #{name}"
-# end
-# puts
-# end
-#
-# Example command line:
-#
-# hello -n 6 --name -- /tmp
-#
-class GetoptLong
- #
- # Orderings.
- #
- ORDERINGS = [REQUIRE_ORDER = 0, PERMUTE = 1, RETURN_IN_ORDER = 2]
-
- #
- # Argument flags.
- #
- ARGUMENT_FLAGS = [NO_ARGUMENT = 0, REQUIRED_ARGUMENT = 1,
- OPTIONAL_ARGUMENT = 2]
-
- #
- # Status codes.
- #
- STATUS_YET, STATUS_STARTED, STATUS_TERMINATED = 0, 1, 2
-
- #
- # Error types.
- #
- class Error < StandardError; end
- class AmbiguousOption < Error; end
- class NeedlessArgument < Error; end
- class MissingArgument < Error; end
- class InvalidOption < Error; end
-
- #
- # Set up option processing.
- #
- # The options to support are passed to new() as an array of arrays.
- # Each sub-array contains any number of String option names which carry
- # the same meaning, and one of the following flags:
- #
- # GetoptLong::NO_ARGUMENT :: Option does not take an argument.
- #
- # GetoptLong::REQUIRED_ARGUMENT :: Option always takes an argument.
- #
- # GetoptLong::OPTIONAL_ARGUMENT :: Option may or may not take an argument.
- #
- # The first option name is considered to be the preferred (canonical) name.
- # Other than that, the elements of each sub-array can be in any order.
- #
- def initialize(*arguments)
- #
- # Current ordering.
- #
- if ENV.include?('POSIXLY_CORRECT')
- @ordering = REQUIRE_ORDER
- else
- @ordering = PERMUTE
- end
-
- #
- # Hash table of option names.
- # Keys of the table are option names, and their values are canonical
- # names of the options.
- #
- @canonical_names = Hash.new
-
- #
- # Hash table of argument flags.
- # Keys of the table are option names, and their values are argument
- # flags of the options.
- #
- @argument_flags = Hash.new
-
- #
- # Whether error messages are output to $stderr.
- #
- @quiet = FALSE
-
- #
- # Status code.
- #
- @status = STATUS_YET
-
- #
- # Error code.
- #
- @error = nil
-
- #
- # Error message.
- #
- @error_message = nil
-
- #
- # Rest of catenated short options.
- #
- @rest_singles = ''
-
- #
- # List of non-option-arguments.
- # Append them to ARGV when option processing is terminated.
- #
- @non_option_arguments = Array.new
-
- if 0 < arguments.length
- set_options(*arguments)
- end
- end
-
- #
- # Set the handling of the ordering of options and arguments.
- # A RuntimeError is raised if option processing has already started.
- #
- # The supplied value must be a member of GetoptLong::ORDERINGS. It alters
- # the processing of options as follows:
- #
- # <b>REQUIRE_ORDER</b> :
- #
- # Options are required to occur before non-options.
- #
- # Processing of options ends as soon as a word is encountered that has not
- # been preceded by an appropriate option flag.
- #
- # For example, if -a and -b are options which do not take arguments,
- # parsing command line arguments of '-a one -b two' would result in
- # 'one', '-b', 'two' being left in ARGV, and only ('-a', '') being
- # processed as an option/arg pair.
- #
- # This is the default ordering, if the environment variable
- # POSIXLY_CORRECT is set. (This is for compatibility with GNU getopt_long.)
- #
- # <b>PERMUTE</b> :
- #
- # Options can occur anywhere in the command line parsed. This is the
- # default behavior.
- #
- # Every sequence of words which can be interpreted as an option (with or
- # without argument) is treated as an option; non-option words are skipped.
- #
- # For example, if -a does not require an argument and -b optionally takes
- # an argument, parsing '-a one -b two three' would result in ('-a','') and
- # ('-b', 'two') being processed as option/arg pairs, and 'one','three'
- # being left in ARGV.
- #
- # If the ordering is set to PERMUTE but the environment variable
- # POSIXLY_CORRECT is set, REQUIRE_ORDER is used instead. This is for
- # compatibility with GNU getopt_long.
- #
- # <b>RETURN_IN_ORDER</b> :
- #
- # All words on the command line are processed as options. Words not
- # preceded by a short or long option flag are passed as arguments
- # with an option of '' (empty string).
- #
- # For example, if -a requires an argument but -b does not, a command line
- # of '-a one -b two three' would result in option/arg pairs of ('-a', 'one')
- # ('-b', ''), ('', 'two'), ('', 'three') being processed.
- #
- def ordering=(ordering)
- #
- # The method is failed if option processing has already started.
- #
- if @status != STATUS_YET
- set_error(ArgumentError, "argument error")
- raise RuntimeError,
- "invoke ordering=, but option processing has already started"
- end
-
- #
- # Check ordering.
- #
- if !ORDERINGS.include?(ordering)
- raise ArgumentError, "invalid ordering `#{ordering}'"
- end
- if ordering == PERMUTE && ENV.include?('POSIXLY_CORRECT')
- @ordering = REQUIRE_ORDER
- else
- @ordering = ordering
- end
- end
-
- #
- # Return ordering.
- #
- attr_reader :ordering
-
- #
- # Set options. Takes the same argument as GetoptLong.new.
- #
- # Raises a RuntimeError if option processing has already started.
- #
- def set_options(*arguments)
- #
- # The method is failed if option processing has already started.
- #
- if @status != STATUS_YET
- raise RuntimeError,
- "invoke set_options, but option processing has already started"
- end
-
- #
- # Clear tables of option names and argument flags.
- #
- @canonical_names.clear
- @argument_flags.clear
-
- arguments.each do |arg|
- if !arg.is_a?(Array)
- raise ArgumentError, "the option list contains non-Array argument"
- end
-
- #
- # Find an argument flag and it set to `argument_flag'.
- #
- argument_flag = nil
- arg.each do |i|
- if ARGUMENT_FLAGS.include?(i)
- if argument_flag != nil
- raise ArgumentError, "too many argument-flags"
- end
- argument_flag = i
- end
- end
-
- raise ArgumentError, "no argument-flag" if argument_flag == nil
-
- canonical_name = nil
- arg.each do |i|
- #
- # Check an option name.
- #
- next if i == argument_flag
- begin
- if !i.is_a?(String) || i !~ /^-([^-]|-.+)$/
- raise ArgumentError, "an invalid option `#{i}'"
- end
- if (@canonical_names.include?(i))
- raise ArgumentError, "option redefined `#{i}'"
- end
- rescue
- @canonical_names.clear
- @argument_flags.clear
- raise
- end
-
- #
- # Register the option (`i') to the `@canonical_names' and
- # `@canonical_names' Hashes.
- #
- if canonical_name == nil
- canonical_name = i
- end
- @canonical_names[i] = canonical_name
- @argument_flags[i] = argument_flag
- end
- raise ArgumentError, "no option name" if canonical_name == nil
- end
- return self
- end
-
- #
- # Set/Unset `quiet' mode.
- #
- attr_writer :quiet
-
- #
- # Return the flag of `quiet' mode.
- #
- attr_reader :quiet
-
- #
- # `quiet?' is an alias of `quiet'.
- #
- alias quiet? quiet
-
- #
- # Explicitly terminate option processing.
- #
- def terminate
- return nil if @status == STATUS_TERMINATED
- raise RuntimeError, "an error has occured" if @error != nil
-
- @status = STATUS_TERMINATED
- @non_option_arguments.reverse_each do |argument|
- ARGV.unshift(argument)
- end
-
- @canonical_names = nil
- @argument_flags = nil
- @rest_singles = nil
- @non_option_arguments = nil
-
- return self
- end
-
- #
- # Returns true if option processing has terminated, false otherwise.
- #
- def terminated?
- return @status == STATUS_TERMINATED
- end
-
- #
- # Set an error (a protected method).
- #
- def set_error(type, message)
- $stderr.print("#{$0}: #{message}\n") if !@quiet
-
- @error = type
- @error_message = message
- @canonical_names = nil
- @argument_flags = nil
- @rest_singles = nil
- @non_option_arguments = nil
-
- raise type, message
- end
- protected :set_error
-
- #
- # Examine whether an option processing is failed.
- #
- attr_reader :error
-
- #
- # `error?' is an alias of `error'.
- #
- alias error? error
-
- # Return the appropriate error message in POSIX-defined format.
- # If no error has occurred, returns nil.
- #
- def error_message
- return @error_message
- end
-
- #
- # Get next option name and its argument, as an Array of two elements.
- #
- # The option name is always converted to the first (preferred)
- # name given in the original options to GetoptLong.new.
- #
- # Example: ['--option', 'value']
- #
- # Returns nil if the processing is complete (as determined by
- # STATUS_TERMINATED).
- #
- def get
- option_name, option_argument = nil, ''
-
- #
- # Check status.
- #
- return nil if @error != nil
- case @status
- when STATUS_YET
- @status = STATUS_STARTED
- when STATUS_TERMINATED
- return nil
- end
-
- #
- # Get next option argument.
- #
- if 0 < @rest_singles.length
- argument = '-' + @rest_singles
- elsif (ARGV.length == 0)
- terminate
- return nil
- elsif @ordering == PERMUTE
- while 0 < ARGV.length && ARGV[0] !~ /^-./
- @non_option_arguments.push(ARGV.shift)
- end
- if ARGV.length == 0
- terminate
- return nil
- end
- argument = ARGV.shift
- elsif @ordering == REQUIRE_ORDER
- if (ARGV[0] !~ /^-./)
- terminate
- return nil
- end
- argument = ARGV.shift
- else
- argument = ARGV.shift
- end
-
- #
- # Check the special argument `--'.
- # `--' indicates the end of the option list.
- #
- if argument == '--' && @rest_singles.length == 0
- terminate
- return nil
- end
-
- #
- # Check for long and short options.
- #
- if argument =~ /^(--[^=]+)/ && @rest_singles.length == 0
- #
- # This is a long style option, which start with `--'.
- #
- pattern = $1
- if @canonical_names.include?(pattern)
- option_name = pattern
- else
- #
- # The option `option_name' is not registered in `@canonical_names'.
- # It may be an abbreviated.
- #
- matches = []
- @canonical_names.each_key do |key|
- if key.index(pattern) == 0
- option_name = key
- matches << key
- end
- end
- if 2 <= matches.length
- set_error(AmbiguousOption, "option `#{argument}' is ambiguous between #{matches.join(', ')}")
- elsif matches.length == 0
- set_error(InvalidOption, "unrecognized option `#{argument}'")
- end
- end
-
- #
- # Check an argument to the option.
- #
- if @argument_flags[option_name] == REQUIRED_ARGUMENT
- if argument =~ /=(.*)$/
- option_argument = $1
- elsif 0 < ARGV.length
- option_argument = ARGV.shift
- else
- set_error(MissingArgument,
- "option `#{argument}' requires an argument")
- end
- elsif @argument_flags[option_name] == OPTIONAL_ARGUMENT
- if argument =~ /=(.*)$/
- option_argument = $1
- elsif 0 < ARGV.length && ARGV[0] !~ /^-./
- option_argument = ARGV.shift
- else
- option_argument = ''
- end
- elsif argument =~ /=(.*)$/
- set_error(NeedlessArgument,
- "option `#{option_name}' doesn't allow an argument")
- end
-
- elsif argument =~ /^(-(.))(.*)/
- #
- # This is a short style option, which start with `-' (not `--').
- # Short options may be catenated (e.g. `-l -g' is equivalent to
- # `-lg').
- #
- option_name, ch, @rest_singles = $1, $2, $3
-
- if @canonical_names.include?(option_name)
- #
- # The option `option_name' is found in `@canonical_names'.
- # Check its argument.
- #
- if @argument_flags[option_name] == REQUIRED_ARGUMENT
- if 0 < @rest_singles.length
- option_argument = @rest_singles
- @rest_singles = ''
- elsif 0 < ARGV.length
- option_argument = ARGV.shift
- else
- # 1003.2 specifies the format of this message.
- set_error(MissingArgument, "option requires an argument -- #{ch}")
- end
- elsif @argument_flags[option_name] == OPTIONAL_ARGUMENT
- if 0 < @rest_singles.length
- option_argument = @rest_singles
- @rest_singles = ''
- elsif 0 < ARGV.length && ARGV[0] !~ /^-./
- option_argument = ARGV.shift
- else
- option_argument = ''
- end
- end
- else
- #
- # This is an invalid option.
- # 1003.2 specifies the format of this message.
- #
- if ENV.include?('POSIXLY_CORRECT')
- set_error(InvalidOption, "invalid option -- #{ch}")
- else
- set_error(InvalidOption, "invalid option -- #{ch}")
- end
- end
- else
- #
- # This is a non-option argument.
- # Only RETURN_IN_ORDER falled into here.
- #
- return '', argument
- end
-
- return @canonical_names[option_name], option_argument
- end
-
- #
- # `get_option' is an alias of `get'.
- #
- alias get_option get
-
- # Iterator version of `get'.
- #
- # The block is called repeatedly with two arguments:
- # The first is the option name.
- # The second is the argument which followed it (if any).
- # Example: ('--opt', 'value')
- #
- # The option name is always converted to the first (preferred)
- # name given in the original options to GetoptLong.new.
- #
- def each
- loop do
- option_name, option_argument = get_option
- break if option_name == nil
- yield option_name, option_argument
- end
- end
-
- #
- # `each_option' is an alias of `each'.
- #
- alias each_option each
-end
diff --git a/ruby_1_9_3/lib/gserver.rb b/ruby_1_9_3/lib/gserver.rb
deleted file mode 100644
index f6f37d3a89..0000000000
--- a/ruby_1_9_3/lib/gserver.rb
+++ /dev/null
@@ -1,309 +0,0 @@
-#
-# Copyright (C) 2001 John W. Small All Rights Reserved
-#
-# Author:: John W. Small
-# Documentation:: Gavin Sinclair
-# Licence:: Freeware.
-
-require "socket"
-require "thread"
-
-#
-# GServer implements a generic server, featuring thread pool management,
-# simple logging, and multi-server management. See HttpServer in
-# <tt>xmlrpc/httpserver.rb</tt> in the Ruby standard library for an example of
-# GServer in action.
-#
-# Any kind of application-level server can be implemented using this class.
-# It accepts multiple simultaneous connections from clients, up to an optional
-# maximum number. Several _services_ (i.e. one service per TCP port) can be
-# run simultaneously, and stopped at any time through the class method
-# <tt>GServer.stop(port)</tt>. All the threading issues are handled, saving
-# you the effort. All events are optionally logged, but you can provide your
-# own event handlers if you wish.
-#
-# == Example
-#
-# Using GServer is simple. Below we implement a simple time server, run it,
-# query it, and shut it down. Try this code in +irb+:
-#
-# require 'gserver'
-#
-# #
-# # A server that returns the time in seconds since 1970.
-# #
-# class TimeServer < GServer
-# def initialize(port=10001, *args)
-# super(port, *args)
-# end
-# def serve(io)
-# io.puts(Time.now.to_s)
-# end
-# end
-#
-# # Run the server with logging enabled (it's a separate thread).
-# server = TimeServer.new
-# server.audit = true # Turn logging on.
-# server.start
-#
-# # *** Now point your browser to http://localhost:10001 to see it working ***
-#
-# # See if it's still running.
-# GServer.in_service?(10001) # -> true
-# server.stopped? # -> false
-#
-# # Shut the server down gracefully.
-# server.shutdown
-#
-# # Alternatively, stop it immediately.
-# GServer.stop(10001)
-# # or, of course, "server.stop".
-#
-# All the business of accepting connections and exception handling is taken
-# care of. All we have to do is implement the method that actually serves the
-# client.
-#
-# === Advanced
-#
-# As the example above shows, the way to use GServer is to subclass it to
-# create a specific server, overriding the +serve+ method. You can override
-# other methods as well if you wish, perhaps to collect statistics, or emit
-# more detailed logging.
-#
-# * #connecting
-# * #disconnecting
-# * #starting
-# * #stopping
-#
-# The above methods are only called if auditing is enabled, via #audit=.
-#
-# You can also override #log and #error if, for example, you wish to use a
-# more sophisticated logging system.
-#
-class GServer
-
- DEFAULT_HOST = "127.0.0.1"
-
- def serve(io)
- end
-
- @@services = {} # Hash of opened ports, i.e. services
- @@servicesMutex = Mutex.new
-
- # Stop the server running on the given port, bound to the given host
- #
- # +port+:: port, as a FixNum, of the server to stop
- # +host+:: host on which to find the server to stop
- def GServer.stop(port, host = DEFAULT_HOST)
- @@servicesMutex.synchronize {
- @@services[host][port].stop
- }
- end
-
- # Check if a server is running on the given port and host
- #
- # +port+:: port, as a FixNum, of the server to check
- # +host+:: host on which to find the server to check
- #
- # Returns true if a server is running on that port and host.
- def GServer.in_service?(port, host = DEFAULT_HOST)
- @@services.has_key?(host) and
- @@services[host].has_key?(port)
- end
-
- # Stop the server
- def stop
- @connectionsMutex.synchronize {
- if @tcpServerThread
- @tcpServerThread.raise "stop"
- end
- }
- end
-
- # Returns true if the server has stopped.
- def stopped?
- @tcpServerThread == nil
- end
-
- # Schedule a shutdown for the server
- def shutdown
- @shutdown = true
- end
-
- # Return the current number of connected clients
- def connections
- @connections.size
- end
-
- # Join with the server thread
- def join
- @tcpServerThread.join if @tcpServerThread
- end
-
- # Port on which to listen, as a FixNum
- attr_reader :port
- # Host on which to bind, as a String
- attr_reader :host
- # Maximum number of connections to accept at at ime, as a FixNum
- attr_reader :maxConnections
- # IO Device on which log messages should be written
- attr_accessor :stdlog
- # Set to true to cause the callbacks #connecting, #disconnecting, #starting,
- # and #stopping to be called during the server's lifecycle
- attr_accessor :audit
- # Set to true to show more detailed logging
- attr_accessor :debug
-
- # Called when a client connects, if auditing is enabled.
- #
- # +client+:: a TCPSocket instances representing the client that connected
- #
- # Return true to allow this client to connect, false to prevent it.
- def connecting(client)
- addr = client.peeraddr
- log("#{self.class.to_s} #{@host}:#{@port} client:#{addr[1]} " +
- "#{addr[2]}<#{addr[3]}> connect")
- true
- end
-
-
- # Called when a client disconnects, if audition is enabled.
- #
- # +clientPort+:: the port of the client that is connecting
- def disconnecting(clientPort)
- log("#{self.class.to_s} #{@host}:#{@port} " +
- "client:#{clientPort} disconnect")
- end
-
- protected :connecting, :disconnecting
-
- # Called when the server is starting up, if auditing is enabled.
- def starting()
- log("#{self.class.to_s} #{@host}:#{@port} start")
- end
-
- # Called when the server is shutting down, if auditing is enabled.
- def stopping()
- log("#{self.class.to_s} #{@host}:#{@port} stop")
- end
-
- protected :starting, :stopping
-
- # Called if #debug is true whenever an unhandled exception is raised.
- # This implementation simply logs the backtrace.
- #
- # +detail+:: The Exception that was caught
- def error(detail)
- log(detail.backtrace.join("\n"))
- end
-
- # Log a message to #stdlog, if it's defined. This implementation
- # outputs the timestamp and message to the log.
- #
- # +msg+:: the message to log
- def log(msg)
- if @stdlog
- @stdlog.puts("[#{Time.new.ctime}] %s" % msg)
- @stdlog.flush
- end
- end
-
- protected :error, :log
-
- # Create a new server
- #
- # +port+:: the port, as a FixNum, on which to listen.
- # +host+:: the host to bind to
- # +maxConnections+:: The maximum number of simultaneous connections to
- # accept
- # +stdlog+:: IO device on which to log messages
- # +audit+:: if true, lifecycle callbacks will be called. See #audit
- # +debug+:: if true, error messages are logged. See #debug
- def initialize(port, host = DEFAULT_HOST, maxConnections = 4,
- stdlog = $stderr, audit = false, debug = false)
- @tcpServerThread = nil
- @port = port
- @host = host
- @maxConnections = maxConnections
- @connections = []
- @connectionsMutex = Mutex.new
- @connectionsCV = ConditionVariable.new
- @stdlog = stdlog
- @audit = audit
- @debug = debug
- end
-
- # Start the server if it isn't already running
- #
- # +maxConnections+::
- # override +maxConnections+ given to the constructor. A negative
- # value indicates that the value from the constructor should be used.
- def start(maxConnections = -1)
- raise "server is already running" if !stopped?
- @shutdown = false
- @maxConnections = maxConnections if maxConnections > 0
- @@servicesMutex.synchronize {
- if GServer.in_service?(@port,@host)
- raise "Port already in use: #{host}:#{@port}!"
- end
- @tcpServer = TCPServer.new(@host,@port)
- @port = @tcpServer.addr[1]
- @@services[@host] = {} unless @@services.has_key?(@host)
- @@services[@host][@port] = self;
- }
- @tcpServerThread = Thread.new {
- begin
- starting if @audit
- while !@shutdown
- @connectionsMutex.synchronize {
- while @connections.size >= @maxConnections
- @connectionsCV.wait(@connectionsMutex)
- end
- }
- client = @tcpServer.accept
- @connections << Thread.new(client) { |myClient|
- begin
- myPort = myClient.peeraddr[1]
- serve(myClient) if !@audit or connecting(myClient)
- rescue => detail
- error(detail) if @debug
- ensure
- begin
- myClient.close
- rescue
- end
- @connectionsMutex.synchronize {
- @connections.delete(Thread.current)
- @connectionsCV.signal
- }
- disconnecting(myPort) if @audit
- end
- }
- end
- rescue => detail
- error(detail) if @debug
- ensure
- begin
- @tcpServer.close
- rescue
- end
- if @shutdown
- @connectionsMutex.synchronize {
- while @connections.size > 0
- @connectionsCV.wait(@connectionsMutex)
- end
- }
- else
- @connections.each { |c| c.raise "stop" }
- end
- @tcpServerThread = nil
- @@servicesMutex.synchronize {
- @@services[@host].delete(@port)
- }
- stopping if @audit
- end
- }
- self
- end
-
-end
diff --git a/ruby_1_9_3/lib/ipaddr.rb b/ruby_1_9_3/lib/ipaddr.rb
deleted file mode 100644
index 15692cf4f8..0000000000
--- a/ruby_1_9_3/lib/ipaddr.rb
+++ /dev/null
@@ -1,924 +0,0 @@
-#
-# ipaddr.rb - A class to manipulate an IP address
-#
-# Copyright (c) 2002 Hajimu UMEMOTO <ume@mahoroba.org>.
-# Copyright (c) 2007, 2009, 2012 Akinori MUSHA <knu@iDaemons.org>.
-# All rights reserved.
-#
-# You can redistribute and/or modify it under the same terms as Ruby.
-#
-# $Id$
-#
-# Contact:
-# - Akinori MUSHA <knu@iDaemons.org> (current maintainer)
-#
-# TODO:
-# - scope_id support
-#
-require 'socket'
-
-# IPAddr provides a set of methods to manipulate an IP address. Both IPv4 and
-# IPv6 are supported.
-#
-# == Example
-#
-# require 'ipaddr'
-#
-# ipaddr1 = IPAddr.new "3ffe:505:2::1"
-#
-# p ipaddr1 #=> #<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0001/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff>
-#
-# p ipaddr1.to_s #=> "3ffe:505:2::1"
-#
-# ipaddr2 = ipaddr1.mask(48) #=> #<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0000/ffff:ffff:ffff:0000:0000:0000:0000:0000>
-#
-# p ipaddr2.to_s #=> "3ffe:505:2::"
-#
-# ipaddr3 = IPAddr.new "192.168.2.0/24"
-#
-# p ipaddr3 #=> #<IPAddr: IPv4:192.168.2.0/255.255.255.0>
-
-class IPAddr
-
- # 32 bit mask for IPv4
- IN4MASK = 0xffffffff
- # 128 bit mask for IPv4
- IN6MASK = 0xffffffffffffffffffffffffffffffff
- # Format string for IPv6
- IN6FORMAT = (["%.4x"] * 8).join(':')
-
- # Regexp _internally_ used for parsing IPv4 address.
- RE_IPV4ADDRLIKE = %r{
- \A
- (\d+) \. (\d+) \. (\d+) \. (\d+)
- \z
- }x
-
- # Regexp _internally_ used for parsing IPv6 address.
- RE_IPV6ADDRLIKE_FULL = %r{
- \A
- (?:
- (?: [\da-f]{1,4} : ){7} [\da-f]{1,4}
- |
- ( (?: [\da-f]{1,4} : ){6} )
- (\d+) \. (\d+) \. (\d+) \. (\d+)
- )
- \z
- }xi
-
- # Regexp _internally_ used for parsing IPv6 address.
- RE_IPV6ADDRLIKE_COMPRESSED = %r{
- \A
- ( (?: (?: [\da-f]{1,4} : )* [\da-f]{1,4} )? )
- ::
- ( (?:
- ( (?: [\da-f]{1,4} : )* )
- (?:
- [\da-f]{1,4}
- |
- (\d+) \. (\d+) \. (\d+) \. (\d+)
- )
- )? )
- \z
- }xi
-
- # Returns the address family of this IP address.
- attr_reader :family
-
- # Creates a new ipaddr containing the given network byte ordered
- # string form of an IP address.
- def IPAddr::new_ntoh(addr)
- return IPAddr.new(IPAddr::ntop(addr))
- end
-
- # Convert a network byte ordered string form of an IP address into
- # human readable form.
- def IPAddr::ntop(addr)
- case addr.size
- when 4
- s = addr.unpack('C4').join('.')
- when 16
- s = IN6FORMAT % addr.unpack('n8')
- else
- raise ArgumentError, "unsupported address family"
- end
- return s
- end
-
- # Returns a new ipaddr built by bitwise AND.
- def &(other)
- return self.clone.set(@addr & coerce_other(other).to_i)
- end
-
- # Returns a new ipaddr built by bitwise OR.
- def |(other)
- return self.clone.set(@addr | coerce_other(other).to_i)
- end
-
- # Returns a new ipaddr built by bitwise right-shift.
- def >>(num)
- return self.clone.set(@addr >> num)
- end
-
- # Returns a new ipaddr built by bitwise left shift.
- def <<(num)
- return self.clone.set(addr_mask(@addr << num))
- end
-
- # Returns a new ipaddr built by bitwise negation.
- def ~
- return self.clone.set(addr_mask(~@addr))
- end
-
- # Returns true if two ipaddrs are equal.
- def ==(other)
- other = coerce_other(other)
- return @family == other.family && @addr == other.to_i
- end
-
- # Returns a new ipaddr built by masking IP address with the given
- # prefixlen/netmask. (e.g. 8, 64, "255.255.255.0", etc.)
- def mask(prefixlen)
- return self.clone.mask!(prefixlen)
- end
-
- # Returns true if the given ipaddr is in the range.
- #
- # e.g.:
- # require 'ipaddr'
- # net1 = IPAddr.new("192.168.2.0/24")
- # net2 = IPAddr.new("192.168.2.100")
- # net3 = IPAddr.new("192.168.3.0")
- # p net1.include?(net2) #=> true
- # p net1.include?(net3) #=> false
- def include?(other)
- other = coerce_other(other)
- if ipv4_mapped?
- if (@mask_addr >> 32) != 0xffffffffffffffffffffffff
- return false
- end
- mask_addr = (@mask_addr & IN4MASK)
- addr = (@addr & IN4MASK)
- family = Socket::AF_INET
- else
- mask_addr = @mask_addr
- addr = @addr
- family = @family
- end
- if other.ipv4_mapped?
- other_addr = (other.to_i & IN4MASK)
- other_family = Socket::AF_INET
- else
- other_addr = other.to_i
- other_family = other.family
- end
-
- if family != other_family
- return false
- end
- return ((addr & mask_addr) == (other_addr & mask_addr))
- end
- alias === include?
-
- # Returns the integer representation of the ipaddr.
- def to_i
- return @addr
- end
-
- # Returns a string containing the IP address representation.
- def to_s
- str = to_string
- return str if ipv4?
-
- str.gsub!(/\b0{1,3}([\da-f]+)\b/i, '\1')
- loop do
- break if str.sub!(/\A0:0:0:0:0:0:0:0\z/, '::')
- break if str.sub!(/\b0:0:0:0:0:0:0\b/, ':')
- break if str.sub!(/\b0:0:0:0:0:0\b/, ':')
- break if str.sub!(/\b0:0:0:0:0\b/, ':')
- break if str.sub!(/\b0:0:0:0\b/, ':')
- break if str.sub!(/\b0:0:0\b/, ':')
- break if str.sub!(/\b0:0\b/, ':')
- break
- end
- str.sub!(/:{3,}/, '::')
-
- if /\A::(ffff:)?([\da-f]{1,4}):([\da-f]{1,4})\z/i =~ str
- str = sprintf('::%s%d.%d.%d.%d', $1, $2.hex / 256, $2.hex % 256, $3.hex / 256, $3.hex % 256)
- end
-
- str
- end
-
- # Returns a string containing the IP address representation in
- # canonical form.
- def to_string
- return _to_string(@addr)
- end
-
- # Returns a network byte ordered string form of the IP address.
- def hton
- case @family
- when Socket::AF_INET
- return [@addr].pack('N')
- when Socket::AF_INET6
- return (0..7).map { |i|
- (@addr >> (112 - 16 * i)) & 0xffff
- }.pack('n8')
- else
- raise "unsupported address family"
- end
- end
-
- # Returns true if the ipaddr is an IPv4 address.
- def ipv4?
- return @family == Socket::AF_INET
- end
-
- # Returns true if the ipaddr is an IPv6 address.
- def ipv6?
- return @family == Socket::AF_INET6
- end
-
- # Returns true if the ipaddr is an IPv4-mapped IPv6 address.
- def ipv4_mapped?
- return ipv6? && (@addr >> 32) == 0xffff
- end
-
- # Returns true if the ipaddr is an IPv4-compatible IPv6 address.
- def ipv4_compat?
- if !ipv6? || (@addr >> 32) != 0
- return false
- end
- a = (@addr & IN4MASK)
- return a != 0 && a != 1
- end
-
- # Returns a new ipaddr built by converting the native IPv4 address
- # into an IPv4-mapped IPv6 address.
- def ipv4_mapped
- if !ipv4?
- raise ArgumentError, "not an IPv4 address"
- end
- return self.clone.set(@addr | 0xffff00000000, Socket::AF_INET6)
- end
-
- # Returns a new ipaddr built by converting the native IPv4 address
- # into an IPv4-compatible IPv6 address.
- def ipv4_compat
- if !ipv4?
- raise ArgumentError, "not an IPv4 address"
- end
- return self.clone.set(@addr, Socket::AF_INET6)
- end
-
- # Returns a new ipaddr built by converting the IPv6 address into a
- # native IPv4 address. If the IP address is not an IPv4-mapped or
- # IPv4-compatible IPv6 address, returns self.
- def native
- if !ipv4_mapped? && !ipv4_compat?
- return self
- end
- return self.clone.set(@addr & IN4MASK, Socket::AF_INET)
- end
-
- # Returns a string for DNS reverse lookup. It returns a string in
- # RFC3172 form for an IPv6 address.
- def reverse
- case @family
- when Socket::AF_INET
- return _reverse + ".in-addr.arpa"
- when Socket::AF_INET6
- return ip6_arpa
- else
- raise "unsupported address family"
- end
- end
-
- # Returns a string for DNS reverse lookup compatible with RFC3172.
- def ip6_arpa
- if !ipv6?
- raise ArgumentError, "not an IPv6 address"
- end
- return _reverse + ".ip6.arpa"
- end
-
- # Returns a string for DNS reverse lookup compatible with RFC1886.
- def ip6_int
- if !ipv6?
- raise ArgumentError, "not an IPv6 address"
- end
- return _reverse + ".ip6.int"
- end
-
- # Returns the successor to the ipaddr.
- def succ
- return self.clone.set(@addr + 1, @family)
- end
-
- # Compares the ipaddr with another.
- def <=>(other)
- other = coerce_other(other)
-
- return nil if other.family != @family
-
- return @addr <=> other.to_i
- end
- include Comparable
-
- # Checks equality used by Hash.
- def eql?(other)
- return self.class == other.class && self.hash == other.hash && self == other
- end
-
- # Returns a hash value used by Hash, Set, and Array classes
- def hash
- return ([@addr, @mask_addr].hash << 1) | (ipv4? ? 0 : 1)
- end
-
- # Creates a Range object for the network address.
- def to_range
- begin_addr = (@addr & @mask_addr)
-
- case @family
- when Socket::AF_INET
- end_addr = (@addr | (IN4MASK ^ @mask_addr))
- when Socket::AF_INET6
- end_addr = (@addr | (IN6MASK ^ @mask_addr))
- else
- raise "unsupported address family"
- end
-
- return clone.set(begin_addr, @family)..clone.set(end_addr, @family)
- end
-
- # Returns a string containing a human-readable representation of the
- # ipaddr. ("#<IPAddr: family:address/mask>")
- def inspect
- case @family
- when Socket::AF_INET
- af = "IPv4"
- when Socket::AF_INET6
- af = "IPv6"
- else
- raise "unsupported address family"
- end
- return sprintf("#<%s: %s:%s/%s>", self.class.name,
- af, _to_string(@addr), _to_string(@mask_addr))
- end
-
- protected
-
- # Set +@addr+, the internal stored ip address, to given +addr+. The
- # parameter +addr+ is validated using the first +family+ member,
- # which is +Socket::AF_INET+ or +Socket::AF_INET6+.
- def set(addr, *family)
- case family[0] ? family[0] : @family
- when Socket::AF_INET
- if addr < 0 || addr > IN4MASK
- raise ArgumentError, "invalid address"
- end
- when Socket::AF_INET6
- if addr < 0 || addr > IN6MASK
- raise ArgumentError, "invalid address"
- end
- else
- raise ArgumentError, "unsupported address family"
- end
- @addr = addr
- if family[0]
- @family = family[0]
- end
- return self
- end
-
- # Set current netmask to given mask.
- def mask!(mask)
- if mask.kind_of?(String)
- if mask =~ /^\d+$/
- prefixlen = mask.to_i
- else
- m = IPAddr.new(mask)
- if m.family != @family
- raise ArgumentError, "address family is not same"
- end
- @mask_addr = m.to_i
- @addr &= @mask_addr
- return self
- end
- else
- prefixlen = mask
- end
- case @family
- when Socket::AF_INET
- if prefixlen < 0 || prefixlen > 32
- raise ArgumentError, "invalid length"
- end
- masklen = 32 - prefixlen
- @mask_addr = ((IN4MASK >> masklen) << masklen)
- when Socket::AF_INET6
- if prefixlen < 0 || prefixlen > 128
- raise ArgumentError, "invalid length"
- end
- masklen = 128 - prefixlen
- @mask_addr = ((IN6MASK >> masklen) << masklen)
- else
- raise "unsupported address family"
- end
- @addr = ((@addr >> masklen) << masklen)
- return self
- end
-
- private
-
- # Creates a new ipaddr object either from a human readable IP
- # address representation in string, or from a packed in_addr value
- # followed by an address family.
- #
- # In the former case, the following are the valid formats that will
- # be recognized: "address", "address/prefixlen" and "address/mask",
- # where IPv6 address may be enclosed in square brackets (`[' and
- # `]'). If a prefixlen or a mask is specified, it returns a masked
- # IP address. Although the address family is determined
- # automatically from a specified string, you can specify one
- # explicitly by the optional second argument.
- #
- # Otherwise an IP address is generated from a packed in_addr value
- # and an address family.
- #
- # The IPAddr class defines many methods and operators, and some of
- # those, such as &, |, include? and ==, accept a string, or a packed
- # in_addr value instead of an IPAddr object.
- def initialize(addr = '::', family = Socket::AF_UNSPEC)
- if !addr.kind_of?(String)
- case family
- when Socket::AF_INET, Socket::AF_INET6
- set(addr.to_i, family)
- @mask_addr = (family == Socket::AF_INET) ? IN4MASK : IN6MASK
- return
- when Socket::AF_UNSPEC
- raise ArgumentError, "address family must be specified"
- else
- raise ArgumentError, "unsupported address family: #{family}"
- end
- end
- prefix, prefixlen = addr.split('/')
- if prefix =~ /^\[(.*)\]$/i
- prefix = $1
- family = Socket::AF_INET6
- end
- # It seems AI_NUMERICHOST doesn't do the job.
- #Socket.getaddrinfo(left, nil, Socket::AF_INET6, Socket::SOCK_STREAM, nil,
- # Socket::AI_NUMERICHOST)
- @addr = @family = nil
- if family == Socket::AF_UNSPEC || family == Socket::AF_INET
- @addr = in_addr(prefix)
- if @addr
- @family = Socket::AF_INET
- end
- end
- if !@addr && (family == Socket::AF_UNSPEC || family == Socket::AF_INET6)
- @addr = in6_addr(prefix)
- @family = Socket::AF_INET6
- end
- if family != Socket::AF_UNSPEC && @family != family
- raise ArgumentError, "address family mismatch"
- end
- if prefixlen
- mask!(prefixlen)
- else
- @mask_addr = (@family == Socket::AF_INET) ? IN4MASK : IN6MASK
- end
- end
-
- def coerce_other(other)
- case other
- when IPAddr
- other
- when String
- self.class.new(other)
- else
- self.class.new(other, @family)
- end
- end
-
- def in_addr(addr)
- case addr
- when Array
- octets = addr
- else
- m = RE_IPV4ADDRLIKE.match(addr) or return nil
- octets = m.captures
- end
- octets.inject(0) { |i, s|
- (n = s.to_i) < 256 or raise ArgumentError, "invalid address"
- s.match(/\A0./) and raise ArgumentError, "zero-filled number is ambiguous"
- i << 8 | n
- }
- end
-
- def in6_addr(left)
- case left
- when RE_IPV6ADDRLIKE_FULL
- if $2
- addr = in_addr($~[2,4])
- left = $1 + ':'
- else
- addr = 0
- end
- right = ''
- when RE_IPV6ADDRLIKE_COMPRESSED
- if $4
- left.count(':') <= 6 or raise ArgumentError, "invalid address"
- addr = in_addr($~[4,4])
- left = $1
- right = $3 + '0:0'
- else
- left.count(':') <= ($1.empty? || $2.empty? ? 8 : 7) or
- raise InvalidAddressError, "invalid address"
- left = $1
- right = $2
- addr = 0
- end
- else
- raise ArgumentError, "invalid address"
- end
- l = left.split(':')
- r = right.split(':')
- rest = 8 - l.size - r.size
- if rest < 0
- return nil
- end
- (l + Array.new(rest, '0') + r).inject(0) { |i, s|
- i << 16 | s.hex
- } | addr
- end
-
- def addr_mask(addr)
- case @family
- when Socket::AF_INET
- return addr & IN4MASK
- when Socket::AF_INET6
- return addr & IN6MASK
- else
- raise "unsupported address family"
- end
- end
-
- def _reverse
- case @family
- when Socket::AF_INET
- return (0..3).map { |i|
- (@addr >> (8 * i)) & 0xff
- }.join('.')
- when Socket::AF_INET6
- return ("%.32x" % @addr).reverse!.gsub!(/.(?!$)/, '\&.')
- else
- raise "unsupported address family"
- end
- end
-
- def _to_string(addr)
- case @family
- when Socket::AF_INET
- return (0..3).map { |i|
- (addr >> (24 - 8 * i)) & 0xff
- }.join('.')
- when Socket::AF_INET6
- return (("%.32x" % addr).gsub!(/.{4}(?!$)/, '\&:'))
- else
- raise "unsupported address family"
- end
- end
-
-end
-
-unless Socket.const_defined? "AF_INET6"
- class Socket < BasicSocket
- # IPv6 protocol family
- AF_INET6 = Object.new
- end
-
- class << IPSocket
- private
-
- def valid_v6?(addr)
- case addr
- when IPAddr::RE_IPV6ADDRLIKE_FULL
- if $2
- $~[2,4].all? {|i| i.to_i < 256 }
- else
- true
- end
- when IPAddr::RE_IPV6ADDRLIKE_COMPRESSED
- if $4
- addr.count(':') <= 6 && $~[4,4].all? {|i| i.to_i < 256}
- else
- addr.count(':') <= 7
- end
- else
- false
- end
- end
-
- alias getaddress_orig getaddress
-
- public
-
- # Returns a +String+ based representation of a valid DNS hostname,
- # IPv4 or IPv6 address.
- #
- # IPSocket.getaddress 'localhost' #=> "::1"
- # IPSocket.getaddress 'broadcasthost' #=> "255.255.255.255"
- # IPSocket.getaddress 'www.ruby-lang.org' #=> "221.186.184.68"
- # IPSocket.getaddress 'www.ccc.de' #=> "2a00:1328:e102:ccc0::122"
- def getaddress(s)
- if valid_v6?(s)
- s
- else
- getaddress_orig(s)
- end
- end
- end
-end
-
-if $0 == __FILE__
- eval DATA.read, nil, $0, __LINE__+4
-end
-
-__END__
-
-require 'test/unit'
-
-class TC_IPAddr < Test::Unit::TestCase
- def test_s_new
- [
- ["3FFE:505:ffff::/48"],
- ["0:0:0:1::"],
- ["2001:200:300::/48"],
- ["2001:200:300::192.168.1.2/48"],
- ["1:2:3:4:5:6:7::"],
- ["::2:3:4:5:6:7:8"],
- ].each { |args|
- assert_nothing_raised {
- IPAddr.new(*args)
- }
- }
-
- a = IPAddr.new
- assert_equal("::", a.to_s)
- assert_equal("0000:0000:0000:0000:0000:0000:0000:0000", a.to_string)
- assert_equal(Socket::AF_INET6, a.family)
-
- a = IPAddr.new("0123:4567:89ab:cdef:0ABC:DEF0:1234:5678")
- assert_equal("123:4567:89ab:cdef:abc:def0:1234:5678", a.to_s)
- assert_equal("0123:4567:89ab:cdef:0abc:def0:1234:5678", a.to_string)
- assert_equal(Socket::AF_INET6, a.family)
-
- a = IPAddr.new("3ffe:505:2::/48")
- assert_equal("3ffe:505:2::", a.to_s)
- assert_equal("3ffe:0505:0002:0000:0000:0000:0000:0000", a.to_string)
- assert_equal(Socket::AF_INET6, a.family)
- assert_equal(false, a.ipv4?)
- assert_equal(true, a.ipv6?)
- assert_equal("#<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0000/ffff:ffff:ffff:0000:0000:0000:0000:0000>", a.inspect)
-
- a = IPAddr.new("3ffe:505:2::/ffff:ffff:ffff::")
- assert_equal("3ffe:505:2::", a.to_s)
- assert_equal("3ffe:0505:0002:0000:0000:0000:0000:0000", a.to_string)
- assert_equal(Socket::AF_INET6, a.family)
-
- a = IPAddr.new("0.0.0.0")
- assert_equal("0.0.0.0", a.to_s)
- assert_equal("0.0.0.0", a.to_string)
- assert_equal(Socket::AF_INET, a.family)
-
- a = IPAddr.new("192.168.1.2")
- assert_equal("192.168.1.2", a.to_s)
- assert_equal("192.168.1.2", a.to_string)
- assert_equal(Socket::AF_INET, a.family)
- assert_equal(true, a.ipv4?)
- assert_equal(false, a.ipv6?)
-
- a = IPAddr.new("192.168.1.2/24")
- assert_equal("192.168.1.0", a.to_s)
- assert_equal("192.168.1.0", a.to_string)
- assert_equal(Socket::AF_INET, a.family)
- assert_equal("#<IPAddr: IPv4:192.168.1.0/255.255.255.0>", a.inspect)
-
- a = IPAddr.new("192.168.1.2/255.255.255.0")
- assert_equal("192.168.1.0", a.to_s)
- assert_equal("192.168.1.0", a.to_string)
- assert_equal(Socket::AF_INET, a.family)
-
- assert_equal("0:0:0:1::", IPAddr.new("0:0:0:1::").to_s)
- assert_equal("2001:200:300::", IPAddr.new("2001:200:300::/48").to_s)
-
- assert_equal("2001:200:300::", IPAddr.new("[2001:200:300::]/48").to_s)
- assert_equal("1:2:3:4:5:6:7:0", IPAddr.new("1:2:3:4:5:6:7::").to_s)
- assert_equal("0:2:3:4:5:6:7:8", IPAddr.new("::2:3:4:5:6:7:8").to_s)
-
- [
- ["192.168.0.256"],
- ["192.168.0.011"],
- ["fe80::1%fxp0"],
- ["::1/255.255.255.0"],
- [IPAddr.new("::1").to_i],
- ["::ffff:192.168.1.2/120", Socket::AF_INET],
- ["[192.168.1.2]/120"],
- ].each { |args|
- assert_raises(ArgumentError) {
- IPAddr.new(*args)
- }
- }
- end
-
- def test_s_new_ntoh
- addr = ''
- IPAddr.new("1234:5678:9abc:def0:1234:5678:9abc:def0").hton.each_byte { |c|
- addr += sprintf("%02x", c)
- }
- assert_equal("123456789abcdef0123456789abcdef0", addr)
- addr = ''
- IPAddr.new("123.45.67.89").hton.each_byte { |c|
- addr += sprintf("%02x", c)
- }
- assert_equal(sprintf("%02x%02x%02x%02x", 123, 45, 67, 89), addr)
- a = IPAddr.new("3ffe:505:2::")
- assert_equal("3ffe:505:2::", IPAddr.new_ntoh(a.hton).to_s)
- a = IPAddr.new("192.168.2.1")
- assert_equal("192.168.2.1", IPAddr.new_ntoh(a.hton).to_s)
- end
-
- def test_ipv4_compat
- a = IPAddr.new("::192.168.1.2")
- assert_equal("::192.168.1.2", a.to_s)
- assert_equal("0000:0000:0000:0000:0000:0000:c0a8:0102", a.to_string)
- assert_equal(Socket::AF_INET6, a.family)
- assert_equal(true, a.ipv4_compat?)
- b = a.native
- assert_equal("192.168.1.2", b.to_s)
- assert_equal(Socket::AF_INET, b.family)
- assert_equal(false, b.ipv4_compat?)
-
- a = IPAddr.new("192.168.1.2")
- b = a.ipv4_compat
- assert_equal("::192.168.1.2", b.to_s)
- assert_equal(Socket::AF_INET6, b.family)
- end
-
- def test_ipv4_mapped
- a = IPAddr.new("::ffff:192.168.1.2")
- assert_equal("::ffff:192.168.1.2", a.to_s)
- assert_equal("0000:0000:0000:0000:0000:ffff:c0a8:0102", a.to_string)
- assert_equal(Socket::AF_INET6, a.family)
- assert_equal(true, a.ipv4_mapped?)
- b = a.native
- assert_equal("192.168.1.2", b.to_s)
- assert_equal(Socket::AF_INET, b.family)
- assert_equal(false, b.ipv4_mapped?)
-
- a = IPAddr.new("192.168.1.2")
- b = a.ipv4_mapped
- assert_equal("::ffff:192.168.1.2", b.to_s)
- assert_equal(Socket::AF_INET6, b.family)
- end
-
- def test_reverse
- assert_equal("f.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.2.0.0.0.5.0.5.0.e.f.f.3.ip6.arpa", IPAddr.new("3ffe:505:2::f").reverse)
- assert_equal("1.2.168.192.in-addr.arpa", IPAddr.new("192.168.2.1").reverse)
- end
-
- def test_ip6_arpa
- assert_equal("f.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.2.0.0.0.5.0.5.0.e.f.f.3.ip6.arpa", IPAddr.new("3ffe:505:2::f").ip6_arpa)
- assert_raises(ArgumentError) {
- IPAddr.new("192.168.2.1").ip6_arpa
- }
- end
-
- def test_ip6_int
- assert_equal("f.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.2.0.0.0.5.0.5.0.e.f.f.3.ip6.int", IPAddr.new("3ffe:505:2::f").ip6_int)
- assert_raises(ArgumentError) {
- IPAddr.new("192.168.2.1").ip6_int
- }
- end
-
- def test_to_s
- assert_equal("3ffe:0505:0002:0000:0000:0000:0000:0001", IPAddr.new("3ffe:505:2::1").to_string)
- assert_equal("3ffe:505:2::1", IPAddr.new("3ffe:505:2::1").to_s)
- end
-end
-
-class TC_Operator < Test::Unit::TestCase
-
- IN6MASK32 = "ffff:ffff::"
- IN6MASK128 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"
-
- def setup
- @in6_addr_any = IPAddr.new()
- @a = IPAddr.new("3ffe:505:2::/48")
- @b = IPAddr.new("0:0:0:1::")
- @c = IPAddr.new(IN6MASK32)
- end
- alias set_up setup
-
- def test_or
- assert_equal("3ffe:505:2:1::", (@a | @b).to_s)
- a = @a
- a |= @b
- assert_equal("3ffe:505:2:1::", a.to_s)
- assert_equal("3ffe:505:2::", @a.to_s)
- assert_equal("3ffe:505:2:1::",
- (@a | 0x00000000000000010000000000000000).to_s)
- end
-
- def test_and
- assert_equal("3ffe:505::", (@a & @c).to_s)
- a = @a
- a &= @c
- assert_equal("3ffe:505::", a.to_s)
- assert_equal("3ffe:505:2::", @a.to_s)
- assert_equal("3ffe:505::", (@a & 0xffffffff000000000000000000000000).to_s)
- end
-
- def test_shift_right
- assert_equal("0:3ffe:505:2::", (@a >> 16).to_s)
- a = @a
- a >>= 16
- assert_equal("0:3ffe:505:2::", a.to_s)
- assert_equal("3ffe:505:2::", @a.to_s)
- end
-
- def test_shift_left
- assert_equal("505:2::", (@a << 16).to_s)
- a = @a
- a <<= 16
- assert_equal("505:2::", a.to_s)
- assert_equal("3ffe:505:2::", @a.to_s)
- end
-
- def test_carrot
- a = ~@in6_addr_any
- assert_equal(IN6MASK128, a.to_s)
- assert_equal("::", @in6_addr_any.to_s)
- end
-
- def test_equal
- assert_equal(true, @a == IPAddr.new("3FFE:505:2::"))
- assert_equal(true, @a == IPAddr.new("3ffe:0505:0002::"))
- assert_equal(true, @a == IPAddr.new("3ffe:0505:0002:0:0:0:0:0"))
- assert_equal(false, @a == IPAddr.new("3ffe:505:3::"))
- assert_equal(true, @a != IPAddr.new("3ffe:505:3::"))
- assert_equal(false, @a != IPAddr.new("3ffe:505:2::"))
- end
-
- def test_mask
- a = @a.mask(32)
- assert_equal("3ffe:505::", a.to_s)
- assert_equal("3ffe:505:2::", @a.to_s)
- end
-
- def test_include?
- assert_equal(true, @a.include?(IPAddr.new("3ffe:505:2::")))
- assert_equal(true, @a.include?(IPAddr.new("3ffe:505:2::1")))
- assert_equal(false, @a.include?(IPAddr.new("3ffe:505:3::")))
- net1 = IPAddr.new("192.168.2.0/24")
- assert_equal(true, net1.include?(IPAddr.new("192.168.2.0")))
- assert_equal(true, net1.include?(IPAddr.new("192.168.2.255")))
- assert_equal(false, net1.include?(IPAddr.new("192.168.3.0")))
- # test with integer parameter
- int = (192 << 24) + (168 << 16) + (2 << 8) + 13
-
- assert_equal(true, net1.include?(int))
- assert_equal(false, net1.include?(int+255))
-
- end
-
- def test_hash
- a1 = IPAddr.new('192.168.2.0')
- a2 = IPAddr.new('192.168.2.0')
- a3 = IPAddr.new('3ffe:505:2::1')
- a4 = IPAddr.new('3ffe:505:2::1')
- a5 = IPAddr.new('127.0.0.1')
- a6 = IPAddr.new('::1')
- a7 = IPAddr.new('192.168.2.0/25')
- a8 = IPAddr.new('192.168.2.0/25')
-
- h = { a1 => 'ipv4', a2 => 'ipv4', a3 => 'ipv6', a4 => 'ipv6', a5 => 'ipv4', a6 => 'ipv6', a7 => 'ipv4', a8 => 'ipv4'}
- assert_equal(5, h.size)
- assert_equal('ipv4', h[a1])
- assert_equal('ipv4', h[a2])
- assert_equal('ipv6', h[a3])
- assert_equal('ipv6', h[a4])
-
- require 'set'
- s = Set[a1, a2, a3, a4, a5, a6, a7, a8]
- assert_equal(5, s.size)
- assert_equal(true, s.include?(a1))
- assert_equal(true, s.include?(a2))
- assert_equal(true, s.include?(a3))
- assert_equal(true, s.include?(a4))
- assert_equal(true, s.include?(a5))
- assert_equal(true, s.include?(a6))
- end
-end
diff --git a/ruby_1_9_3/lib/irb.rb b/ruby_1_9_3/lib/irb.rb
deleted file mode 100644
index c8fa04c4e5..0000000000
--- a/ruby_1_9_3/lib/irb.rb
+++ /dev/null
@@ -1,352 +0,0 @@
-#
-# irb.rb - irb main module
-# $Release Version: 0.9.6 $
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-require "e2mmap"
-
-require "irb/init"
-require "irb/context"
-require "irb/extend-command"
-#require "irb/workspace"
-
-require "irb/ruby-lex"
-require "irb/input-method"
-require "irb/locale"
-
-STDOUT.sync = true
-
-module IRB
- @RCS_ID='-$Id$-'
-
- class Abort < Exception;end
-
- #
- @CONF = {}
-
- def IRB.conf
- @CONF
- end
-
- # IRB version method
- def IRB.version
- if v = @CONF[:VERSION] then return v end
-
- require "irb/version"
- rv = @RELEASE_VERSION.sub(/\.0/, "")
- @CONF[:VERSION] = format("irb %s(%s)", rv, @LAST_UPDATE_DATE)
- end
-
- def IRB.CurrentContext
- IRB.conf[:MAIN_CONTEXT]
- end
-
- # initialize IRB and start TOP_LEVEL irb
- def IRB.start(ap_path = nil)
- $0 = File::basename(ap_path, ".rb") if ap_path
-
- IRB.setup(ap_path)
-
- if @CONF[:SCRIPT]
- irb = Irb.new(nil, @CONF[:SCRIPT])
- else
- irb = Irb.new
- end
-
- @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC]
- @CONF[:MAIN_CONTEXT] = irb.context
-
- trap("SIGINT") do
- irb.signal_handle
- end
-
- begin
- catch(:IRB_EXIT) do
- irb.eval_input
- end
- ensure
- irb_at_exit
- end
-# print "\n"
- end
-
- def IRB.irb_at_exit
- @CONF[:AT_EXIT].each{|hook| hook.call}
- end
-
- def IRB.irb_exit(irb, ret)
- throw :IRB_EXIT, ret
- end
-
- def IRB.irb_abort(irb, exception = Abort)
- if defined? Thread
- irb.context.thread.raise exception, "abort then interrupt!"
- else
- raise exception, "abort then interrupt!"
- end
- end
-
- #
- # irb interpreter main routine
- #
- class Irb
- def initialize(workspace = nil, input_method = nil, output_method = nil)
- @context = Context.new(self, workspace, input_method, output_method)
- @context.main.extend ExtendCommandBundle
- @signal_status = :IN_IRB
-
- @scanner = RubyLex.new
- @scanner.exception_on_syntax_error = false
- end
- attr_reader :context
- attr_accessor :scanner
-
- def eval_input
- @scanner.set_prompt do
- |ltype, indent, continue, line_no|
- if ltype
- f = @context.prompt_s
- elsif continue
- f = @context.prompt_c
- elsif indent > 0
- f = @context.prompt_n
- else
- f = @context.prompt_i
- end
- f = "" unless f
- if @context.prompting?
- @context.io.prompt = p = prompt(f, ltype, indent, line_no)
- else
- @context.io.prompt = p = ""
- end
- if @context.auto_indent_mode
- unless ltype
- ind = prompt(@context.prompt_i, ltype, indent, line_no)[/.*\z/].size +
- indent * 2 - p.size
- ind += 2 if continue
- @context.io.prompt = p + " " * ind if ind > 0
- end
- end
- end
-
- @scanner.set_input(@context.io) do
- signal_status(:IN_INPUT) do
- if l = @context.io.gets
- print l if @context.verbose?
- else
- if @context.ignore_eof? and @context.io.readable_atfer_eof?
- l = "\n"
- if @context.verbose?
- printf "Use \"exit\" to leave %s\n", @context.ap_name
- end
- else
- print "\n"
- end
- end
- l
- end
- end
-
- @scanner.each_top_level_statement do |line, line_no|
- signal_status(:IN_EVAL) do
- begin
- line.untaint
- @context.evaluate(line, line_no)
- output_value if @context.echo?
- exc = nil
- rescue Interrupt => exc
- rescue SystemExit, SignalException
- raise
- rescue Exception => exc
- end
- if exc
- print exc.class, ": ", exc, "\n"
- if exc.backtrace[0] =~ /irb(2)?(\/.*|-.*|\.rb)?:/ && exc.class.to_s !~ /^IRB/ &&
- !(SyntaxError === exc)
- irb_bug = true
- else
- irb_bug = false
- end
-
- messages = []
- lasts = []
- levels = 0
- for m in exc.backtrace
- m = @context.workspace.filter_backtrace(m) unless irb_bug
- if m
- if messages.size < @context.back_trace_limit
- messages.push "\tfrom "+m
- else
- lasts.push "\tfrom "+m
- if lasts.size > @context.back_trace_limit
- lasts.shift
- levels += 1
- end
- end
- end
- end
- print messages.join("\n"), "\n"
- unless lasts.empty?
- printf "... %d levels...\n", levels if levels > 0
- print lasts.join("\n")
- end
- print "Maybe IRB bug!\n" if irb_bug
- end
- if $SAFE > 2
- abort "Error: irb does not work for $SAFE level higher than 2"
- end
- end
- end
- end
-
- def suspend_name(path = nil, name = nil)
- @context.irb_path, back_path = path, @context.irb_path if path
- @context.irb_name, back_name = name, @context.irb_name if name
- begin
- yield back_path, back_name
- ensure
- @context.irb_path = back_path if path
- @context.irb_name = back_name if name
- end
- end
-
- def suspend_workspace(workspace)
- @context.workspace, back_workspace = workspace, @context.workspace
- begin
- yield back_workspace
- ensure
- @context.workspace = back_workspace
- end
- end
-
- def suspend_input_method(input_method)
- back_io = @context.io
- @context.instance_eval{@io = input_method}
- begin
- yield back_io
- ensure
- @context.instance_eval{@io = back_io}
- end
- end
-
- def suspend_context(context)
- @context, back_context = context, @context
- begin
- yield back_context
- ensure
- @context = back_context
- end
- end
-
- def signal_handle
- unless @context.ignore_sigint?
- print "\nabort!\n" if @context.verbose?
- exit
- end
-
- case @signal_status
- when :IN_INPUT
- print "^C\n"
- raise RubyLex::TerminateLineInput
- when :IN_EVAL
- IRB.irb_abort(self)
- when :IN_LOAD
- IRB.irb_abort(self, LoadAbort)
- when :IN_IRB
- # ignore
- else
- # ignore other cases as well
- end
- end
-
- def signal_status(status)
- return yield if @signal_status == :IN_LOAD
-
- signal_status_back = @signal_status
- @signal_status = status
- begin
- yield
- ensure
- @signal_status = signal_status_back
- end
- end
-
- def prompt(prompt, ltype, indent, line_no)
- p = prompt.dup
- p.gsub!(/%([0-9]+)?([a-zA-Z])/) do
- case $2
- when "N"
- @context.irb_name
- when "m"
- @context.main.to_s
- when "M"
- @context.main.inspect
- when "l"
- ltype
- when "i"
- if $1
- format("%" + $1 + "d", indent)
- else
- indent.to_s
- end
- when "n"
- if $1
- format("%" + $1 + "d", line_no)
- else
- line_no.to_s
- end
- when "%"
- "%"
- end
- end
- p
- end
-
- def output_value
- printf @context.return_format, @context.inspect_last_value
- end
-
- def inspect
- ary = []
- for iv in instance_variables
- case (iv = iv.to_s)
- when "@signal_status"
- ary.push format("%s=:%s", iv, @signal_status.id2name)
- when "@context"
- ary.push format("%s=%s", iv, eval(iv).__to_s__)
- else
- ary.push format("%s=%s", iv, eval(iv))
- end
- end
- format("#<%s: %s>", self.class, ary.join(", "))
- end
- end
-
- # Singleton method
- def @CONF.inspect
- IRB.version unless self[:VERSION]
-
- array = []
- for k, v in sort{|a1, a2| a1[0].id2name <=> a2[0].id2name}
- case k
- when :MAIN_CONTEXT, :__TMP__EHV__
- array.push format("CONF[:%s]=...myself...", k.id2name)
- when :PROMPT
- s = v.collect{
- |kk, vv|
- ss = vv.collect{|kkk, vvv| ":#{kkk.id2name}=>#{vvv.inspect}"}
- format(":%s=>{%s}", kk.id2name, ss.join(", "))
- }
- array.push format("CONF[:%s]={%s}", k.id2name, s.join(", "))
- else
- array.push format("CONF[:%s]=%s", k.id2name, v.inspect)
- end
- end
- array.join("\n")
- end
-end
diff --git a/ruby_1_9_3/lib/irb/cmd/chws.rb b/ruby_1_9_3/lib/irb/cmd/chws.rb
deleted file mode 100644
index 65c977016b..0000000000
--- a/ruby_1_9_3/lib/irb/cmd/chws.rb
+++ /dev/null
@@ -1,32 +0,0 @@
-#
-# change-ws.rb -
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-require "irb/cmd/nop.rb"
-require "irb/ext/change-ws.rb"
-
-module IRB
- module ExtendCommand
-
- class CurrentWorkingWorkspace<Nop
- def execute(*obj)
- irb_context.main
- end
- end
-
- class ChangeWorkspace<Nop
- def execute(*obj)
- irb_context.change_workspace(*obj)
- irb_context.main
- end
- end
- end
-end
-
diff --git a/ruby_1_9_3/lib/irb/cmd/fork.rb b/ruby_1_9_3/lib/irb/cmd/fork.rb
deleted file mode 100644
index c2664626ae..0000000000
--- a/ruby_1_9_3/lib/irb/cmd/fork.rb
+++ /dev/null
@@ -1,38 +0,0 @@
-#
-# fork.rb -
-# $Release Version: 0.9.6 $
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-@RCS_ID='-$Id$-'
-
-
-module IRB
- module ExtendCommand
- class Fork<Nop
- def execute(&block)
- pid = send ExtendCommand.irb_original_method_name("fork")
- unless pid
- class << self
- alias_method :exit, ExtendCommand.irb_original_method_name('exit')
- end
- if iterator?
- begin
- yield
- ensure
- exit
- end
- end
- end
- pid
- end
- end
- end
-end
-
-
diff --git a/ruby_1_9_3/lib/irb/cmd/help.rb b/ruby_1_9_3/lib/irb/cmd/help.rb
deleted file mode 100644
index 67cf89990b..0000000000
--- a/ruby_1_9_3/lib/irb/cmd/help.rb
+++ /dev/null
@@ -1,39 +0,0 @@
-#
-# help.rb - helper using ri
-# $Release Version: 0.9.6$
-# $Revision$
-#
-# --
-#
-#
-#
-
-require 'rdoc/ri/driver'
-
-require "irb/cmd/nop.rb"
-
-module IRB
- module ExtendCommand
- class Help<Nop
- begin
- Ri = RDoc::RI::Driver.new
- rescue SystemExit
- else
- def execute(*names)
- if names.empty?
- Ri.interactive
- return
- end
- names.each do |name|
- begin
- Ri.display_name(name.to_s)
- rescue RDoc::RI::Error
- puts $!.message
- end
- end
- nil
- end
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/irb/cmd/load.rb b/ruby_1_9_3/lib/irb/cmd/load.rb
deleted file mode 100644
index 2a6de21ed7..0000000000
--- a/ruby_1_9_3/lib/irb/cmd/load.rb
+++ /dev/null
@@ -1,66 +0,0 @@
-#
-# load.rb -
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-require "irb/cmd/nop.rb"
-require "irb/ext/loader"
-
-module IRB
- module ExtendCommand
- class Load<Nop
- include IrbLoader
-
- def execute(file_name, priv = nil)
-# return ruby_load(file_name) unless IRB.conf[:USE_LOADER]
- return irb_load(file_name, priv)
- end
- end
-
- class Require<Nop
- include IrbLoader
-
- def execute(file_name)
-# return ruby_require(file_name) unless IRB.conf[:USE_LOADER]
-
- rex = Regexp.new("#{Regexp.quote(file_name)}(\.o|\.rb)?")
- return false if $".find{|f| f =~ rex}
-
- case file_name
- when /\.rb$/
- begin
- if irb_load(file_name)
- $".push file_name
- return true
- end
- rescue LoadError
- end
- when /\.(so|o|sl)$/
- return ruby_require(file_name)
- end
-
- begin
- irb_load(f = file_name + ".rb")
- $".push f
- return true
- rescue LoadError
- return ruby_require(file_name)
- end
- end
- end
-
- class Source<Nop
- include IrbLoader
- def execute(file_name)
- source_file(file_name)
- end
- end
- end
-
-end
diff --git a/ruby_1_9_3/lib/irb/cmd/nop.rb b/ruby_1_9_3/lib/irb/cmd/nop.rb
deleted file mode 100644
index 2b028975c8..0000000000
--- a/ruby_1_9_3/lib/irb/cmd/nop.rb
+++ /dev/null
@@ -1,38 +0,0 @@
-#
-# nop.rb -
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-module IRB
- module ExtendCommand
- class Nop
-
- @RCS_ID='-$Id$-'
-
- def self.execute(conf, *opts)
- command = new(conf)
- command.execute(*opts)
- end
-
- def initialize(conf)
- @irb_context = conf
- end
-
- attr_reader :irb_context
-
- def irb
- @irb_context.irb
- end
-
- def execute(*opts)
- #nop
- end
- end
- end
-end
-
diff --git a/ruby_1_9_3/lib/irb/cmd/pushws.rb b/ruby_1_9_3/lib/irb/cmd/pushws.rb
deleted file mode 100644
index 5fd567731c..0000000000
--- a/ruby_1_9_3/lib/irb/cmd/pushws.rb
+++ /dev/null
@@ -1,38 +0,0 @@
-#
-# change-ws.rb -
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-require "irb/cmd/nop.rb"
-require "irb/ext/workspaces.rb"
-
-module IRB
- module ExtendCommand
- class Workspaces<Nop
- def execute(*obj)
- irb_context.workspaces.collect{|ws| ws.main}
- end
- end
-
- class PushWorkspace<Workspaces
- def execute(*obj)
- irb_context.push_workspace(*obj)
- super
- end
- end
-
- class PopWorkspace<Workspaces
- def execute(*obj)
- irb_context.pop_workspace(*obj)
- super
- end
- end
- end
-end
-
diff --git a/ruby_1_9_3/lib/irb/cmd/subirb.rb b/ruby_1_9_3/lib/irb/cmd/subirb.rb
deleted file mode 100644
index 4d54a72b6f..0000000000
--- a/ruby_1_9_3/lib/irb/cmd/subirb.rb
+++ /dev/null
@@ -1,40 +0,0 @@
-# multi.rb -
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-require "irb/cmd/nop.rb"
-require "irb/ext/multi-irb"
-
-module IRB
- module ExtendCommand
- class IrbCommand<Nop
- def execute(*obj)
- IRB.irb(nil, *obj)
- end
- end
-
- class Jobs<Nop
- def execute
- IRB.JobManager
- end
- end
-
- class Foreground<Nop
- def execute(key)
- IRB.JobManager.switch(key)
- end
- end
-
- class Kill<Nop
- def execute(*keys)
- IRB.JobManager.kill(*keys)
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/irb/completion.rb b/ruby_1_9_3/lib/irb/completion.rb
deleted file mode 100644
index 7fd69a0a09..0000000000
--- a/ruby_1_9_3/lib/irb/completion.rb
+++ /dev/null
@@ -1,233 +0,0 @@
-#
-# irb/completor.rb -
-# $Release Version: 0.9$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-# From Original Idea of shugo@ruby-lang.org
-#
-
-require "readline"
-
-module IRB
- module InputCompletor
-
- @RCS_ID='-$Id$-'
-
- ReservedWords = [
- "BEGIN", "END",
- "alias", "and",
- "begin", "break",
- "case", "class",
- "def", "defined", "do",
- "else", "elsif", "end", "ensure",
- "false", "for",
- "if", "in",
- "module",
- "next", "nil", "not",
- "or",
- "redo", "rescue", "retry", "return",
- "self", "super",
- "then", "true",
- "undef", "unless", "until",
- "when", "while",
- "yield",
- ]
-
- CompletionProc = proc { |input|
- bind = IRB.conf[:MAIN_CONTEXT].workspace.binding
-
-# puts "input: #{input}"
-
- case input
- when /^((["'`]).*\2)\.([^.]*)$/
- # String
- receiver = $1
- message = $3
-
- candidates = String.instance_methods.collect{|m| m.to_s}
- select_message(receiver, message, candidates)
-
- when /^(\/[^\/]*\/)\.([^.]*)$/
- # Regexp
- receiver = $1
- message = Regexp.quote($2)
-
- candidates = Regexp.instance_methods.collect{|m| m.to_s}
- select_message(receiver, message, candidates)
-
- when /^([^\]]*\])\.([^.]*)$/
- # Array
- receiver = $1
- message = Regexp.quote($2)
-
- candidates = Array.instance_methods.collect{|m| m.to_s}
- select_message(receiver, message, candidates)
-
- when /^([^\}]*\})\.([^.]*)$/
- # Proc or Hash
- receiver = $1
- message = Regexp.quote($2)
-
- candidates = Proc.instance_methods.collect{|m| m.to_s}
- candidates |= Hash.instance_methods.collect{|m| m.to_s}
- select_message(receiver, message, candidates)
-
- when /^(:[^:.]*)$/
- # Symbol
- if Symbol.respond_to?(:all_symbols)
- sym = $1
- candidates = Symbol.all_symbols.collect{|s| ":" + s.id2name}
- candidates.grep(/^#{sym}/)
- else
- []
- end
-
- when /^::([A-Z][^:\.\(]*)$/
- # Absolute Constant or class methods
- receiver = $1
- candidates = Object.constants.collect{|m| m.to_s}
- candidates.grep(/^#{receiver}/).collect{|e| "::" + e}
-
-# when /^(((::)?[A-Z][^:.\(]*)+)::?([^:.]*)$/
- when /^([A-Z].*)::([^:.]*)$/
- # Constant or class methods
- receiver = $1
- message = Regexp.quote($2)
- begin
- candidates = eval("#{receiver}.constants.collect{|m| m.to_s}", bind)
- candidates |= eval("#{receiver}.methods.collect{|m| m.to_s}", bind)
- rescue Exception
- candidates = []
- end
- select_message(receiver, message, candidates, "::")
-
- when /^(:[^:.]+)(\.|::)([^.]*)$/
- # Symbol
- receiver = $1
- sep = $2
- message = Regexp.quote($3)
-
- candidates = Symbol.instance_methods.collect{|m| m.to_s}
- select_message(receiver, message, candidates, sep)
-
- when /^(-?(0[dbo])?[0-9_]+(\.[0-9_]+)?([eE]-?[0-9]+)?)(\.|::)([^.]*)$/
- # Numeric
- receiver = $1
- sep = $5
- message = Regexp.quote($6)
-
- begin
- candidates = eval(receiver, bind).methods.collect{|m| m.to_s}
- rescue Exception
- candidates = []
- end
- select_message(receiver, message, candidates, sep)
-
- when /^(-?0x[0-9a-fA-F_]+)(\.|::)([^.]*)$/
- # Numeric(0xFFFF)
- receiver = $1
- sep = $2
- message = Regexp.quote($3)
-
- begin
- candidates = eval(receiver, bind).methods.collect{|m| m.to_s}
- rescue Exception
- candidates = []
- end
- select_message(receiver, message, candidates, sep)
-
- when /^(\$[^.]*)$/
- # global var
- regmessage = Regexp.new(Regexp.quote($1))
- candidates = global_variables.collect{|m| m.to_s}.grep(regmessage)
-
-# when /^(\$?(\.?[^.]+)+)\.([^.]*)$/
-# when /^((\.?[^.]+)+)\.([^.]*)$/
-# when /^([^."].*)\.([^.]*)$/
- when /^([^."].*)(\.|::)([^.]*)$/
- # variable.func or func.func
- receiver = $1
- sep = $2
- message = Regexp.quote($3)
-
- gv = eval("global_variables", bind).collect{|m| m.to_s}
- lv = eval("local_variables", bind).collect{|m| m.to_s}
- cv = eval("self.class.constants", bind).collect{|m| m.to_s}
-
- if (gv | lv | cv).include?(receiver) or /^[A-Z]/ =~ receiver && /\./ !~ receiver
- # foo.func and foo is var. OR
- # foo::func and foo is var. OR
- # foo::Const and foo is var. OR
- # Foo::Bar.func
- begin
- candidates = []
- rec = eval(receiver, bind)
- if sep == "::" and rec.kind_of?(Module)
- candidates = rec.constants.collect{|m| m.to_s}
- end
- candidates |= rec.methods.collect{|m| m.to_s}
- rescue Exception
- candidates = []
- end
- else
- # func1.func2
- candidates = []
- ObjectSpace.each_object(Module){|m|
- begin
- name = m.name
- rescue Exception
- name = ""
- end
- begin
- next if name != "IRB::Context" and
- /^(IRB|SLex|RubyLex|RubyToken)/ =~ name
- rescue Exception
- next
- end
- candidates.concat m.instance_methods(false).collect{|x| x.to_s}
- }
- candidates.sort!
- candidates.uniq!
- end
- select_message(receiver, message, candidates, sep)
-
- when /^\.([^.]*)$/
- # unknown(maybe String)
-
- receiver = ""
- message = Regexp.quote($1)
-
- candidates = String.instance_methods(true).collect{|m| m.to_s}
- select_message(receiver, message, candidates)
-
- else
- candidates = eval("methods | private_methods | local_variables | self.class.constants", bind).collect{|m| m.to_s}
-
- (candidates|ReservedWords).grep(/^#{Regexp.quote(input)}/)
- end
- }
-
- Operators = ["%", "&", "*", "**", "+", "-", "/",
- "<", "<<", "<=", "<=>", "==", "===", "=~", ">", ">=", ">>",
- "[]", "[]=", "^", "!", "!=", "!~"]
-
- def self.select_message(receiver, message, candidates, sep = ".")
- candidates.grep(/^#{message}/).collect do |e|
- case e
- when /^[a-zA-Z_]/
- receiver + sep + e
- when /^[0-9]/
- when *Operators
- #receiver + " " + e
- end
- end
- end
- end
-end
-
-if Readline.respond_to?("basic_word_break_characters=")
-# Readline.basic_word_break_characters= " \t\n\"\\'`><=;|&{("
- Readline.basic_word_break_characters= " \t\n`><=;|&{("
-end
-Readline.completion_append_character = nil
-Readline.completion_proc = IRB::InputCompletor::CompletionProc
diff --git a/ruby_1_9_3/lib/irb/context.rb b/ruby_1_9_3/lib/irb/context.rb
deleted file mode 100644
index 61b519170d..0000000000
--- a/ruby_1_9_3/lib/irb/context.rb
+++ /dev/null
@@ -1,295 +0,0 @@
-#
-# irb/context.rb - irb context
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-require "irb/workspace"
-require "irb/inspector"
-
-module IRB
- class Context
- #
- # Arguments:
- # input_method: nil -- stdin or readline
- # String -- File
- # other -- using this as InputMethod
- #
- def initialize(irb, workspace = nil, input_method = nil, output_method = nil)
- @irb = irb
- if workspace
- @workspace = workspace
- else
- @workspace = WorkSpace.new
- end
- @thread = Thread.current if defined? Thread
-# @irb_level = 0
-
- # copy of default configuration
- @ap_name = IRB.conf[:AP_NAME]
- @rc = IRB.conf[:RC]
- @load_modules = IRB.conf[:LOAD_MODULES]
-
- @use_readline = IRB.conf[:USE_READLINE]
- @verbose = IRB.conf[:VERBOSE]
- @io = nil
-
- self.inspect_mode = IRB.conf[:INSPECT_MODE]
- self.math_mode = IRB.conf[:MATH_MODE] if IRB.conf[:MATH_MODE]
- self.use_tracer = IRB.conf[:USE_TRACER] if IRB.conf[:USE_TRACER]
- self.use_loader = IRB.conf[:USE_LOADER] if IRB.conf[:USE_LOADER]
- self.eval_history = IRB.conf[:EVAL_HISTORY] if IRB.conf[:EVAL_HISTORY]
-
- @ignore_sigint = IRB.conf[:IGNORE_SIGINT]
- @ignore_eof = IRB.conf[:IGNORE_EOF]
-
- @back_trace_limit = IRB.conf[:BACK_TRACE_LIMIT]
-
- self.prompt_mode = IRB.conf[:PROMPT_MODE]
-
- if IRB.conf[:SINGLE_IRB] or !defined?(JobManager)
- @irb_name = IRB.conf[:IRB_NAME]
- else
- @irb_name = "irb#"+IRB.JobManager.n_jobs.to_s
- end
- @irb_path = "(" + @irb_name + ")"
-
- case input_method
- when nil
- case use_readline?
- when nil
- if (defined?(ReadlineInputMethod) && STDIN.tty? &&
- IRB.conf[:PROMPT_MODE] != :INF_RUBY)
- @io = ReadlineInputMethod.new
- else
- @io = StdioInputMethod.new
- end
- when false
- @io = StdioInputMethod.new
- when true
- if defined?(ReadlineInputMethod)
- @io = ReadlineInputMethod.new
- else
- @io = StdioInputMethod.new
- end
- end
-
- when String
- @io = FileInputMethod.new(input_method)
- @irb_name = File.basename(input_method)
- @irb_path = input_method
- else
- @io = input_method
- end
- self.save_history = IRB.conf[:SAVE_HISTORY] if IRB.conf[:SAVE_HISTORY]
-
- if output_method
- @output_method = output_method
- else
- @output_method = StdioOutputMethod.new
- end
-
- @echo = IRB.conf[:ECHO]
- if @echo.nil?
- @echo = true
- end
- @debug_level = IRB.conf[:DEBUG_LEVEL]
- end
-
- def main
- @workspace.main
- end
-
- attr_reader :workspace_home
- attr_accessor :workspace
- attr_reader :thread
- attr_accessor :io
-
- attr_accessor :irb
- attr_accessor :ap_name
- attr_accessor :rc
- attr_accessor :load_modules
- attr_accessor :irb_name
- attr_accessor :irb_path
-
- attr_reader :use_readline
- attr_reader :inspect_mode
-
- attr_reader :prompt_mode
- attr_accessor :prompt_i
- attr_accessor :prompt_s
- attr_accessor :prompt_c
- attr_accessor :prompt_n
- attr_accessor :auto_indent_mode
- attr_accessor :return_format
-
- attr_accessor :ignore_sigint
- attr_accessor :ignore_eof
- attr_accessor :echo
- attr_accessor :verbose
- attr_reader :debug_level
-
- attr_accessor :back_trace_limit
-
- alias use_readline? use_readline
- alias rc? rc
- alias ignore_sigint? ignore_sigint
- alias ignore_eof? ignore_eof
- alias echo? echo
-
- def verbose?
- if @verbose.nil?
- if defined?(ReadlineInputMethod) && @io.kind_of?(ReadlineInputMethod)
- false
- elsif !STDIN.tty? or @io.kind_of?(FileInputMethod)
- true
- else
- false
- end
- else
- @verbose
- end
- end
-
- def prompting?
- verbose? || (STDIN.tty? && @io.kind_of?(StdioInputMethod) ||
- (defined?(ReadlineInputMethod) && @io.kind_of?(ReadlineInputMethod)))
- end
-
- attr_reader :last_value
-
- def set_last_value(value)
- @last_value = value
- @workspace.evaluate self, "_ = IRB.CurrentContext.last_value"
- end
-
- def prompt_mode=(mode)
- @prompt_mode = mode
- pconf = IRB.conf[:PROMPT][mode]
- @prompt_i = pconf[:PROMPT_I]
- @prompt_s = pconf[:PROMPT_S]
- @prompt_c = pconf[:PROMPT_C]
- @prompt_n = pconf[:PROMPT_N]
- @return_format = pconf[:RETURN]
- if ai = pconf.include?(:AUTO_INDENT)
- @auto_indent_mode = ai
- else
- @auto_indent_mode = IRB.conf[:AUTO_INDENT]
- end
- end
-
- def inspect?
- @inspect_mode.nil? or @inspect_mode
- end
-
- def file_input?
- @io.class == FileInputMethod
- end
-
- def inspect_mode=(opt)
-
- if i = INSPECTORS[opt]
- @inspect_mode = opt
- @inspect_method = i
- i.init
- else
- case opt
- when nil
- if INSPECTORS.keys_with_inspector(INSPECTORS[true]).include?(@inspect_mode)
- self.inspect_mode = false
- elsif INSPECTORS.keys_with_inspector(INSPECTORS[false]).include?(@inspect_mode)
- self.inspect_mode = true
- else
- puts "Can't switch inspect mode."
- return
- end
- when /^\s*\{.*\}\s*$/
- begin
- inspector = eval "proc#{opt}"
- rescue Exception
- puts "Can't switch inspect mode(#{opt})."
- return
- end
- self.inspect_mode = inspector
- when Proc
- self.inspect_mode = IRB::Inspector(opt)
- when Inspector
- prefix = "usr%d"
- i = 1
- while INSPECTORS[format(prefix, i)]; i += 1; end
- @inspect_mode = format(prefix, i)
- @inspect_method = opt
- INSPECTORS.def_inspector(format(prefix, i), @inspect_method)
- else
- puts "Can't switch inspect mode(#{opt})."
- return
- end
- end
- print "Switch to#{unless @inspect_mode; ' non';end} inspect mode.\n" if verbose?
- @inspect_mode
- end
-
-
- def use_readline=(opt)
- @use_readline = opt
- print "use readline module\n" if @use_readline
- end
-
- def debug_level=(value)
- @debug_level = value
- RubyLex.debug_level = value
- SLex.debug_level = value
- end
-
- def debug?
- @debug_level > 0
- end
-
- def evaluate(line, line_no)
- @line_no = line_no
- set_last_value(@workspace.evaluate(self, line, irb_path, line_no))
-# @workspace.evaluate("_ = IRB.conf[:MAIN_CONTEXT]._")
-# @_ = @workspace.evaluate(line, irb_path, line_no)
- end
-
- def inspect_last_value
- @inspect_method.inspect_value(@last_value)
- end
-
- alias __exit__ exit
- def exit(ret = 0)
- IRB.irb_exit(@irb, ret)
- end
-
- NOPRINTING_IVARS = ["@last_value"]
- NO_INSPECTING_IVARS = ["@irb", "@io"]
- IDNAME_IVARS = ["@prompt_mode"]
-
- alias __inspect__ inspect
- def inspect
- array = []
- for ivar in instance_variables.sort{|e1, e2| e1 <=> e2}
- ivar = ivar.to_s
- name = ivar.sub(/^@(.*)$/, '\1')
- val = instance_eval(ivar)
- case ivar
- when *NOPRINTING_IVARS
- array.push format("conf.%s=%s", name, "...")
- when *NO_INSPECTING_IVARS
- array.push format("conf.%s=%s", name, val.to_s)
- when *IDNAME_IVARS
- array.push format("conf.%s=:%s", name, val.id2name)
- else
- array.push format("conf.%s=%s", name, val.inspect)
- end
- end
- array.join("\n")
- end
- alias __to_s__ to_s
- alias to_s inspect
- end
-end
diff --git a/ruby_1_9_3/lib/irb/ext/change-ws.rb b/ruby_1_9_3/lib/irb/ext/change-ws.rb
deleted file mode 100644
index dea969d384..0000000000
--- a/ruby_1_9_3/lib/irb/ext/change-ws.rb
+++ /dev/null
@@ -1,61 +0,0 @@
-#
-# irb/ext/cb.rb -
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-module IRB
- class Context
-
- def home_workspace
- if defined? @home_workspace
- @home_workspace
- else
- @home_workspace = @workspace
- end
- end
-
- def change_workspace(*_main)
- if _main.empty?
- @workspace = home_workspace
- return main
- end
-
- @workspace = WorkSpace.new(_main[0])
-
- if !(class<<main;ancestors;end).include?(ExtendCommandBundle)
- main.extend ExtendCommandBundle
- end
- end
-
-# def change_binding(*_main)
-# back = @workspace
-# @workspace = WorkSpace.new(*_main)
-# unless _main.empty?
-# begin
-# main.extend ExtendCommandBundle
-# rescue
-# print "can't change binding to: ", main.inspect, "\n"
-# @workspace = back
-# return nil
-# end
-# end
-# @irb_level += 1
-# begin
-# catch(:SU_EXIT) do
-# @irb.eval_input
-# end
-# ensure
-# @irb_level -= 1
-# @workspace = back
-# end
-# end
-# alias change_workspace change_binding
- end
-end
-
diff --git a/ruby_1_9_3/lib/irb/ext/history.rb b/ruby_1_9_3/lib/irb/ext/history.rb
deleted file mode 100644
index 1495f9eb14..0000000000
--- a/ruby_1_9_3/lib/irb/ext/history.rb
+++ /dev/null
@@ -1,109 +0,0 @@
-#
-# history.rb -
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-module IRB
-
- class Context
-
- NOPRINTING_IVARS.push "@eval_history_values"
-
- alias _set_last_value set_last_value
-
- def set_last_value(value)
- _set_last_value(value)
-
-# @workspace.evaluate self, "_ = IRB.CurrentContext.last_value"
- if @eval_history #and !@eval_history_values.equal?(llv)
- @eval_history_values.push @line_no, @last_value
- @workspace.evaluate self, "__ = IRB.CurrentContext.instance_eval{@eval_history_values}"
- end
-
- @last_value
- end
-
- attr_reader :eval_history
- def eval_history=(no)
- if no
- if defined?(@eval_history) && @eval_history
- @eval_history_values.size(no)
- else
- @eval_history_values = History.new(no)
- IRB.conf[:__TMP__EHV__] = @eval_history_values
- @workspace.evaluate(self, "__ = IRB.conf[:__TMP__EHV__]")
- IRB.conf.delete(:__TMP_EHV__)
- end
- else
- @eval_history_values = nil
- end
- @eval_history = no
- end
- end
-
- class History
- @RCS_ID='-$Id$-'
-
- def initialize(size = 16)
- @size = size
- @contents = []
- end
-
- def size(size)
- if size != 0 && size < @size
- @contents = @contents[@size - size .. @size]
- end
- @size = size
- end
-
- def [](idx)
- begin
- if idx >= 0
- @contents.find{|no, val| no == idx}[1]
- else
- @contents[idx][1]
- end
- rescue NameError
- nil
- end
- end
-
- def push(no, val)
- @contents.push [no, val]
- @contents.shift if @size != 0 && @contents.size > @size
- end
-
- alias real_inspect inspect
-
- def inspect
- if @contents.empty?
- return real_inspect
- end
-
- unless (last = @contents.pop)[1].equal?(self)
- @contents.push last
- last = nil
- end
- str = @contents.collect{|no, val|
- if val.equal?(self)
- "#{no} ...self-history..."
- else
- "#{no} #{val.inspect}"
- end
- }.join("\n")
- if str == ""
- str = "Empty."
- end
- @contents.push last if last
- str
- end
- end
-end
-
-
diff --git a/ruby_1_9_3/lib/irb/ext/loader.rb b/ruby_1_9_3/lib/irb/ext/loader.rb
deleted file mode 100644
index 26a3203676..0000000000
--- a/ruby_1_9_3/lib/irb/ext/loader.rb
+++ /dev/null
@@ -1,119 +0,0 @@
-#
-# loader.rb -
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-
-module IRB
- class LoadAbort < Exception;end
-
- module IrbLoader
- @RCS_ID='-$Id$-'
-
- alias ruby_load load
- alias ruby_require require
-
- def irb_load(fn, priv = nil)
- path = search_file_from_ruby_path(fn)
- raise LoadError, "No such file to load -- #{fn}" unless path
-
- load_file(path, priv)
- end
-
- def search_file_from_ruby_path(fn)
- if /^#{Regexp.quote(File::Separator)}/ =~ fn
- return fn if File.exist?(fn)
- return nil
- end
-
- for path in $:
- if File.exist?(f = File.join(path, fn))
- return f
- end
- end
- return nil
- end
-
- def source_file(path)
- irb.suspend_name(path, File.basename(path)) do
- irb.suspend_input_method(FileInputMethod.new(path)) do
- |back_io|
- irb.signal_status(:IN_LOAD) do
- if back_io.kind_of?(FileInputMethod)
- irb.eval_input
- else
- begin
- irb.eval_input
- rescue LoadAbort
- print "load abort!!\n"
- end
- end
- end
- end
- end
- end
-
- def load_file(path, priv = nil)
- irb.suspend_name(path, File.basename(path)) do
-
- if priv
- ws = WorkSpace.new(Module.new)
- else
- ws = WorkSpace.new
- end
- irb.suspend_workspace(ws) do
- irb.suspend_input_method(FileInputMethod.new(path)) do
- |back_io|
- irb.signal_status(:IN_LOAD) do
-# p irb.conf
- if back_io.kind_of?(FileInputMethod)
- irb.eval_input
- else
- begin
- irb.eval_input
- rescue LoadAbort
- print "load abort!!\n"
- end
- end
- end
- end
- end
- end
- end
-
- def old
- back_io = @io
- back_path = @irb_path
- back_name = @irb_name
- back_scanner = @irb.scanner
- begin
- @io = FileInputMethod.new(path)
- @irb_name = File.basename(path)
- @irb_path = path
- @irb.signal_status(:IN_LOAD) do
- if back_io.kind_of?(FileInputMethod)
- @irb.eval_input
- else
- begin
- @irb.eval_input
- rescue LoadAbort
- print "load abort!!\n"
- end
- end
- end
- ensure
- @io = back_io
- @irb_name = back_name
- @irb_path = back_path
- @irb.scanner = back_scanner
- end
- end
- end
-end
-
diff --git a/ruby_1_9_3/lib/irb/ext/math-mode.rb b/ruby_1_9_3/lib/irb/ext/math-mode.rb
deleted file mode 100644
index 41be79841c..0000000000
--- a/ruby_1_9_3/lib/irb/ext/math-mode.rb
+++ /dev/null
@@ -1,36 +0,0 @@
-#
-# math-mode.rb -
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-require "mathn"
-
-module IRB
- class Context
- attr_reader :math_mode
- alias math? math_mode
-
- def math_mode=(opt)
- if @math_mode == true && opt == false
- IRB.fail CantReturnToNormalMode
- return
- end
-
- @math_mode = opt
- if math_mode
- main.extend Math
- print "start math mode\n" if verbose?
- end
- end
-
- def inspect?
- @inspect_mode.nil? && !@math_mode or @inspect_mode
- end
- end
-end
-
diff --git a/ruby_1_9_3/lib/irb/ext/multi-irb.rb b/ruby_1_9_3/lib/irb/ext/multi-irb.rb
deleted file mode 100644
index a8475b75cd..0000000000
--- a/ruby_1_9_3/lib/irb/ext/multi-irb.rb
+++ /dev/null
@@ -1,242 +0,0 @@
-#
-# irb/multi-irb.rb - multiple irb module
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-IRB.fail CantShiftToMultiIrbMode unless defined?(Thread)
-require "thread"
-
-module IRB
- # job management class
- class JobManager
- @RCS_ID='-$Id$-'
-
- def initialize
- # @jobs = [[thread, irb],...]
- @jobs = []
- @current_job = nil
- end
-
- attr_accessor :current_job
-
- def n_jobs
- @jobs.size
- end
-
- def thread(key)
- th, = search(key)
- th
- end
-
- def irb(key)
- _, irb = search(key)
- irb
- end
-
- def main_thread
- @jobs[0][0]
- end
-
- def main_irb
- @jobs[0][1]
- end
-
- def insert(irb)
- @jobs.push [Thread.current, irb]
- end
-
- def switch(key)
- th, irb = search(key)
- IRB.fail IrbAlreadyDead unless th.alive?
- IRB.fail IrbSwitchedToCurrentThread if th == Thread.current
- @current_job = irb
- th.run
- Thread.stop
- @current_job = irb(Thread.current)
- end
-
- def kill(*keys)
- for key in keys
- th, _ = search(key)
- IRB.fail IrbAlreadyDead unless th.alive?
- th.exit
- end
- end
-
- def search(key)
- job = case key
- when Integer
- @jobs[key]
- when Irb
- @jobs.find{|k, v| v.equal?(key)}
- when Thread
- @jobs.assoc(key)
- else
- @jobs.find{|k, v| v.context.main.equal?(key)}
- end
- IRB.fail NoSuchJob, key if job.nil?
- job
- end
-
- def delete(key)
- case key
- when Integer
- IRB.fail NoSuchJob, key unless @jobs[key]
- @jobs[key] = nil
- else
- catch(:EXISTS) do
- @jobs.each_index do
- |i|
- if @jobs[i] and (@jobs[i][0] == key ||
- @jobs[i][1] == key ||
- @jobs[i][1].context.main.equal?(key))
- @jobs[i] = nil
- throw :EXISTS
- end
- end
- IRB.fail NoSuchJob, key
- end
- end
- until assoc = @jobs.pop; end unless @jobs.empty?
- @jobs.push assoc
- end
-
- def inspect
- ary = []
- @jobs.each_index do
- |i|
- th, irb = @jobs[i]
- next if th.nil?
-
- if th.alive?
- if th.stop?
- t_status = "stop"
- else
- t_status = "running"
- end
- else
- t_status = "exited"
- end
- ary.push format("#%d->%s on %s (%s: %s)",
- i,
- irb.context.irb_name,
- irb.context.main,
- th,
- t_status)
- end
- ary.join("\n")
- end
- end
-
- @JobManager = JobManager.new
-
- def IRB.JobManager
- @JobManager
- end
-
- def IRB.CurrentContext
- IRB.JobManager.irb(Thread.current).context
- end
-
- # invoke multi-irb
- def IRB.irb(file = nil, *main)
- workspace = WorkSpace.new(*main)
- parent_thread = Thread.current
- Thread.start do
- begin
- irb = Irb.new(workspace, file)
- rescue
- print "Subirb can't start with context(self): ", workspace.main.inspect, "\n"
- print "return to main irb\n"
- Thread.pass
- Thread.main.wakeup
- Thread.exit
- end
- @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC]
- @JobManager.insert(irb)
- @JobManager.current_job = irb
- begin
- system_exit = false
- catch(:IRB_EXIT) do
- irb.eval_input
- end
- rescue SystemExit
- system_exit = true
- raise
- #fail
- ensure
- unless system_exit
- @JobManager.delete(irb)
- if @JobManager.current_job == irb
- if parent_thread.alive?
- @JobManager.current_job = @JobManager.irb(parent_thread)
- parent_thread.run
- else
- @JobManager.current_job = @JobManager.main_irb
- @JobManager.main_thread.run
- end
- end
- end
- end
- end
- Thread.stop
- @JobManager.current_job = @JobManager.irb(Thread.current)
- end
-
-# class Context
-# def set_last_value(value)
-# @last_value = value
-# @workspace.evaluate "_ = IRB.JobManager.irb(Thread.current).context.last_value"
-# if @eval_history #and !@__.equal?(@last_value)
-# @eval_history_values.push @line_no, @last_value
-# @workspace.evaluate "__ = IRB.JobManager.irb(Thread.current).context.instance_eval{@eval_history_values}"
-# end
-# @last_value
-# end
-# end
-
-# module ExtendCommand
-# def irb_context
-# IRB.JobManager.irb(Thread.current).context
-# end
-# # alias conf irb_context
-# end
-
- @CONF[:SINGLE_IRB_MODE] = false
- @JobManager.insert(@CONF[:MAIN_CONTEXT].irb)
- @JobManager.current_job = @CONF[:MAIN_CONTEXT].irb
-
- class Irb
- def signal_handle
- unless @context.ignore_sigint?
- print "\nabort!!\n" if @context.verbose?
- exit
- end
-
- case @signal_status
- when :IN_INPUT
- print "^C\n"
- IRB.JobManager.thread(self).raise RubyLex::TerminateLineInput
- when :IN_EVAL
- IRB.irb_abort(self)
- when :IN_LOAD
- IRB.irb_abort(self, LoadAbort)
- when :IN_IRB
- # ignore
- else
- # ignore other cases as well
- end
- end
- end
-
- trap("SIGINT") do
- @JobManager.current_job.signal_handle
- Thread.stop
- end
-
-end
diff --git a/ruby_1_9_3/lib/irb/ext/save-history.rb b/ruby_1_9_3/lib/irb/ext/save-history.rb
deleted file mode 100644
index f9c983ac11..0000000000
--- a/ruby_1_9_3/lib/irb/ext/save-history.rb
+++ /dev/null
@@ -1,97 +0,0 @@
-# save-history.rb -
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-require "readline"
-
-module IRB
- module HistorySavingAbility
- @RCS_ID='-$Id$-'
- end
-
- class Context
- def init_save_history
- unless (class<<@io;self;end).include?(HistorySavingAbility)
- @io.extend(HistorySavingAbility)
- end
- end
-
- def save_history
- IRB.conf[:SAVE_HISTORY]
- end
-
- def save_history=(val)
- IRB.conf[:SAVE_HISTORY] = val
- if val
- main_context = IRB.conf[:MAIN_CONTEXT]
- main_context = self unless main_context
- main_context.init_save_history
- end
- end
-
- def history_file
- IRB.conf[:HISTORY_FILE]
- end
-
- def history_file=(hist)
- IRB.conf[:HISTORY_FILE] = hist
- end
- end
-
- module HistorySavingAbility
- include Readline
-
-# def HistorySavingAbility.create_finalizer
-# proc do
-# if num = IRB.conf[:SAVE_HISTORY] and (num = num.to_i) > 0
-# if hf = IRB.conf[:HISTORY_FILE]
-# file = File.expand_path(hf)
-# end
-# file = IRB.rc_file("_history") unless file
-# open(file, 'w' ) do |f|
-# hist = HISTORY.to_a
-# f.puts(hist[-num..-1] || hist)
-# end
-# end
-# end
-# end
-
- def HistorySavingAbility.extended(obj)
-# ObjectSpace.define_finalizer(obj, HistorySavingAbility.create_finalizer)
- IRB.conf[:AT_EXIT].push proc{obj.save_history}
- obj.load_history
- obj
- end
-
- def load_history
- if history_file = IRB.conf[:HISTORY_FILE]
- history_file = File.expand_path(history_file)
- end
- history_file = IRB.rc_file("_history") unless history_file
- if File.exist?(history_file)
- open(history_file) do |f|
- f.each {|l| HISTORY << l.chomp}
- end
- end
- end
-
- def save_history
- if num = IRB.conf[:SAVE_HISTORY] and (num = num.to_i) > 0
- if history_file = IRB.conf[:HISTORY_FILE]
- history_file = File.expand_path(history_file)
- end
- history_file = IRB.rc_file("_history") unless history_file
- open(history_file, 'w' ) do |f|
- hist = HISTORY.to_a
- f.puts(hist[-num..-1] || hist)
- end
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/irb/ext/tracer.rb b/ruby_1_9_3/lib/irb/ext/tracer.rb
deleted file mode 100644
index 46a9d53a2e..0000000000
--- a/ruby_1_9_3/lib/irb/ext/tracer.rb
+++ /dev/null
@@ -1,60 +0,0 @@
-#
-# irb/lib/tracer.rb -
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-require "tracer"
-
-module IRB
-
- # initialize tracing function
- def IRB.initialize_tracer
- Tracer.verbose = false
- Tracer.add_filter {
- |event, file, line, id, binding, *rests|
- /^#{Regexp.quote(@CONF[:IRB_LIB_PATH])}/ !~ file and
- File::basename(file) != "irb.rb"
- }
- end
-
- class Context
- attr_reader :use_tracer
- alias use_tracer? use_tracer
-
- def use_tracer=(opt)
- if opt
- Tracer.set_get_line_procs(@irb_path) {
- |line_no, *rests|
- @io.line(line_no)
- }
- elsif !opt && @use_tracer
- Tracer.off
- end
- @use_tracer=opt
- end
- end
-
- class WorkSpace
- alias __evaluate__ evaluate
- def evaluate(context, statements, file = nil, line = nil)
- if context.use_tracer? && file != nil && line != nil
- Tracer.on
- begin
- __evaluate__(context, statements, file, line)
- ensure
- Tracer.off
- end
- else
- __evaluate__(context, statements, file || __FILE__, line || __LINE__)
- end
- end
- end
-
- IRB.initialize_tracer
-end
-
diff --git a/ruby_1_9_3/lib/irb/ext/use-loader.rb b/ruby_1_9_3/lib/irb/ext/use-loader.rb
deleted file mode 100644
index 64283b8989..0000000000
--- a/ruby_1_9_3/lib/irb/ext/use-loader.rb
+++ /dev/null
@@ -1,64 +0,0 @@
-#
-# use-loader.rb -
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-require "irb/cmd/load"
-require "irb/ext/loader"
-
-class Object
- alias __original__load__IRB_use_loader__ load
- alias __original__require__IRB_use_loader__ require
-end
-
-module IRB
- module ExtendCommandBundle
- def irb_load(*opts, &b)
- ExtendCommand::Load.execute(irb_context, *opts, &b)
- end
- def irb_require(*opts, &b)
- ExtendCommand::Require.execute(irb_context, *opts, &b)
- end
- end
-
- class Context
-
- IRB.conf[:USE_LOADER] = false
-
- def use_loader
- IRB.conf[:USE_LOADER]
- end
-
- alias use_loader? use_loader
-
- def use_loader=(opt)
-
- if IRB.conf[:USE_LOADER] != opt
- IRB.conf[:USE_LOADER] = opt
- if opt
- if !$".include?("irb/cmd/load")
- end
- (class<<@workspace.main;self;end).instance_eval {
- alias_method :load, :irb_load
- alias_method :require, :irb_require
- }
- else
- (class<<@workspace.main;self;end).instance_eval {
- alias_method :load, :__original__load__IRB_use_loader__
- alias_method :require, :__original__require__IRB_use_loader__
- }
- end
- end
- print "Switch to load/require#{unless use_loader; ' non';end} trace mode.\n" if verbose?
- opt
- end
- end
-end
-
-
diff --git a/ruby_1_9_3/lib/irb/ext/workspaces.rb b/ruby_1_9_3/lib/irb/ext/workspaces.rb
deleted file mode 100644
index 118ea598c0..0000000000
--- a/ruby_1_9_3/lib/irb/ext/workspaces.rb
+++ /dev/null
@@ -1,55 +0,0 @@
-#
-# push-ws.rb -
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-module IRB
- class Context
-
- def irb_level
- workspace_stack.size
- end
-
- def workspaces
- if defined? @workspaces
- @workspaces
- else
- @workspaces = []
- end
- end
-
- def push_workspace(*_main)
- if _main.empty?
- if workspaces.empty?
- print "No other workspace\n"
- return nil
- end
- ws = workspaces.pop
- workspaces.push @workspace
- @workspace = ws
- return workspaces
- end
-
- workspaces.push @workspace
- @workspace = WorkSpace.new(@workspace.binding, _main[0])
- if !(class<<main;ancestors;end).include?(ExtendCommandBundle)
- main.extend ExtendCommandBundle
- end
- end
-
- def pop_workspace
- if workspaces.empty?
- print "workspace stack empty\n"
- return
- end
- @workspace = workspaces.pop
- end
- end
-end
-
diff --git a/ruby_1_9_3/lib/irb/extend-command.rb b/ruby_1_9_3/lib/irb/extend-command.rb
deleted file mode 100644
index 190c49ae78..0000000000
--- a/ruby_1_9_3/lib/irb/extend-command.rb
+++ /dev/null
@@ -1,268 +0,0 @@
-#
-# irb/extend-command.rb - irb extend command
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-module IRB
- #
- # IRB extended command
- #
- module ExtendCommandBundle
- EXCB = ExtendCommandBundle
-
- NO_OVERRIDE = 0
- OVERRIDE_PRIVATE_ONLY = 0x01
- OVERRIDE_ALL = 0x02
-
- def irb_exit(ret = 0)
- irb_context.exit(ret)
- end
-
- def irb_context
- IRB.CurrentContext
- end
-
- @ALIASES = [
- [:context, :irb_context, NO_OVERRIDE],
- [:conf, :irb_context, NO_OVERRIDE],
- [:irb_quit, :irb_exit, OVERRIDE_PRIVATE_ONLY],
- [:exit, :irb_exit, OVERRIDE_PRIVATE_ONLY],
- [:quit, :irb_exit, OVERRIDE_PRIVATE_ONLY],
- ]
-
- @EXTEND_COMMANDS = [
- [:irb_current_working_workspace, :CurrentWorkingWorkspace, "irb/cmd/chws",
- [:irb_print_working_workspace, OVERRIDE_ALL],
- [:irb_cwws, OVERRIDE_ALL],
- [:irb_pwws, OVERRIDE_ALL],
-# [:irb_cww, OVERRIDE_ALL],
-# [:irb_pww, OVERRIDE_ALL],
- [:cwws, NO_OVERRIDE],
- [:pwws, NO_OVERRIDE],
-# [:cww, NO_OVERRIDE],
-# [:pww, NO_OVERRIDE],
- [:irb_current_working_binding, OVERRIDE_ALL],
- [:irb_print_working_binding, OVERRIDE_ALL],
- [:irb_cwb, OVERRIDE_ALL],
- [:irb_pwb, OVERRIDE_ALL],
-# [:cwb, NO_OVERRIDE],
-# [:pwb, NO_OVERRIDE]
- ],
- [:irb_change_workspace, :ChangeWorkspace, "irb/cmd/chws",
- [:irb_chws, OVERRIDE_ALL],
-# [:irb_chw, OVERRIDE_ALL],
- [:irb_cws, OVERRIDE_ALL],
-# [:irb_cw, OVERRIDE_ALL],
- [:chws, NO_OVERRIDE],
-# [:chw, NO_OVERRIDE],
- [:cws, NO_OVERRIDE],
-# [:cw, NO_OVERRIDE],
- [:irb_change_binding, OVERRIDE_ALL],
- [:irb_cb, OVERRIDE_ALL],
- [:cb, NO_OVERRIDE]],
-
- [:irb_workspaces, :Workspaces, "irb/cmd/pushws",
- [:workspaces, NO_OVERRIDE],
- [:irb_bindings, OVERRIDE_ALL],
- [:bindings, NO_OVERRIDE]],
- [:irb_push_workspace, :PushWorkspace, "irb/cmd/pushws",
- [:irb_pushws, OVERRIDE_ALL],
-# [:irb_pushw, OVERRIDE_ALL],
- [:pushws, NO_OVERRIDE],
-# [:pushw, NO_OVERRIDE],
- [:irb_push_binding, OVERRIDE_ALL],
- [:irb_pushb, OVERRIDE_ALL],
- [:pushb, NO_OVERRIDE]],
- [:irb_pop_workspace, :PopWorkspace, "irb/cmd/pushws",
- [:irb_popws, OVERRIDE_ALL],
-# [:irb_popw, OVERRIDE_ALL],
- [:popws, NO_OVERRIDE],
-# [:popw, NO_OVERRIDE],
- [:irb_pop_binding, OVERRIDE_ALL],
- [:irb_popb, OVERRIDE_ALL],
- [:popb, NO_OVERRIDE]],
-
- [:irb_load, :Load, "irb/cmd/load"],
- [:irb_require, :Require, "irb/cmd/load"],
- [:irb_source, :Source, "irb/cmd/load",
- [:source, NO_OVERRIDE]],
-
- [:irb, :IrbCommand, "irb/cmd/subirb"],
- [:irb_jobs, :Jobs, "irb/cmd/subirb",
- [:jobs, NO_OVERRIDE]],
- [:irb_fg, :Foreground, "irb/cmd/subirb",
- [:fg, NO_OVERRIDE]],
- [:irb_kill, :Kill, "irb/cmd/subirb",
- [:kill, OVERRIDE_PRIVATE_ONLY]],
-
- [:irb_help, :Help, "irb/cmd/help",
- [:help, NO_OVERRIDE]],
-
- ]
-
- def self.install_extend_commands
- for args in @EXTEND_COMMANDS
- def_extend_command(*args)
- end
- end
-
- # aliases = [commands_alias, flag], ...
- def self.def_extend_command(cmd_name, cmd_class, load_file = nil, *aliases)
- case cmd_class
- when Symbol
- cmd_class = cmd_class.id2name
- when String
- when Class
- cmd_class = cmd_class.name
- end
-
- if load_file
- line = __LINE__; eval %[
- def #{cmd_name}(*opts, &b)
- require "#{load_file}"
- arity = ExtendCommand::#{cmd_class}.instance_method(:execute).arity
- args = (1..(arity < 0 ? ~arity : arity)).map {|i| "arg" + i.to_s }
- args << "*opts" if arity < 0
- args << "&block"
- args = args.join(", ")
- line = __LINE__; eval %[
- def #{cmd_name}(\#{args})
- ExtendCommand::#{cmd_class}.execute(irb_context, \#{args})
- end
- ], nil, __FILE__, line
- send :#{cmd_name}, *opts, &b
- end
- ], nil, __FILE__, line
- else
- line = __LINE__; eval %[
- def #{cmd_name}(*opts, &b)
- ExtendCommand::#{cmd_class}.execute(irb_context, *opts, &b)
- end
- ], nil, __FILE__, line
- end
-
- for ali, flag in aliases
- @ALIASES.push [ali, cmd_name, flag]
- end
- end
-
- # override = {NO_OVERRIDE, OVERRIDE_PRIVATE_ONLY, OVERRIDE_ALL}
- def install_alias_method(to, from, override = NO_OVERRIDE)
- to = to.id2name unless to.kind_of?(String)
- from = from.id2name unless from.kind_of?(String)
-
- if override == OVERRIDE_ALL or
- (override == OVERRIDE_PRIVATE_ONLY) && !respond_to?(to) or
- (override == NO_OVERRIDE) && !respond_to?(to, true)
- target = self
- (class << self; self; end).instance_eval{
- if target.respond_to?(to, true) &&
- !target.respond_to?(EXCB.irb_original_method_name(to), true)
- alias_method(EXCB.irb_original_method_name(to), to)
- end
- alias_method to, from
- }
- else
- print "irb: warn: can't alias #{to} from #{from}.\n"
- end
- end
-
- def self.irb_original_method_name(method_name)
- "irb_" + method_name + "_org"
- end
-
- def self.extend_object(obj)
- unless (class << obj; ancestors; end).include?(EXCB)
- super
- for ali, com, flg in @ALIASES
- obj.install_alias_method(ali, com, flg)
- end
- end
- end
-
- install_extend_commands
- end
-
- # extension support for Context
- module ContextExtender
- CE = ContextExtender
-
- @EXTEND_COMMANDS = [
- [:eval_history=, "irb/ext/history.rb"],
- [:use_tracer=, "irb/ext/tracer.rb"],
- [:math_mode=, "irb/ext/math-mode.rb"],
- [:use_loader=, "irb/ext/use-loader.rb"],
- [:save_history=, "irb/ext/save-history.rb"],
- ]
-
- def self.install_extend_commands
- for args in @EXTEND_COMMANDS
- def_extend_command(*args)
- end
- end
-
- def self.def_extend_command(cmd_name, load_file, *aliases)
- line = __LINE__; Context.module_eval %[
- def #{cmd_name}(*opts, &b)
- Context.module_eval {remove_method(:#{cmd_name})}
- require "#{load_file}"
- send :#{cmd_name}, *opts, &b
- end
- for ali in aliases
- alias_method ali, cmd_name
- end
- ], __FILE__, line
- end
-
- CE.install_extend_commands
- end
-
- module MethodExtender
- def def_pre_proc(base_method, extend_method)
- base_method = base_method.to_s
- extend_method = extend_method.to_s
-
- alias_name = new_alias_name(base_method)
- module_eval %[
- alias_method alias_name, base_method
- def #{base_method}(*opts)
- send :#{extend_method}, *opts
- send :#{alias_name}, *opts
- end
- ]
- end
-
- def def_post_proc(base_method, extend_method)
- base_method = base_method.to_s
- extend_method = extend_method.to_s
-
- alias_name = new_alias_name(base_method)
- module_eval %[
- alias_method alias_name, base_method
- def #{base_method}(*opts)
- send :#{alias_name}, *opts
- send :#{extend_method}, *opts
- end
- ]
- end
-
- # return #{prefix}#{name}#{postfix}<num>
- def new_alias_name(name, prefix = "__alias_of__", postfix = "__")
- base_name = "#{prefix}#{name}#{postfix}"
- all_methods = instance_methods(true) + private_instance_methods(true)
- same_methods = all_methods.grep(/^#{Regexp.quote(base_name)}[0-9]*$/)
- return base_name if same_methods.empty?
- no = same_methods.size
- while !same_methods.include?(alias_name = base_name + no)
- no += 1
- end
- alias_name
- end
- end
-end
-
diff --git a/ruby_1_9_3/lib/irb/frame.rb b/ruby_1_9_3/lib/irb/frame.rb
deleted file mode 100644
index 8814b47a9d..0000000000
--- a/ruby_1_9_3/lib/irb/frame.rb
+++ /dev/null
@@ -1,66 +0,0 @@
-#
-# frame.rb -
-# $Release Version: 0.9$
-# $Revision$
-# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd)
-#
-# --
-#
-#
-#
-
-require "e2mmap"
-
-module IRB
- class Frame
- extend Exception2MessageMapper
- def_exception :FrameOverflow, "frame overflow"
- def_exception :FrameUnderflow, "frame underflow"
-
- INIT_STACK_TIMES = 3
- CALL_STACK_OFFSET = 3
-
- def initialize
- @frames = [TOPLEVEL_BINDING] * INIT_STACK_TIMES
- end
-
- def trace_func(event, file, line, id, binding)
- case event
- when 'call', 'class'
- @frames.push binding
- when 'return', 'end'
- @frames.pop
- end
- end
-
- def top(n = 0)
- bind = @frames[-(n + CALL_STACK_OFFSET)]
- Fail FrameUnderflow unless bind
- bind
- end
-
- def bottom(n = 0)
- bind = @frames[n]
- Fail FrameOverflow unless bind
- bind
- end
-
- # singleton functions
- def Frame.bottom(n = 0)
- @backtrace.bottom(n)
- end
-
- def Frame.top(n = 0)
- @backtrace.top(n)
- end
-
- def Frame.sender
- eval "self", @backtrace.top
- end
-
- @backtrace = Frame.new
- set_trace_func proc{|event, file, line, id, binding, klass|
- @backtrace.trace_func(event, file, line, id, binding)
- }
- end
-end
diff --git a/ruby_1_9_3/lib/irb/help.rb b/ruby_1_9_3/lib/irb/help.rb
deleted file mode 100644
index 4a308b6e46..0000000000
--- a/ruby_1_9_3/lib/irb/help.rb
+++ /dev/null
@@ -1,35 +0,0 @@
-#
-# irb/help.rb - print usage module
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-#
-# --
-#
-#
-#
-
-require 'irb/magic-file'
-
-module IRB
- def IRB.print_usage
- lc = IRB.conf[:LC_MESSAGES]
- path = lc.find("irb/help-message")
- space_line = false
- IRB::MagicFile.open(path){|f|
- f.each_line do |l|
- if /^\s*$/ =~ l
- lc.puts l unless space_line
- space_line = true
- next
- end
- space_line = false
-
- l.sub!(/#.*$/, "")
- next if /^\s*$/ =~ l
- lc.puts l
- end
- }
- end
-end
-
diff --git a/ruby_1_9_3/lib/irb/init.rb b/ruby_1_9_3/lib/irb/init.rb
deleted file mode 100644
index fce2df4f09..0000000000
--- a/ruby_1_9_3/lib/irb/init.rb
+++ /dev/null
@@ -1,305 +0,0 @@
-#
-# irb/init.rb - irb initialize module
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-module IRB
-
- # initialize config
- def IRB.setup(ap_path)
- IRB.init_config(ap_path)
- IRB.init_error
- IRB.parse_opts
- IRB.run_config
- IRB.load_modules
-
- unless @CONF[:PROMPT][@CONF[:PROMPT_MODE]]
- IRB.fail(UndefinedPromptMode, @CONF[:PROMPT_MODE])
- end
- end
-
- # @CONF default setting
- def IRB.init_config(ap_path)
- # class instance variables
- @TRACER_INITIALIZED = false
-
- # default configurations
- unless ap_path and @CONF[:AP_NAME]
- ap_path = File.join(File.dirname(File.dirname(__FILE__)), "irb.rb")
- end
- @CONF[:AP_NAME] = File::basename(ap_path, ".rb")
-
- @CONF[:IRB_NAME] = "irb"
- @CONF[:IRB_LIB_PATH] = File.dirname(__FILE__)
-
- @CONF[:RC] = true
- @CONF[:LOAD_MODULES] = []
- @CONF[:IRB_RC] = nil
-
- @CONF[:MATH_MODE] = false
- @CONF[:USE_READLINE] = false unless defined?(ReadlineInputMethod)
- @CONF[:INSPECT_MODE] = true
- @CONF[:USE_TRACER] = false
- @CONF[:USE_LOADER] = false
- @CONF[:IGNORE_SIGINT] = true
- @CONF[:IGNORE_EOF] = false
- @CONF[:ECHO] = nil
- @CONF[:VERBOSE] = nil
-
- @CONF[:EVAL_HISTORY] = nil
- @CONF[:SAVE_HISTORY] = nil
-
- @CONF[:BACK_TRACE_LIMIT] = 16
-
- @CONF[:PROMPT] = {
- :NULL => {
- :PROMPT_I => nil,
- :PROMPT_N => nil,
- :PROMPT_S => nil,
- :PROMPT_C => nil,
- :RETURN => "%s\n"
- },
- :DEFAULT => {
- :PROMPT_I => "%N(%m):%03n:%i> ",
- :PROMPT_N => "%N(%m):%03n:%i> ",
- :PROMPT_S => "%N(%m):%03n:%i%l ",
- :PROMPT_C => "%N(%m):%03n:%i* ",
- :RETURN => "=> %s\n"
- },
- :CLASSIC => {
- :PROMPT_I => "%N(%m):%03n:%i> ",
- :PROMPT_N => "%N(%m):%03n:%i> ",
- :PROMPT_S => "%N(%m):%03n:%i%l ",
- :PROMPT_C => "%N(%m):%03n:%i* ",
- :RETURN => "%s\n"
- },
- :SIMPLE => {
- :PROMPT_I => ">> ",
- :PROMPT_N => ">> ",
- :PROMPT_S => nil,
- :PROMPT_C => "?> ",
- :RETURN => "=> %s\n"
- },
- :INF_RUBY => {
- :PROMPT_I => "%N(%m):%03n:%i> ",
-# :PROMPT_N => "%N(%m):%03n:%i> ",
- :PROMPT_N => nil,
- :PROMPT_S => nil,
- :PROMPT_C => nil,
- :RETURN => "%s\n",
- :AUTO_INDENT => true
- },
- :XMP => {
- :PROMPT_I => nil,
- :PROMPT_N => nil,
- :PROMPT_S => nil,
- :PROMPT_C => nil,
- :RETURN => " ==>%s\n"
- }
- }
-
- @CONF[:PROMPT_MODE] = (STDIN.tty? ? :DEFAULT : :NULL)
- @CONF[:AUTO_INDENT] = false
-
- @CONF[:CONTEXT_MODE] = 3 # use binding in function on TOPLEVEL_BINDING
- @CONF[:SINGLE_IRB] = false
-
-# @CONF[:LC_MESSAGES] = "en"
- @CONF[:LC_MESSAGES] = Locale.new
-
- @CONF[:AT_EXIT] = []
-
- @CONF[:DEBUG_LEVEL] = 1
- end
-
- def IRB.init_error
- @CONF[:LC_MESSAGES].load("irb/error.rb")
- end
-
- FEATURE_IOPT_CHANGE_VERSION = "1.9.0"
-
- # option analyzing
- def IRB.parse_opts
- load_path = []
- while opt = ARGV.shift
- case opt
- when "-f"
- @CONF[:RC] = false
- when "-m"
- @CONF[:MATH_MODE] = true
- when "-d"
- $DEBUG = true
- $VERBOSE = true
- when "-w"
- $VERBOSE = true
- when /^-W(.+)?/
- opt = $1 || ARGV.shift
- case opt
- when "0"
- $VERBOSE = nil
- when "1"
- $VERBOSE = false
- else
- $VERBOSE = true
- end
- when /^-r(.+)?/
- opt = $1 || ARGV.shift
- @CONF[:LOAD_MODULES].push opt if opt
- when /^-I(.+)?/
- opt = $1 || ARGV.shift
- load_path.concat(opt.split(File::PATH_SEPARATOR)) if opt
- when '-U'
- set_encoding("UTF-8", "UTF-8")
- when /^-E(.+)?/, /^--encoding(?:=(.+))?/
- opt = $1 || ARGV.shift
- set_encoding(*opt.split(':', 2))
- when "--inspect"
- if /^-/ !~ ARGV.first
- @CONF[:INSPECT_MODE] = ARGV.shift
- else
- @CONF[:INSPECT_MODE] = true
- end
- when "--noinspect"
- @CONF[:INSPECT_MODE] = false
- when "--readline"
- @CONF[:USE_READLINE] = true
- when "--noreadline"
- @CONF[:USE_READLINE] = false
- when "--echo"
- @CONF[:ECHO] = true
- when "--noecho"
- @CONF[:ECHO] = false
- when "--verbose"
- @CONF[:VERBOSE] = true
- when "--noverbose"
- @CONF[:VERBOSE] = false
- when /^--prompt-mode(?:=(.+))?/, /^--prompt(?:=(.+))?/
- opt = $1 || ARGV.shift
- prompt_mode = opt.upcase.tr("-", "_").intern
- @CONF[:PROMPT_MODE] = prompt_mode
- when "--noprompt"
- @CONF[:PROMPT_MODE] = :NULL
- when "--inf-ruby-mode"
- @CONF[:PROMPT_MODE] = :INF_RUBY
- when "--sample-book-mode", "--simple-prompt"
- @CONF[:PROMPT_MODE] = :SIMPLE
- when "--tracer"
- @CONF[:USE_TRACER] = true
- when /^--back-trace-limit(?:=(.+))?/
- @CONF[:BACK_TRACE_LIMIT] = ($1 || ARGV.shift).to_i
- when /^--context-mode(?:=(.+))?/
- @CONF[:CONTEXT_MODE] = ($1 || ARGV.shift).to_i
- when "--single-irb"
- @CONF[:SINGLE_IRB] = true
- when /^--irb_debug=(?:=(.+))?/
- @CONF[:DEBUG_LEVEL] = ($1 || ARGV.shift).to_i
- when "-v", "--version"
- print IRB.version, "\n"
- exit 0
- when "-h", "--help"
- require "irb/help"
- IRB.print_usage
- exit 0
- when "--"
- if opt = ARGV.shift
- @CONF[:SCRIPT] = opt
- $0 = opt
- end
- break
- when /^-/
- IRB.fail UnrecognizedSwitch, opt
- else
- @CONF[:SCRIPT] = opt
- $0 = opt
- break
- end
- end
- if RUBY_VERSION >= FEATURE_IOPT_CHANGE_VERSION
- load_path.collect! do |path|
- /\A\.\// =~ path ? path : File.expand_path(path)
- end
- end
- $LOAD_PATH.unshift(*load_path)
-
- end
-
- # running config
- def IRB.run_config
- if @CONF[:RC]
- begin
- load rc_file
- rescue LoadError, Errno::ENOENT
- rescue # StandardError, ScriptError
- print "load error: #{rc_file}\n"
- print $!.class, ": ", $!, "\n"
- for err in $@[0, $@.size - 2]
- print "\t", err, "\n"
- end
- end
- end
- end
-
- IRBRC_EXT = "rc"
- def IRB.rc_file(ext = IRBRC_EXT)
- if !@CONF[:RC_NAME_GENERATOR]
- rc_file_generators do |rcgen|
- @CONF[:RC_NAME_GENERATOR] ||= rcgen
- if File.exist?(rcgen.call(IRBRC_EXT))
- @CONF[:RC_NAME_GENERATOR] = rcgen
- break
- end
- end
- end
- @CONF[:RC_NAME_GENERATOR].call ext
- end
-
- # enumerate possible rc-file base name generators
- def IRB.rc_file_generators
- if irbrc = ENV["IRBRC"]
- yield proc{|rc| rc == "rc" ? irbrc : irbrc+rc}
- end
- if home = ENV["HOME"]
- yield proc{|rc| home+"/.irb#{rc}"}
- end
- home = Dir.pwd
- yield proc{|rc| home+"/.irb#{rc}"}
- yield proc{|rc| home+"/irb#{rc.sub(/\A_?/, '.')}"}
- yield proc{|rc| home+"/_irb#{rc}"}
- yield proc{|rc| home+"/$irb#{rc}"}
- end
-
- # loading modules
- def IRB.load_modules
- for m in @CONF[:LOAD_MODULES]
- begin
- require m
- rescue LoadError => err
- warn err.backtrace[0] << ":#{err.class}: #{err}"
- end
- end
- end
-
-
- DefaultEncodings = Struct.new(:external, :internal)
- class << IRB
- private
- def set_encoding(extern, intern = nil)
- verbose, $VERBOSE = $VERBOSE, nil
- Encoding.default_external = extern unless extern.nil? || extern.empty?
- Encoding.default_internal = intern unless intern.nil? || intern.empty?
- @CONF[:ENCODINGS] = IRB::DefaultEncodings.new(extern, intern)
- [$stdin, $stdout, $stderr].each do |io|
- io.set_encoding(extern, intern)
- end
- @CONF[:LC_MESSAGES].instance_variable_set(:@encoding, extern)
- ensure
- $VERBOSE = verbose
- end
- end
-end
diff --git a/ruby_1_9_3/lib/irb/input-method.rb b/ruby_1_9_3/lib/irb/input-method.rb
deleted file mode 100644
index 7227df4ca0..0000000000
--- a/ruby_1_9_3/lib/irb/input-method.rb
+++ /dev/null
@@ -1,142 +0,0 @@
-#
-# irb/input-method.rb - input methods used irb
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-require 'irb/src_encoding'
-require 'irb/magic-file'
-
-module IRB
- #
- # InputMethod
- # StdioInputMethod
- # FileInputMethod
- # (ReadlineInputMethod)
- #
- STDIN_FILE_NAME = "(line)"
- class InputMethod
- @RCS_ID='-$Id$-'
-
- def initialize(file = STDIN_FILE_NAME)
- @file_name = file
- end
- attr_reader :file_name
-
- attr_accessor :prompt
-
- def gets
- IRB.fail NotImplementedError, "gets"
- end
- public :gets
-
- def readable_atfer_eof?
- false
- end
- end
-
- class StdioInputMethod < InputMethod
- def initialize
- super
- @line_no = 0
- @line = []
- @stdin = IO.open(STDIN.to_i, :external_encoding => IRB.conf[:LC_MESSAGES].encoding, :internal_encoding => "-")
- @stdout = IO.open(STDOUT.to_i, 'w', :external_encoding => IRB.conf[:LC_MESSAGES].encoding, :internal_encoding => "-")
- end
-
- def gets
- print @prompt
- line = @stdin.gets
- @line[@line_no += 1] = line
- end
-
- def eof?
- @stdin.eof?
- end
-
- def readable_atfer_eof?
- true
- end
-
- def line(line_no)
- @line[line_no]
- end
-
- def encoding
- @stdin.external_encoding
- end
- end
-
- class FileInputMethod < InputMethod
- def initialize(file)
- super
- @io = IRB::MagicFile.open(file)
- end
- attr_reader :file_name
-
- def eof?
- @io.eof?
- end
-
- def gets
- print @prompt
- l = @io.gets
-# print @prompt, l
- l
- end
-
- def encoding
- @io.external_encoding
- end
- end
-
- begin
- require "readline"
- class ReadlineInputMethod < InputMethod
- include Readline
- def initialize
- super
-
- @line_no = 0
- @line = []
- @eof = false
-
- @stdin = IO.open(STDIN.to_i, :external_encoding => IRB.conf[:LC_MESSAGES].encoding, :internal_encoding => "-")
- @stdout = IO.open(STDOUT.to_i, 'w', :external_encoding => IRB.conf[:LC_MESSAGES].encoding, :internal_encoding => "-")
- end
-
- def gets
- Readline.input = @stdin
- Readline.output = @stdout
- if l = readline(@prompt, false)
- HISTORY.push(l) if !l.empty?
- @line[@line_no += 1] = l + "\n"
- else
- @eof = true
- l
- end
- end
-
- def eof?
- @eof
- end
-
- def readable_atfer_eof?
- true
- end
-
- def line(line_no)
- @line[line_no]
- end
-
- def encoding
- @stdin.external_encoding
- end
- end
- rescue LoadError
- end
-end
diff --git a/ruby_1_9_3/lib/irb/inspector.rb b/ruby_1_9_3/lib/irb/inspector.rb
deleted file mode 100644
index aefe077f37..0000000000
--- a/ruby_1_9_3/lib/irb/inspector.rb
+++ /dev/null
@@ -1,109 +0,0 @@
-#
-# irb/inspector.rb - inspect methods
-# $Release Version: 0.9.6$
-# $Revision: 1.19 $
-# $Date: 2002/06/11 07:51:31 $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-module IRB
-
- def IRB::Inspector(inspect, init = nil)
- Inspector.new(inspect, init)
- end
-
- class Inspector
- def initialize(inspect_proc, init_proc = nil)
- @init = init_proc
- @inspect = inspect_proc
- end
-
- def init
- @init.call if @init
- end
-
- def inspect_value(v)
- @inspect.call(v)
- end
- end
-
- INSPECTORS = {}
-
- def INSPECTORS.keys_with_inspector(inspector)
- select{|k,v| v == inspector}.collect{|k, v| k}
- end
-
- # ex)
- # INSPECTORS.def_inspector(key, init_p=nil){|v| v.inspect}
- # INSPECTORS.def_inspector([key1,..], init_p=nil){|v| v.inspect}
- # INSPECTORS.def_inspector(key, inspector)
- # INSPECTORS.def_inspector([key1,...], inspector)
-
- def INSPECTORS.def_inspector(key, arg=nil, &block)
-# if !block_given?
-# case arg
-# when nil, Proc
-# inspector = IRB::Inspector(init_p)
-# when Inspector
-# inspector = init_p
-# else
-# IRB.Raise IllegalParameter, init_p
-# end
-# init_p = nil
-# else
-# inspector = IRB::Inspector(block, init_p)
-# end
-
- if block_given?
- inspector = IRB::Inspector(block, arg)
- else
- inspector = arg
- end
-
- case key
- when Array
- for k in key
- def_inspector(k, inspector)
- end
- when Symbol
- self[key] = inspector
- self[key.to_s] = inspector
- when String
- self[key] = inspector
- self[key.intern] = inspector
- else
- self[key] = inspector
- end
- end
-
- INSPECTORS.def_inspector([false, :to_s, :raw]){|v| v.to_s}
- INSPECTORS.def_inspector([true, :p, :inspect]){|v|
- begin
- v.inspect
- rescue NoMethodError
- puts "(Object doesn't support #inspect)"
- end
- }
- INSPECTORS.def_inspector([:pp, :pretty_inspect], proc{require "pp"}){|v| v.pretty_inspect.chomp}
- INSPECTORS.def_inspector([:yaml, :YAML], proc{require "yaml"}){|v|
- begin
- YAML.dump(v)
- rescue
- puts "(can't dump yaml. use inspect)"
- v.inspect
- end
- }
-
- INSPECTORS.def_inspector([:marshal, :Marshal, :MARSHAL, Marshal]){|v|
- Marshal.dump(v)
- }
-end
-
-
-
-
-
diff --git a/ruby_1_9_3/lib/irb/lc/error.rb b/ruby_1_9_3/lib/irb/lc/error.rb
deleted file mode 100644
index 742821e3af..0000000000
--- a/ruby_1_9_3/lib/irb/lc/error.rb
+++ /dev/null
@@ -1,29 +0,0 @@
-#
-# irb/lc/error.rb -
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-require "e2mmap"
-
-module IRB
-
- # exceptions
- extend Exception2MessageMapper
- def_exception :UnrecognizedSwitch, "Unrecognized switch: %s"
- def_exception :NotImplementedError, "Need to define `%s'"
- def_exception :CantReturnToNormalMode, "Can't return to normal mode."
- def_exception :IllegalParameter, "Invalid parameter(%s)."
- def_exception :IrbAlreadyDead, "Irb is already dead."
- def_exception :IrbSwitchedToCurrentThread, "Switched to current thread."
- def_exception :NoSuchJob, "No such job(%s)."
- def_exception :CantShiftToMultiIrbMode, "Can't shift to multi irb mode."
- def_exception :CantChangeBinding, "Can't change binding to (%s)."
- def_exception :UndefinedPromptMode, "Undefined prompt mode(%s)."
-
-end
-
diff --git a/ruby_1_9_3/lib/irb/lc/help-message b/ruby_1_9_3/lib/irb/lc/help-message
deleted file mode 100644
index c01cdaab93..0000000000
--- a/ruby_1_9_3/lib/irb/lc/help-message
+++ /dev/null
@@ -1,40 +0,0 @@
-# -*- coding: US-ASCII -*-
-#
-# irb/lc/help-message.rb -
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-Usage: irb.rb [options] [programfile] [arguments]
- -f Suppress read of ~/.irbrc
- -m Bc mode (load mathn, fraction or matrix are available)
- -d Set $DEBUG to true (same as `ruby -d')
- -r load-module Same as `ruby -r'
- -I path Specify $LOAD_PATH directory
- -U Same as `ruby -U`
- -E enc Same as `ruby -E`
- -w Same as `ruby -w`
- -W[level=2] Same as `ruby -W`
- --inspect Use `inspect' for output (default except for bc mode)
- --noinspect Don't use inspect for output
- --readline Use Readline extension module
- --noreadline Don't use Readline extension module
- --prompt prompt-mode
- --prompt-mode prompt-mode
- Switch prompt mode. Pre-defined prompt modes are
- `default', `simple', `xmp' and `inf-ruby'
- --inf-ruby-mode Use prompt appropriate for inf-ruby-mode on emacs.
- Suppresses --readline.
- --simple-prompt Simple prompt mode
- --noprompt No prompt mode
- --tracer Display trace for each execution of commands.
- --back-trace-limit n
- Display backtrace top n and tail n. The default
- value is 16.
- --irb_debug n Set internal debug level to n (not for popular use)
- -v, --version Print the version of irb
-# vim:fileencoding=us-ascii
diff --git a/ruby_1_9_3/lib/irb/lc/ja/encoding_aliases.rb b/ruby_1_9_3/lib/irb/lc/ja/encoding_aliases.rb
deleted file mode 100644
index a713dff4be..0000000000
--- a/ruby_1_9_3/lib/irb/lc/ja/encoding_aliases.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-module IRB
- class Locale
- @@legacy_encoding_alias_map = {
- 'ujis' => Encoding::EUC_JP,
- 'euc' => Encoding::EUC_JP
- }.freeze
- end
-end
diff --git a/ruby_1_9_3/lib/irb/lc/ja/error.rb b/ruby_1_9_3/lib/irb/lc/ja/error.rb
deleted file mode 100644
index 9a7670f459..0000000000
--- a/ruby_1_9_3/lib/irb/lc/ja/error.rb
+++ /dev/null
@@ -1,27 +0,0 @@
-# -*- coding: utf-8 -*-
-# irb/lc/ja/error.rb -
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-require "e2mmap"
-
-module IRB
- # exceptions
- extend Exception2MessageMapper
- def_exception :UnrecognizedSwitch, 'スイッãƒ(%s)ãŒåˆ†ã‚Šã¾ã›ã‚“'
- def_exception :NotImplementedError, '`%s\'ã®å®šç¾©ãŒå¿…è¦ã§ã™'
- def_exception :CantReturnToNormalMode, 'Normalモードã«æˆ»ã‚Œã¾ã›ã‚“.'
- def_exception :IllegalParameter, 'パラメータ(%s)ãŒé–“é•ã£ã¦ã„ã¾ã™.'
- def_exception :IrbAlreadyDead, 'Irbã¯æ—¢ã«æ­»ã‚“ã§ã„ã¾ã™.'
- def_exception :IrbSwitchedToCurrentThread, 'カレントスレッドã«åˆ‡ã‚Šæ›¿ã‚ã‚Šã¾ã—ãŸ.'
- def_exception :NoSuchJob, 'ãã®ã‚ˆã†ãªã‚¸ãƒ§ãƒ–(%s)ã¯ã‚ã‚Šã¾ã›ã‚“.'
- def_exception :CantShiftToMultiIrbMode, 'multi-irb modeã«ç§»ã‚Œã¾ã›ã‚“.'
- def_exception :CantChangeBinding, 'ãƒã‚¤ãƒ³ãƒ‡ã‚£ãƒ³ã‚°(%s)ã«å¤‰æ›´ã§ãã¾ã›ã‚“.'
- def_exception :UndefinedPromptMode, 'プロンプトモード(%s)ã¯å®šç¾©ã•ã‚Œã¦ã„ã¾ã›ã‚“.'
-end
-# vim:fileencoding=utf-8
diff --git a/ruby_1_9_3/lib/irb/lc/ja/help-message b/ruby_1_9_3/lib/irb/lc/ja/help-message
deleted file mode 100644
index 57e8f23edf..0000000000
--- a/ruby_1_9_3/lib/irb/lc/ja/help-message
+++ /dev/null
@@ -1,41 +0,0 @@
-# -*- coding: utf-8 -*-
-# irb/lc/ja/help-message.rb -
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-Usage: irb.rb [options] [programfile] [arguments]
- -f ~/.irbrc を読ã¿è¾¼ã¾ãªã„.
- -m bcモード(分数, 行列ã®è¨ˆç®—ãŒã§ãã‚‹)
- -d $DEBUG ã‚’trueã«ã™ã‚‹(ruby -d ã¨åŒã˜)
- -r load-module ruby -r ã¨åŒã˜.
- -I path $LOAD_PATH ã« path を追加ã™ã‚‹.
- -U ruby -U ã¨åŒã˜.
- -E enc ruby -E ã¨åŒã˜.
- -w ruby -w ã¨åŒã˜.
- -W[level=2] ruby -W ã¨åŒã˜.
- --inspect çµæžœå‡ºåŠ›ã«inspectを用ã„ã‚‹(bcモード以外ã¯ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆ).
- --noinspect çµæžœå‡ºåŠ›ã«inspectを用ã„ãªã„.
- --readline readlineライブラリを利用ã™ã‚‹.
- --noreadline readlineライブラリを利用ã—ãªã„.
- --prompt prompt-mode/--prompt-mode prompt-mode
- プロンプトモードを切替ãˆã¾ã™. ç¾åœ¨å®šç¾©ã•ã‚Œã¦ã„るプ
- ロンプトモードã¯, default, simple, xmp, inf-rubyãŒ
- 用æ„ã•ã‚Œã¦ã„ã¾ã™.
- --inf-ruby-mode emacsã®inf-ruby-mode用ã®ãƒ—ロンプト表示を行ãªã†. 特
- ã«æŒ‡å®šãŒãªã„é™ã‚Š, readlineライブラリã¯ä½¿ã‚ãªããªã‚‹.
- --simple-prompt éžå¸¸ã«ã‚·ãƒ³ãƒ—ルãªãƒ—ロンプトを用ã„るモードã§ã™.
- --noprompt プロンプト表示を行ãªã‚ãªã„.
- --tracer コマンド実行時ã«ãƒˆãƒ¬ãƒ¼ã‚¹ã‚’è¡Œãªã†.
- --back-trace-limit n
- ãƒãƒƒã‚¯ãƒˆãƒ¬ãƒ¼ã‚¹è¡¨ç¤ºã‚’ãƒãƒƒã‚¯ãƒˆãƒ¬ãƒ¼ã‚¹ã®é ­ã‹ã‚‰ n, 後ã‚
- ã‹ã‚‰nã ã‘è¡Œãªã†. デフォルトã¯16
- --irb_debug n irbã®ãƒ‡ãƒãƒƒã‚°ãƒ‡ãƒãƒƒã‚°ãƒ¬ãƒ™ãƒ«ã‚’nã«è¨­å®šã™ã‚‹(利用ã—ãª
- ã„æ–¹ãŒç„¡é›£ã§ã—ょã†).
- -v, --version irbã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³ã‚’表示ã™ã‚‹
-
-# vim:fileencoding=utf-8
diff --git a/ruby_1_9_3/lib/irb/locale.rb b/ruby_1_9_3/lib/irb/locale.rb
deleted file mode 100644
index 7781006da4..0000000000
--- a/ruby_1_9_3/lib/irb/locale.rb
+++ /dev/null
@@ -1,182 +0,0 @@
-#
-# irb/locale.rb - internationalization module
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-module IRB
- class Locale
- @RCS_ID='-$Id$-'
-
- LOCALE_NAME_RE = %r[
- (?<language>[[:alpha:]]{2,3})
- (?:_ (?<territory>[[:alpha:]]{2,3}) )?
- (?:\. (?<codeset>[^@]+) )?
- (?:@ (?<modifier>.*) )?
- ]x
- LOCALE_DIR = "/lc/"
-
- @@legacy_encoding_alias_map = {}.freeze
-
- def initialize(locale = nil)
- @lang = @territory = @encoding_name = @modifier = nil
- @locale = locale || ENV["IRB_LANG"] || ENV["LC_MESSAGES"] || ENV["LC_ALL"] || ENV["LANG"] || "C"
- if m = LOCALE_NAME_RE.match(@locale)
- @lang, @territory, @encoding_name, @modifier = m[:language], m[:territory], m[:codeset], m[:modifier]
-
- if @encoding_name
- begin load 'irb/encoding_aliases.rb'; rescue LoadError; end
- if @encoding = @@legacy_encoding_alias_map[@encoding_name]
- warn "%s is obsolete. use %s" % ["#{@lang}_#{@territory}.#{@encoding_name}", "#{@lang}_#{@territory}.#{@encoding.name}"]
- end
- @encoding = Encoding.find(@encoding_name) rescue nil
- end
- end
- @encoding ||= (Encoding.find('locale') rescue Encoding::ASCII_8BIT)
- end
-
- attr_reader :lang, :territory, :encoding, :modifieer
-
- def String(mes)
- mes = super(mes)
- if @encoding
- mes.encode(@encoding, undef: :replace)
- else
- mes
- end
- end
-
- def format(*opts)
- String(super(*opts))
- end
-
- def gets(*rs)
- String(super(*rs))
- end
-
- def readline(*rs)
- String(super(*rs))
- end
-
- def print(*opts)
- ary = opts.collect{|opt| String(opt)}
- super(*ary)
- end
-
- def printf(*opts)
- s = format(*opts)
- print s
- end
-
- def puts(*opts)
- ary = opts.collect{|opt| String(opt)}
- super(*ary)
- end
-
- def require(file, priv = nil)
- rex = Regexp.new("lc/#{Regexp.quote(file)}\.(so|o|sl|rb)?")
- return false if $".find{|f| f =~ rex}
-
- case file
- when /\.rb$/
- begin
- load(file, priv)
- $".push file
- return true
- rescue LoadError
- end
- when /\.(so|o|sl)$/
- return super
- end
-
- begin
- load(f = file + ".rb")
- $".push f #"
- return true
- rescue LoadError
- return ruby_require(file)
- end
- end
-
- alias toplevel_load load
-
- def load(file, priv=nil)
- found = find(file)
- if found
- return real_load(found, priv)
- else
- raise LoadError, "No such file to load -- #{file}"
- end
- end
-
- def find(file , paths = $:)
- dir = File.dirname(file)
- dir = "" if dir == "."
- base = File.basename(file)
-
- if dir.start_with?('/')
- return each_localized_path(dir, base).find{|full_path| File.readable? full_path}
- else
- return search_file(paths, dir, base)
- end
- end
-
- private
- def real_load(path, priv)
- src = MagicFile.open(path){|f| f.read}
- if priv
- eval("self", TOPLEVEL_BINDING).extend(Module.new {eval(src, nil, path)})
- else
- eval(src, TOPLEVEL_BINDING, path)
- end
- end
-
- # @param paths load paths in which IRB find a localized file.
- # @param dir directory
- # @param file basename to be localized
- #
- # typically, for the parameters and a <path> in paths, it searches
- # <path>/<dir>/<locale>/<file>
- def search_file(lib_paths, dir, file)
- each_localized_path(dir, file) do |lc_path|
- lib_paths.each do |libpath|
- full_path = File.join(libpath, lc_path)
- return full_path if File.readable?(full_path)
- end
- redo if defined?(Gem) and Gem.try_activate(lc_path)
- end
- nil
- end
-
- def each_localized_path(dir, file)
- return enum_for(:each_localized_path) unless block_given?
- each_sublocale do |lc|
- yield lc.nil? ? File.join(dir, LOCALE_DIR, file) : File.join(dir, LOCALE_DIR, lc, file)
- end
- end
-
- def each_sublocale
- if @lang
- if @territory
- if @encoding_name
- yield "#{@lang}_#{@territory}.#{@encoding_name}@#{@modifier}" if @modifier
- yield "#{@lang}_#{@territory}.#{@encoding_name}"
- end
- yield "#{@lang}_#{@territory}@#{@modifier}" if @modifier
- yield "#{@lang}_#{@territory}"
- end
- if @encoding_name
- yield "#{@lang}.#{@encoding_name}@#{@modifier}" if @modifier
- yield "#{@lang}.#{@encoding_name}"
- end
- yield "#{@lang}@#{@modifier}" if @modifier
- yield "#{@lang}"
- end
- yield nil
- end
- end
-end
diff --git a/ruby_1_9_3/lib/irb/magic-file.rb b/ruby_1_9_3/lib/irb/magic-file.rb
deleted file mode 100644
index 339ed60b6b..0000000000
--- a/ruby_1_9_3/lib/irb/magic-file.rb
+++ /dev/null
@@ -1,37 +0,0 @@
-module IRB
- class << (MagicFile = Object.new)
- # see parser_magic_comment in parse.y
- ENCODING_SPEC_RE = %r"coding\s*[=:]\s*([[:alnum:]\-_]+)"
-
- def open(path)
- io = File.open(path, 'rb')
- line = io.gets
- line = io.gets if line[0,2] == "#!"
- encoding = detect_encoding(line)
- internal_encoding = encoding
- encoding ||= default_src_encoding
- io.rewind
- io.set_encoding(encoding, internal_encoding)
-
- if block_given?
- begin
- return (yield io)
- ensure
- io.close
- end
- else
- return io
- end
- end
-
- private
- def detect_encoding(line)
- return unless line[0] == ?#
- line = line[1..-1]
- line = $1 if line[/-\*-\s*(.*?)\s*-*-$/]
- return nil unless ENCODING_SPEC_RE =~ line
- encoding = $1
- return encoding.sub(/-(?:mac|dos|unix)/i, '')
- end
- end
-end
diff --git a/ruby_1_9_3/lib/irb/notifier.rb b/ruby_1_9_3/lib/irb/notifier.rb
deleted file mode 100644
index d20679da4a..0000000000
--- a/ruby_1_9_3/lib/irb/notifier.rb
+++ /dev/null
@@ -1,144 +0,0 @@
-#
-# notifier.rb - output methods used by irb
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-require "e2mmap"
-require "irb/output-method"
-
-module IRB
- module Notifier
- extend Exception2MessageMapper
- def_exception :ErrUndefinedNotifier,
- "undefined notifier level: %d is specified"
- def_exception :ErrUnrecognizedLevel,
- "unrecognized notifier level: %s is specified"
-
- def def_notifier(prefix = "", output_method = StdioOutputMethod.new)
- CompositeNotifier.new(prefix, output_method)
- end
- module_function :def_notifier
-
- class AbstractNotifier
- def initialize(prefix, base_notifier)
- @prefix = prefix
- @base_notifier = base_notifier
- end
-
- attr_reader :prefix
-
- def notify?
- true
- end
-
- def print(*opts)
- @base_notifier.print prefix, *opts if notify?
- end
-
- def printn(*opts)
- @base_notifier.printn prefix, *opts if notify?
- end
-
- def printf(format, *opts)
- @base_notifier.printf(prefix + format, *opts) if notify?
- end
-
- def puts(*objs)
- if notify?
- @base_notifier.puts(*objs.collect{|obj| prefix + obj.to_s})
- end
- end
-
- def pp(*objs)
- if notify?
- @base_notifier.ppx @prefix, *objs
- end
- end
-
- def ppx(prefix, *objs)
- if notify?
- @base_notifier.ppx @prefix+prefix, *objs
- end
- end
-
- def exec_if
- yield(@base_notifier) if notify?
- end
- end
-
- class CompositeNotifier<AbstractNotifier
- def initialize(prefix, base_notifier)
- super
-
- @notifiers = [D_NOMSG]
- @level_notifier = D_NOMSG
- end
-
- attr_reader :notifiers
-
- def def_notifier(level, prefix = "")
- notifier = LeveledNotifier.new(self, level, prefix)
- @notifiers[level] = notifier
- notifier
- end
-
- attr_reader :level_notifier
- alias level level_notifier
-
- def level_notifier=(value)
- case value
- when AbstractNotifier
- @level_notifier = value
- when Integer
- l = @notifiers[value]
- Notifier.Raise ErrUndefinedNotifer, value unless l
- @level_notifier = l
- else
- Notifier.Raise ErrUnrecognizedLevel, value unless l
- end
- end
-
- alias level= level_notifier=
- end
-
- class LeveledNotifier<AbstractNotifier
- include Comparable
-
- def initialize(base, level, prefix)
- super(prefix, base)
-
- @level = level
- end
-
- attr_reader :level
-
- def <=>(other)
- @level <=> other.level
- end
-
- def notify?
- @base_notifier.level >= self
- end
- end
-
- class NoMsgNotifier<LeveledNotifier
- def initialize
- @base_notifier = nil
- @level = 0
- @prefix = ""
- end
-
- def notify?
- false
- end
- end
-
- D_NOMSG = NoMsgNotifier.new
- end
-end
diff --git a/ruby_1_9_3/lib/irb/output-method.rb b/ruby_1_9_3/lib/irb/output-method.rb
deleted file mode 100644
index 9cccda1c6a..0000000000
--- a/ruby_1_9_3/lib/irb/output-method.rb
+++ /dev/null
@@ -1,69 +0,0 @@
-#
-# output-method.rb - output methods used by irb
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-require "e2mmap"
-
-module IRB
- # OutputMethod
- # StdioOutputMethod
-
- class OutputMethod
- @RCS_ID='-$Id$-'
-
- def print(*opts)
- IRB.fail NotImplementError, "print"
- end
-
- def printn(*opts)
- print opts.join(" "), "\n"
- end
-
- # extend printf
- def printf(format, *opts)
- if /(%*)%I/ =~ format
- format, opts = parse_printf_format(format, opts)
- end
- print sprintf(format, *opts)
- end
-
- # %
- # <flag> [#0- +]
- # <minimum field width> (\*|\*[1-9][0-9]*\$|[1-9][0-9]*)
- # <precision>.(\*|\*[1-9][0-9]*\$|[1-9][0-9]*|)?
- # #<length modifier>(hh|h|l|ll|L|q|j|z|t)
- # <conversion specifier>[diouxXeEfgGcsb%]
- def parse_printf_format(format, opts)
- return format, opts if $1.size % 2 == 1
- end
-
- def puts(*objs)
- for obj in objs
- print(*obj)
- print "\n"
- end
- end
-
- def pp(*objs)
- puts(*objs.collect{|obj| obj.inspect})
- end
-
- def ppx(prefix, *objs)
- puts(*objs.collect{|obj| prefix+obj.inspect})
- end
-
- end
-
- class StdioOutputMethod<OutputMethod
- def print(*opts)
- STDOUT.print(*opts)
- end
- end
-end
diff --git a/ruby_1_9_3/lib/irb/ruby-lex.rb b/ruby_1_9_3/lib/irb/ruby-lex.rb
deleted file mode 100644
index 2a23534bf3..0000000000
--- a/ruby_1_9_3/lib/irb/ruby-lex.rb
+++ /dev/null
@@ -1,1187 +0,0 @@
-#
-# irb/ruby-lex.rb - ruby lexcal analyzer
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-require "e2mmap"
-require "irb/slex"
-require "irb/ruby-token"
-
-class RubyLex
- @RCS_ID='-$Id$-'
-
- 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")
-
- def_exception(:TerminateLineInput, "Terminate Line Input")
-
- include RubyToken
-
- class << self
- attr_accessor :debug_level
- def debug?
- @debug_level > 0
- end
- end
- @debug_level = 0
-
- def initialize
- lex_init
- set_input(STDIN)
-
- @seek = 0
- @exp_line_no = @line_no = 1
- @base_char_no = 0
- @char_no = 0
- @rests = []
- @readed = []
- @here_readed = []
-
- @indent = 0
- @indent_stack = []
- @lex_state = EXPR_BEG
- @space_seen = false
- @here_header = false
-
- @continue = false
- @line = ""
-
- @skip_space = false
- @readed_auto_clean_up = false
- @exception_on_syntax_error = true
-
- @prompt = nil
- end
-
- attr_accessor :skip_space
- attr_accessor :readed_auto_clean_up
- attr_accessor :exception_on_syntax_error
-
- attr_reader :seek
- attr_reader :char_no
- attr_reader :line_no
- attr_reader :indent
-
- # io functions
- def set_input(io, p = nil, &block)
- @io = io
- if p.respond_to?(:call)
- @input = p
- elsif block_given?
- @input = block
- else
- @input = Proc.new{@io.gets}
- end
- end
-
- def get_readed
- if idx = @readed.reverse.index("\n")
- @base_char_no = idx
- else
- @base_char_no += @readed.size
- end
-
- readed = @readed.join("")
- @readed = []
- readed
- end
-
- def getc
- while @rests.empty?
-# return nil unless buf_input
- @rests.push nil unless buf_input
- end
- c = @rests.shift
- if @here_header
- @here_readed.push c
- else
- @readed.push c
- end
- @seek += 1
- if c == "\n"
- @line_no += 1
- @char_no = 0
- else
- @char_no += 1
- end
- c
- end
-
- def gets
- l = ""
- while c = getc
- l.concat(c)
- break if c == "\n"
- end
- return nil if l == "" and c.nil?
- l
- end
-
- def eof?
- @io.eof?
- end
-
- def getc_of_rests
- if @rests.empty?
- nil
- else
- getc
- end
- end
-
- def ungetc(c = nil)
- if @here_readed.empty?
- c2 = @readed.pop
- else
- c2 = @here_readed.pop
- end
- c = c2 unless c
- @rests.unshift c #c =
- @seek -= 1
- if c == "\n"
- @line_no -= 1
- if idx = @readed.reverse.index("\n")
- @char_no = @readed.size - idx
- else
- @char_no = @base_char_no + @readed.size
- end
- else
- @char_no -= 1
- end
- end
-
- def peek_equal?(str)
- chrs = str.split(//)
- until @rests.size >= chrs.size
- return false unless buf_input
- end
- @rests[0, chrs.size] == chrs
- end
-
- def peek_match?(regexp)
- while @rests.empty?
- return false unless buf_input
- end
- regexp =~ @rests.join("")
- end
-
- def peek(i = 0)
- while @rests.size <= i
- return nil unless buf_input
- end
- @rests[i]
- end
-
- def buf_input
- prompt
- line = @input.call
- return nil unless line
- @rests.concat line.chars.to_a
- true
- end
- private :buf_input
-
- def set_prompt(p = nil, &block)
- p = block if block_given?
- if p.respond_to?(:call)
- @prompt = p
- else
- @prompt = Proc.new{print p}
- end
- end
-
- def prompt
- if @prompt
- @prompt.call(@ltype, @indent, @continue, @line_no)
- end
- end
-
- def initialize_input
- @ltype = nil
- @quoted = nil
- @indent = 0
- @indent_stack = []
- @lex_state = EXPR_BEG
- @space_seen = false
- @here_header = false
-
- @continue = false
- prompt
-
- @line = ""
- @exp_line_no = @line_no
- end
-
- def each_top_level_statement
- initialize_input
- catch(:TERM_INPUT) do
- loop do
- begin
- @continue = false
- prompt
- unless l = lex
- throw :TERM_INPUT if @line == ''
- else
- @line.concat l
- if @ltype or @continue or @indent > 0
- next
- end
- end
- if @line != "\n"
- @line.force_encoding(@io.encoding)
- yield @line, @exp_line_no
- end
- break unless l
- @line = ''
- @exp_line_no = @line_no
-
- @indent = 0
- @indent_stack = []
- prompt
- rescue TerminateLineInput
- initialize_input
- prompt
- get_readed
- end
- end
- end
- end
-
- def lex
- until (((tk = token).kind_of?(TkNL) || tk.kind_of?(TkEND_OF_SCRIPT)) &&
- !@continue or
- tk.nil?)
- #p tk
- #p @lex_state
- #p self
- end
- line = get_readed
- # print self.inspect
- if line == "" and tk.kind_of?(TkEND_OF_SCRIPT) || tk.nil?
- nil
- else
- line
- end
- end
-
- def token
- # require "tracer"
- # Tracer.on
- @prev_seek = @seek
- @prev_line_no = @line_no
- @prev_char_no = @char_no
- begin
- begin
- tk = @OP.match(self)
- @space_seen = tk.kind_of?(TkSPACE)
- rescue SyntaxError
- raise if @exception_on_syntax_error
- tk = TkError.new(@seek, @line_no, @char_no)
- end
- end while @skip_space and tk.kind_of?(TkSPACE)
- if @readed_auto_clean_up
- get_readed
- end
- # Tracer.off
- 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" => "]",
- "W" => "]",
- "s" => ":"
- }
-
- PERCENT_PAREN = {
- "{" => "}",
- "[" => "]",
- "<" => ">",
- "(" => ")"
- }
-
- Ltype2Token = {
- "\'" => TkSTRING,
- "\"" => TkSTRING,
- "\`" => TkXSTRING,
- "/" => TkREGEXP,
- "]" => TkDSTRING,
- ":" => TkSYMBOL
- }
- DLtype2Token = {
- "\"" => TkDSTRING,
- "\`" => TkDXSTRING,
- "/" => TkDREGEXP,
- }
-
- def lex_init()
- @OP = IRB::SLex.new
- @OP.def_rules("\0", "\004", "\032") do |op, io|
- Token(TkEND_OF_SCRIPT)
- end
-
- @OP.def_rules(" ", "\t", "\f", "\r", "\13") do |op, io|
- @space_seen = true
- while getc =~ /[ \t\f\r\13]/; end
- ungetc
- Token(TkSPACE)
- end
-
- @OP.def_rule("#") do |op, io|
- identify_comment
- end
-
- @OP.def_rule("=begin",
- proc{|op, io| @prev_char_no == 0 && peek(0) =~ /\s/}) do
- |op, io|
- @ltype = "="
- until getc == "\n"; end
- until peek_equal?("=end") && peek(4) =~ /\s/
- until getc == "\n"; end
- end
- gets
- @ltype = nil
- Token(TkRD_COMMENT)
- end
-
- @OP.def_rule("\n") do |op, io|
- 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
- until (@indent_stack.empty? ||
- [TkLPAREN, TkLBRACK, TkLBRACE,
- TkfLPAREN, TkfLBRACK, TkfLBRACE].include?(@indent_stack.last))
- @indent_stack.pop
- end
- end
- @here_header = false
- @here_readed = []
- Token(TkNL)
- end
-
- @OP.def_rules("*", "**",
- "=", "==", "===",
- "=~", "<=>",
- "<", "<=",
- ">", ">=", ">>",
- "!", "!=", "!~") do
- |op, io|
- case @lex_state
- when EXPR_FNAME, EXPR_DOT
- @lex_state = EXPR_ARG
- else
- @lex_state = EXPR_BEG
- end
- Token(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 /\S/ =~ c && (/["'`]/ =~ c || /\w/ =~ c || c == "-")
- tk = identify_here_document
- end
- end
- unless tk
- tk = Token(op)
- case @lex_state
- when EXPR_FNAME, EXPR_DOT
- @lex_state = EXPR_ARG
- else
- @lex_state = EXPR_BEG
- end
- end
- tk
- end
-
- @OP.def_rules("'", '"') do
- |op, io|
- identify_string(op)
- end
-
- @OP.def_rules("`") do
- |op, io|
- if @lex_state == EXPR_FNAME
- @lex_state = EXPR_END
- Token(op)
- else
- identify_string(op)
- end
- end
-
- @OP.def_rules('?') do
- |op, io|
- if @lex_state == EXPR_END
- @lex_state = EXPR_BEG
- Token(TkQUESTION)
- else
- ch = getc
- if @lex_state == EXPR_ARG && ch =~ /\s/
- ungetc
- @lex_state = EXPR_BEG;
- Token(TkQUESTION)
- else
- if (ch == '\\')
- read_escape
- end
- @lex_state = EXPR_END
- Token(TkINTEGER)
- end
- end
- end
-
- @OP.def_rules("&", "&&", "|", "||") do
- |op, io|
- @lex_state = EXPR_BEG
- Token(op)
- end
-
- @OP.def_rules("+=", "-=", "*=", "**=",
- "&=", "|=", "^=", "<<=", ">>=", "||=", "&&=") do
- |op, io|
- @lex_state = EXPR_BEG
- op =~ /^(.*)=$/
- Token(TkOPASGN, $1)
- end
-
- @OP.def_rule("+@", proc{|op, io| @lex_state == EXPR_FNAME}) do
- |op, io|
- @lex_state = EXPR_ARG
- Token(op)
- end
-
- @OP.def_rule("-@", proc{|op, io| @lex_state == EXPR_FNAME}) do
- |op, io|
- @lex_state = EXPR_ARG
- Token(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
- else
- @lex_state = EXPR_BEG
- end
- elsif @lex_state != EXPR_END and peek(0) =~ /[0-9]/
- throw :RET, identify_number
- else
- @lex_state = EXPR_BEG
- end
- Token(op)
- end
- end
-
- @OP.def_rule(".") do
- |op, io|
- @lex_state = EXPR_BEG
- if peek(0) =~ /[0-9]/
- ungetc
- identify_number
- else
- # for "obj.if" etc.
- @lex_state = EXPR_DOT
- Token(TkDOT)
- end
- end
-
- @OP.def_rules("..", "...") do
- |op, io|
- @lex_state = EXPR_BEG
- Token(op)
- end
-
- lex_int2
- end
-
- def lex_int2
- @OP.def_rules("]", "}", ")") do
- |op, io|
- @lex_state = EXPR_END
- @indent -= 1
- @indent_stack.pop
- Token(op)
- end
-
- @OP.def_rule(":") do
- |op, io|
- if @lex_state == EXPR_END || peek(0) =~ /\s/
- @lex_state = EXPR_BEG
- Token(TkCOLON)
- else
- @lex_state = EXPR_FNAME;
- Token(TkSYMBEG)
- end
- end
-
- @OP.def_rule("::") do
- |op, io|
-# p @lex_state.id2name, @space_seen
- if @lex_state == EXPR_BEG or @lex_state == EXPR_ARG && @space_seen
- @lex_state = EXPR_BEG
- Token(TkCOLON3)
- else
- @lex_state = EXPR_DOT
- Token(TkCOLON2)
- end
- 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, "/") #/)
- elsif @lex_state == EXPR_ARG and @space_seen and peek(0) !~ /\s/
- identify_string(op)
- else
- @lex_state = EXPR_BEG
- Token("/") #/)
- end
- end
-
- @OP.def_rules("^") do
- |op, io|
- @lex_state = EXPR_BEG
- Token("^")
- end
-
- # @OP.def_rules("^=") do
- # @lex_state = EXPR_BEG
- # Token(OP_ASGN, :^)
- # end
-
- @OP.def_rules(",") do
- |op, io|
- @lex_state = EXPR_BEG
- Token(op)
- end
-
- @OP.def_rules(";") do
- |op, io|
- @lex_state = EXPR_BEG
- until (@indent_stack.empty? ||
- [TkLPAREN, TkLBRACK, TkLBRACE,
- TkfLPAREN, TkfLBRACK, TkfLBRACE].include?(@indent_stack.last))
- @indent_stack.pop
- end
- Token(op)
- end
-
- @OP.def_rule("~") do
- |op, io|
- @lex_state = EXPR_BEG
- Token("~")
- end
-
- @OP.def_rule("~@", proc{|op, io| @lex_state == EXPR_FNAME}) do
- |op, io|
- @lex_state = EXPR_BEG
- Token("~")
- end
-
- @OP.def_rule("(") do
- |op, io|
- @indent += 1
- if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
- @lex_state = EXPR_BEG
- tk_c = TkfLPAREN
- else
- @lex_state = EXPR_BEG
- tk_c = TkLPAREN
- end
- @indent_stack.push tk_c
- Token(tk_c)
- end
-
- @OP.def_rule("[]", proc{|op, io| @lex_state == EXPR_FNAME}) do
- |op, io|
- @lex_state = EXPR_ARG
- Token("[]")
- end
-
- @OP.def_rule("[]=", proc{|op, io| @lex_state == EXPR_FNAME}) do
- |op, io|
- @lex_state = EXPR_ARG
- Token("[]=")
- end
-
- @OP.def_rule("[") do
- |op, io|
- @indent += 1
- if @lex_state == EXPR_FNAME
- tk_c = TkfLBRACK
- else
- if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
- tk_c = TkLBRACK
- elsif @lex_state == EXPR_ARG && @space_seen
- tk_c = TkLBRACK
- else
- tk_c = TkfLBRACK
- end
- @lex_state = EXPR_BEG
- end
- @indent_stack.push tk_c
- Token(tk_c)
- end
-
- @OP.def_rule("{") do
- |op, io|
- @indent += 1
- if @lex_state != EXPR_END && @lex_state != EXPR_ARG
- tk_c = TkLBRACE
- else
- tk_c = TkfLBRACE
- end
- @lex_state = EXPR_BEG
- @indent_stack.push tk_c
- Token(tk_c)
- end
-
- @OP.def_rule('\\') do
- |op, io|
- if getc == "\n"
- @space_seen = true
- @continue = true
- Token(TkSPACE)
- else
- read_escape
- Token("\\")
- 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, :%)
- elsif @lex_state == EXPR_ARG and @space_seen and peek(0) !~ /\s/
- identify_quotation
- else
- @lex_state = EXPR_BEG
- Token("%") #))
- end
- end
-
- @OP.def_rule('$') do
- |op, io|
- identify_gvar
- end
-
- @OP.def_rule('@') do
- |op, io|
- if peek(0) =~ /[\w@]/
- ungetc
- identify_identifier
- else
- Token("@")
- 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("") 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) =~ /[^\x00-\/:-@\[-^`{-\x7F]/
- 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
-
- case ch = getc
- when /[~_*$?!@\/\\;,=:<>".]/ #"
- Token(TkGVAR, "$" + ch)
- when "-"
- Token(TkGVAR, "$-" + getc)
- when "&", "`", "'", "+"
- Token(TkBACK_REF, "$"+ch)
- when /[1-9]/
- while getc =~ /[0-9]/; end
- ungetc
- Token(TkNTH_REF)
- when /\w/
- ungetc
- ungetc
- identify_identifier
- else
- ungetc
- Token("$")
- end
- end
-
- def identify_identifier
- token = ""
- if peek(0) =~ /[$@]/
- token.concat(c = getc)
- if c == "@" and peek(0) == "@"
- token.concat getc
- end
- end
-
- while (ch = getc) =~ /[^\x00-\/:-@\[-^`{-\x7F]/
- print ":", ch, ":" if RubyLex.debug?
- token.concat ch
- end
- ungetc
-
- if (ch == "!" || ch == "?") && token[0,1] =~ /\w/ && peek(0) != "="
- token.concat getc
- end
-
- # almost fix token
-
- case token
- when /^\$/
- return Token(TkGVAR, token)
- when /^\@\@/
- @lex_state = EXPR_END
- # p Token(TkCVAR, token)
- return Token(TkCVAR, token)
- when /^\@/
- @lex_state = EXPR_END
- return Token(TkIVAR, 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)
- # check for ``class = val'' etc.
- valid = true
- case token
- when "class"
- valid = false unless peek_match?(/^\s*(<<|\w|::)/)
- when "def"
- valid = false if peek_match?(/^\s*(([+\-\/*&\|^]|<<|>>|\|\||\&\&)=|\&\&|\|\|)/)
- when "do"
- valid = false if peek_match?(/^\s*([+\-\/*]?=|\*|<|>|\&)/)
- when *ENINDENT_CLAUSE
- valid = false if peek_match?(/^\s*([+\-\/*]?=|\*|<|>|\&|\|)/)
- else
- # no nothing
- end
- if valid
- if token == "do"
- if ![TkFOR, TkWHILE, TkUNTIL].include?(@indent_stack.last)
- @indent += 1
- @indent_stack.push token_c
- end
- else
- @indent += 1
- @indent_stack.push token_c
- end
-# p @indent_stack
- end
-
- elsif DEINDENT_CLAUSE.include?(token)
- @indent -= 1
- @indent_stack.pop
- end
- @lex_state = trans[0]
- else
- @lex_state = EXPR_END
- end
- end
- return Token(token_c, 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)
- elsif token[token.size - 1, 1] =~ /[!?]/
- return Token(TkFID, token)
- else
- return Token(TkIDENTIFIER, token)
- end
- end
-
- def identify_here_document
- ch = getc
-# if lt = PERCENT_LTYPE[ch]
- 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.push ch
- if ch == "\\"
- reserve.push ch = getc
- elsif ch == "\n"
- break
- end
- end
-
- @here_header = false
- while l = gets
- l = l.sub(/(:?\r)?\n\z/, '')
- if (indent ? l.strip : l) == quoted
- break
- end
- end
-
- @here_header = true
- @here_readed.concat reserve
- while ch = reserve.pop
- ungetc ch
- end
-
- @ltype = ltback
- @lex_state = EXPR_END
- Token(Ltype2Token[lt])
- end
-
- def identify_quotation
- ch = getc
- if lt = PERCENT_LTYPE[ch]
- ch = getc
- elsif ch =~ /\W/
- lt = "\""
- else
- RubyLex.fail SyntaxError, "unknown type of %string"
- end
-# if ch !~ /\W/
-# ungetc
-# next
-# end
- #@ltype = lt
- @quoted = ch unless @quoted = PERCENT_PAREN[ch]
- identify_string(lt, @quoted)
- end
-
- def identify_number
- @lex_state = EXPR_END
-
- if peek(0) == "0" && peek(1) !~ /[.eE]/
- getc
- case peek(0)
- when /[xX]/
- ch = getc
- match = /[0-9a-fA-F_]/
- when /[bB]/
- ch = getc
- match = /[01_]/
- when /[oO]/
- ch = getc
- match = /[0-7_]/
- when /[dD]/
- ch = getc
- match = /[0-9_]/
- when /[0-7]/
- match = /[0-7_]/
- when /[89]/
- RubyLex.fail SyntaxError, "Invalid octal digit"
- else
- return Token(TkINTEGER)
- end
-
- len0 = true
- non_digit = false
- while ch = getc
- if match =~ ch
- if ch == "_"
- if non_digit
- RubyLex.fail SyntaxError, "trailing `#{ch}' in number"
- else
- non_digit = ch
- end
- else
- non_digit = false
- len0 = false
- end
- else
- ungetc
- if len0
- RubyLex.fail SyntaxError, "numeric literal without digits"
- end
- if non_digit
- RubyLex.fail SyntaxError, "trailing `#{non_digit}' in number"
- end
- break
- end
- end
- return Token(TkINTEGER)
- end
-
- type = TkINTEGER
- allow_point = true
- allow_e = true
- non_digit = false
- while ch = getc
- case ch
- when /[0-9]/
- non_digit = false
- when "_"
- non_digit = ch
- when allow_point && "."
- if non_digit
- RubyLex.fail SyntaxError, "trailing `#{non_digit}' in number"
- end
- type = TkFLOAT
- if peek(0) !~ /[0-9]/
- type = TkINTEGER
- ungetc
- break
- end
- allow_point = false
- when allow_e && "e", allow_e && "E"
- if non_digit
- RubyLex.fail SyntaxError, "trailing `#{non_digit}' in number"
- end
- type = TkFLOAT
- if peek(0) =~ /[+-]/
- getc
- end
- allow_e = false
- allow_point = false
- non_digit = ch
- else
- if non_digit
- RubyLex.fail SyntaxError, "trailing `#{non_digit}' in number"
- end
- ungetc
- break
- end
- end
- Token(type)
- end
-
- def identify_string(ltype, quoted = ltype)
- @ltype = ltype
- @quoted = quoted
- subtype = nil
- begin
- nest = 0
- while ch = getc
- if @quoted == ch and nest == 0
- break
- elsif @ltype != "'" && ch == "#" && peek(0) == "{"
- identify_string_dvar
- elsif @ltype != "'" && @ltype != "]" && @ltype != ":" and ch == "#"
- subtype = true
- elsif ch == '\\' and @ltype == "'" #'
- case ch = getc
- when "\\", "\n", "'"
- else
- ungetc
- end
- elsif ch == '\\' #'
- read_escape
- end
- if PERCENT_PAREN.values.include?(@quoted)
- if PERCENT_PAREN[ch] == @quoted
- nest += 1
- elsif ch == @quoted
- nest -= 1
- end
- end
- end
- if @ltype == "/"
- while /[imxoesun]/ =~ peek(0)
- getc
- end
- end
- if subtype
- Token(DLtype2Token[ltype])
- else
- Token(Ltype2Token[ltype])
- end
- ensure
- @ltype = nil
- @quoted = nil
- @lex_state = EXPR_END
- end
- end
-
- def identify_string_dvar
- begin
- getc
-
- reserve_continue = @continue
- reserve_ltype = @ltype
- reserve_indent = @indent
- reserve_indent_stack = @indent_stack
- reserve_state = @lex_state
- reserve_quoted = @quoted
-
- @ltype = nil
- @quoted = nil
- @indent = 0
- @indent_stack = []
- @lex_state = EXPR_BEG
-
- loop do
- @continue = false
- prompt
- tk = token
- if @ltype or @continue or @indent > 0
- next
- end
- break if tk.kind_of?(TkRBRACE)
- end
- ensure
- @continue = reserve_continue
- @ltype = reserve_ltype
- @indent = reserve_indent
- @indent_stack = reserve_indent_stack
- @lex_state = reserve_state
- @quoted = reserve_quoted
- end
- end
-
- def identify_comment
- @ltype = "#"
-
- while ch = getc
-# if ch == "\\" #"
-# read_escape
-# end
- if ch == "\n"
- @ltype = nil
- ungetc
- break
- end
- end
- return Token(TkCOMMENT)
- end
-
- def read_escape
- case ch = getc
- when "\n", "\r", "\f"
- when "\\", "n", "t", "r", "f", "v", "a", "e", "b", "s" #"
- when /[0-7]/
- ungetc ch
- 3.times do
- case ch = getc
- when /[0-7]/
- when nil
- break
- else
- ungetc
- break
- end
- end
-
- when "x"
- 2.times do
- case ch = getc
- when /[0-9a-fA-F]/
- when nil
- break
- else
- ungetc
- break
- end
- end
-
- when "M"
- if (ch = getc) != '-'
- ungetc
- else
- if (ch = getc) == "\\" #"
- read_escape
- end
- end
-
- when "C", "c" #, "^"
- if ch == "C" and (ch = getc) != "-"
- ungetc
- elsif (ch = getc) == "\\" #"
- read_escape
- end
- else
- # other characters
- end
- end
-end
diff --git a/ruby_1_9_3/lib/irb/ruby-token.rb b/ruby_1_9_3/lib/irb/ruby-token.rb
deleted file mode 100644
index 531fb859ff..0000000000
--- a/ruby_1_9_3/lib/irb/ruby-token.rb
+++ /dev/null
@@ -1,265 +0,0 @@
-#
-# irb/ruby-token.rb - ruby tokens
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-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
- def initialize(seek, line_no, char_no)
- @seek = seek
- @line_no = line_no
- @char_no = char_no
- end
- attr :seek, :line_no, :char_no
- end
-
- class TkNode < Token
- def initialize(seek, line_no, char_no)
- super
- end
- attr :node
- end
-
- class TkId < Token
- def initialize(seek, line_no, char_no, name)
- super(seek, line_no, char_no)
- @name = name
- end
- attr :name
- end
-
- class TkVal < Token
- def initialize(seek, line_no, char_no, value = nil)
- super(seek, line_no, char_no)
- @value = value
- end
- attr :value
- end
-
- class TkOp < Token
- attr_accessor :name
- end
-
- class TkOPASGN < TkOp
- def initialize(seek, line_no, char_no, op)
- super(seek, line_no, char_no)
- op = TkReading2Token[op][0] unless op.kind_of?(Symbol)
- @op = op
- end
- attr :op
- end
-
- class TkUnknownChar < Token
- def initialize(seek, line_no, char_no, id)
- super(seek, line_no, char_no)
- @name = name
- end
- attr :name
- end
-
- class TkError < Token
- end
-
- def Token(token, value = nil)
- case token
- when String
- if (tk = TkReading2Token[token]).nil?
- IRB.fail TkReading2TokenNoKey, token
- end
- tk = Token(tk[0], value)
- if tk.kind_of?(TkOp)
- tk.name = token
- end
- return tk
- when Symbol
- if (tk = TkSymbol2Token[token]).nil?
- IRB.fail TkSymbol2TokenNoKey, token
- end
- return Token(tk[0], value)
- else
- if (token.ancestors & [TkId, TkVal, TkOPASGN, TkUnknownChar]).empty?
- token.new(@prev_seek, @prev_line_no, @prev_char_no)
- else
- token.new(@prev_seek, @prev_line_no, @prev_char_no, value)
- end
- end
- end
-
- TokenDefinitions = [
- [:TkCLASS, TkId, "class", EXPR_CLASS],
- [:TkMODULE, TkId, "module", EXPR_BEG],
- [:TkDEF, TkId, "def", EXPR_FNAME],
- [:TkUNDEF, TkId, "undef", EXPR_FNAME],
- [:TkBEGIN, TkId, "begin", EXPR_BEG],
- [:TkRESCUE, TkId, "rescue", EXPR_MID],
- [:TkENSURE, TkId, "ensure", EXPR_BEG],
- [:TkEND, TkId, "end", EXPR_END],
- [:TkIF, TkId, "if", EXPR_BEG, :TkIF_MOD],
- [:TkUNLESS, TkId, "unless", EXPR_BEG, :TkUNLESS_MOD],
- [:TkTHEN, TkId, "then", EXPR_BEG],
- [:TkELSIF, TkId, "elsif", EXPR_BEG],
- [:TkELSE, TkId, "else", EXPR_BEG],
- [:TkCASE, TkId, "case", EXPR_BEG],
- [:TkWHEN, TkId, "when", EXPR_BEG],
- [:TkWHILE, TkId, "while", EXPR_BEG, :TkWHILE_MOD],
- [:TkUNTIL, TkId, "until", EXPR_BEG, :TkUNTIL_MOD],
- [:TkFOR, TkId, "for", EXPR_BEG],
- [:TkBREAK, TkId, "break", EXPR_END],
- [:TkNEXT, TkId, "next", EXPR_END],
- [:TkREDO, TkId, "redo", EXPR_END],
- [:TkRETRY, TkId, "retry", EXPR_END],
- [:TkIN, TkId, "in", EXPR_BEG],
- [:TkDO, TkId, "do", EXPR_BEG],
- [:TkRETURN, TkId, "return", EXPR_MID],
- [:TkYIELD, TkId, "yield", EXPR_END],
- [:TkSUPER, TkId, "super", EXPR_END],
- [:TkSELF, TkId, "self", EXPR_END],
- [:TkNIL, TkId, "nil", EXPR_END],
- [:TkTRUE, TkId, "true", EXPR_END],
- [:TkFALSE, TkId, "false", EXPR_END],
- [:TkAND, TkId, "and", EXPR_BEG],
- [:TkOR, TkId, "or", EXPR_BEG],
- [:TkNOT, TkId, "not", EXPR_BEG],
- [:TkIF_MOD, TkId],
- [:TkUNLESS_MOD, TkId],
- [:TkWHILE_MOD, TkId],
- [:TkUNTIL_MOD, TkId],
- [:TkALIAS, TkId, "alias", EXPR_FNAME],
- [:TkDEFINED, TkId, "defined?", EXPR_END],
- [:TklBEGIN, TkId, "BEGIN", EXPR_END],
- [:TklEND, TkId, "END", EXPR_END],
- [:Tk__LINE__, TkId, "__LINE__", EXPR_END],
- [:Tk__FILE__, TkId, "__FILE__", EXPR_END],
-
- [:TkIDENTIFIER, TkId],
- [:TkFID, TkId],
- [:TkGVAR, TkId],
- [:TkCVAR, TkId],
- [:TkIVAR, TkId],
- [:TkCONSTANT, TkId],
-
- [:TkINTEGER, TkVal],
- [:TkFLOAT, TkVal],
- [:TkSTRING, TkVal],
- [:TkXSTRING, TkVal],
- [:TkREGEXP, TkVal],
- [:TkSYMBOL, TkVal],
-
- [:TkDSTRING, TkNode],
- [:TkDXSTRING, TkNode],
- [:TkDREGEXP, TkNode],
- [:TkNTH_REF, TkNode],
- [:TkBACK_REF, TkNode],
-
- [: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 #
- [:TkSYMBEG], # :SYMBOL
-
- [: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, ";"],
-
- [:TkCOMMENT],
- [: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 if token_n.kind_of?(Symbol)
- if RubyToken.const_defined?(token_n)
- IRB.fail AlreadyDefinedToken, token_n
- end
- token_c = eval("class #{token_n} < #{super_token}; end; #{token_n}")
-
- 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
- end
-
- for defs in TokenDefinitions
- def_token(*defs)
- end
-end
diff --git a/ruby_1_9_3/lib/irb/slex.rb b/ruby_1_9_3/lib/irb/slex.rb
deleted file mode 100644
index b395eaa475..0000000000
--- a/ruby_1_9_3/lib/irb/slex.rb
+++ /dev/null
@@ -1,282 +0,0 @@
-#
-# irb/slex.rb - simple lex analyzer
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-require "e2mmap"
-require "irb/notifier"
-
-module IRB
- class SLex
- @RCS_ID='-$Id$-'
-
- extend Exception2MessageMapper
- def_exception :ErrNodeNothing, "node nothing"
- def_exception :ErrNodeAlreadyExists, "node already exists"
-
- DOUT = Notifier::def_notifier("SLex::")
- D_WARN = DOUT::def_notifier(1, "Warn: ")
- D_DEBUG = DOUT::def_notifier(2, "Debug: ")
- D_DETAIL = DOUT::def_notifier(4, "Detail: ")
-
- DOUT.level = Notifier::D_NOMSG
-
- def initialize
- @head = Node.new("")
- end
-
- def def_rule(token, preproc = nil, postproc = nil, &block)
- D_DETAIL.pp token
-
- postproc = block if block_given?
- create(token, preproc, postproc)
- end
-
- def def_rules(*tokens, &block)
- if block_given?
- p = block
- end
- for token in tokens
- def_rule(token, nil, p)
- end
- end
-
- def preproc(token, proc)
- node = search(token)
- node.preproc=proc
- end
-
- #$BMW%A%'%C%/(B?
- def postproc(token)
- node = search(token, proc)
- node.postproc=proc
- end
-
- def search(token)
- @head.search(token.split(//))
- end
-
- def create(token, preproc = nil, postproc = nil)
- @head.create_subnode(token.split(//), preproc, postproc)
- end
-
- def match(token)
- case token
- when Array
- when String
- return match(token.split(//))
- else
- return @head.match_io(token)
- end
- ret = @head.match(token)
- D_DETAIL.exec_if{D_DEATIL.printf "match end: %s:%s\n", ret, token.inspect}
- ret
- end
-
- def inspect
- format("<SLex: @head = %s>", @head.inspect)
- end
-
- #----------------------------------------------------------------------
- #
- # class Node -
- #
- #----------------------------------------------------------------------
- class Node
- # if postproc is nil, this node is an abstract node.
- # if postproc is non-nil, this node is a real node.
- def initialize(preproc = nil, postproc = nil)
- @Tree = {}
- @preproc = preproc
- @postproc = postproc
- end
-
- attr_accessor :preproc
- attr_accessor :postproc
-
- def search(chrs, opt = nil)
- return self if chrs.empty?
- ch = chrs.shift
- if node = @Tree[ch]
- node.search(chrs, opt)
- else
- if opt
- chrs.unshift ch
- self.create_subnode(chrs)
- else
- SLex.fail ErrNodeNothing
- end
- end
- end
-
- def create_subnode(chrs, preproc = nil, postproc = nil)
- if chrs.empty?
- if @postproc
- D_DETAIL.pp node
- SLex.fail ErrNodeAlreadyExists
- else
- D_DEBUG.puts "change abstract node to real node."
- @preproc = preproc
- @postproc = postproc
- end
- return self
- end
-
- ch = chrs.shift
- if node = @Tree[ch]
- if chrs.empty?
- if node.postproc
- DebugLogger.pp node
- DebugLogger.pp self
- DebugLogger.pp ch
- DebugLogger.pp chrs
- SLex.fail ErrNodeAlreadyExists
- else
- D_WARN.puts "change abstract node to real node"
- node.preproc = preproc
- node.postproc = postproc
- end
- else
- node.create_subnode(chrs, preproc, postproc)
- end
- else
- if chrs.empty?
- node = Node.new(preproc, postproc)
- else
- node = Node.new
- node.create_subnode(chrs, preproc, postproc)
- end
- @Tree[ch] = node
- end
- node
- end
-
- #
- # chrs: String
- # character array
- # io must have getc()/ungetc(); and ungetc() must be
- # able to be called arbitrary number of times.
- #
- def match(chrs, op = "")
- D_DETAIL.print "match>: ", chrs, "op:", op, "\n"
- if chrs.empty?
- if @preproc.nil? || @preproc.call(op, chrs)
- DOUT.printf(D_DETAIL, "op1: %s\n", op)
- @postproc.call(op, chrs)
- else
- nil
- end
- else
- ch = chrs.shift
- if node = @Tree[ch]
- if ret = node.match(chrs, op+ch)
- return ret
- else
- chrs.unshift ch
- if @postproc and @preproc.nil? || @preproc.call(op, chrs)
- DOUT.printf(D_DETAIL, "op2: %s\n", op.inspect)
- ret = @postproc.call(op, chrs)
- return ret
- else
- return nil
- end
- end
- else
- chrs.unshift ch
- if @postproc and @preproc.nil? || @preproc.call(op, chrs)
- DOUT.printf(D_DETAIL, "op3: %s\n", op)
- @postproc.call(op, chrs)
- return ""
- else
- return nil
- end
- end
- end
- end
-
- def match_io(io, op = "")
- if op == ""
- ch = io.getc
- if ch == nil
- return nil
- end
- else
- ch = io.getc_of_rests
- end
- if ch.nil?
- if @preproc.nil? || @preproc.call(op, io)
- D_DETAIL.printf("op1: %s\n", op)
- @postproc.call(op, io)
- else
- nil
- end
- else
- if node = @Tree[ch]
- if ret = node.match_io(io, op+ch)
- ret
- else
- io.ungetc ch
- if @postproc and @preproc.nil? || @preproc.call(op, io)
- DOUT.exec_if{D_DETAIL.printf "op2: %s\n", op.inspect}
- @postproc.call(op, io)
- else
- nil
- end
- end
- else
- io.ungetc ch
- if @postproc and @preproc.nil? || @preproc.call(op, io)
- D_DETAIL.printf("op3: %s\n", op)
- @postproc.call(op, io)
- else
- nil
- end
- end
- end
- end
- end
- end
-end
-
-if $0 == __FILE__
- # Tracer.on
- case $1
- when "1"
- tr = SLex.new
- print "0: ", tr.inspect, "\n"
- tr.def_rule("=") {print "=\n"}
- print "1: ", tr.inspect, "\n"
- tr.def_rule("==") {print "==\n"}
- print "2: ", tr.inspect, "\n"
-
- print "case 1:\n"
- print tr.match("="), "\n"
- print "case 2:\n"
- print tr.match("=="), "\n"
- print "case 3:\n"
- print tr.match("=>"), "\n"
-
- when "2"
- tr = SLex.new
- print "0: ", tr.inspect, "\n"
- tr.def_rule("=") {print "=\n"}
- print "1: ", tr.inspect, "\n"
- tr.def_rule("==", proc{false}) {print "==\n"}
- print "2: ", tr.inspect, "\n"
-
- print "case 1:\n"
- print tr.match("="), "\n"
- print "case 2:\n"
- print tr.match("=="), "\n"
- print "case 3:\n"
- print tr.match("=>"), "\n"
- end
- exit
-end
-
diff --git a/ruby_1_9_3/lib/irb/src_encoding.rb b/ruby_1_9_3/lib/irb/src_encoding.rb
deleted file mode 100644
index 958cef104c..0000000000
--- a/ruby_1_9_3/lib/irb/src_encoding.rb
+++ /dev/null
@@ -1,4 +0,0 @@
-# DO NOT WRITE ANY MAGIC COMMENT HERE.
-def default_src_encoding
- return __ENCODING__
-end
diff --git a/ruby_1_9_3/lib/irb/version.rb b/ruby_1_9_3/lib/irb/version.rb
deleted file mode 100644
index 621a127ebd..0000000000
--- a/ruby_1_9_3/lib/irb/version.rb
+++ /dev/null
@@ -1,15 +0,0 @@
-#
-# irb/version.rb - irb version definition file
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-#
-# --
-#
-#
-#
-
-module IRB
- @RELEASE_VERSION = "0.9.6"
- @LAST_UPDATE_DATE = "09/06/30"
-end
diff --git a/ruby_1_9_3/lib/irb/workspace.rb b/ruby_1_9_3/lib/irb/workspace.rb
deleted file mode 100644
index edc0d3b147..0000000000
--- a/ruby_1_9_3/lib/irb/workspace.rb
+++ /dev/null
@@ -1,108 +0,0 @@
-#
-# irb/workspace-binding.rb -
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-module IRB
- class WorkSpace
- # create new workspace. set self to main if specified, otherwise
- # inherit main from TOPLEVEL_BINDING.
- def initialize(*main)
- if main[0].kind_of?(Binding)
- @binding = main.shift
- elsif IRB.conf[:SINGLE_IRB]
- @binding = TOPLEVEL_BINDING
- else
- case IRB.conf[:CONTEXT_MODE]
- when 0 # binding in proc on TOPLEVEL_BINDING
- @binding = eval("proc{binding}.call",
- TOPLEVEL_BINDING,
- __FILE__,
- __LINE__)
- when 1 # binding in loaded file
- require "tempfile"
- f = Tempfile.open("irb-binding")
- f.print <<EOF
- $binding = binding
-EOF
- f.close
- load f.path
- @binding = $binding
-
- when 2 # binding in loaded file(thread use)
- unless defined? BINDING_QUEUE
- require "thread"
-
- IRB.const_set("BINDING_QUEUE", SizedQueue.new(1))
- Thread.abort_on_exception = true
- Thread.start do
- eval "require \"irb/ws-for-case-2\"", TOPLEVEL_BINDING, __FILE__, __LINE__
- end
- Thread.pass
- end
- @binding = BINDING_QUEUE.pop
-
- when 3 # binging in function on TOPLEVEL_BINDING(default)
- @binding = eval("def irb_binding; binding; end; irb_binding",
- TOPLEVEL_BINDING,
- __FILE__,
- __LINE__ - 3)
- end
- end
- if main.empty?
- @main = eval("self", @binding)
- else
- @main = main[0]
- IRB.conf[:__MAIN__] = @main
- case @main
- when Module
- @binding = eval("IRB.conf[:__MAIN__].module_eval('binding', __FILE__, __LINE__)", @binding, __FILE__, __LINE__)
- else
- begin
- @binding = eval("IRB.conf[:__MAIN__].instance_eval('binding', __FILE__, __LINE__)", @binding, __FILE__, __LINE__)
- rescue TypeError
- IRB.fail CantChangeBinding, @main.inspect
- end
- end
- end
- eval("_=nil", @binding)
- end
-
- attr_reader :binding
- attr_reader :main
-
- def evaluate(context, statements, file = __FILE__, line = __LINE__)
- eval(statements, @binding, file, line)
- end
-
- # error message manipulator
- def filter_backtrace(bt)
- case IRB.conf[:CONTEXT_MODE]
- when 0
- return nil if bt =~ /\(irb_local_binding\)/
- when 1
- if(bt =~ %r!/tmp/irb-binding! or
- bt =~ %r!irb/.*\.rb! or
- bt =~ /irb\.rb/)
- return nil
- end
- when 2
- return nil if bt =~ /irb\/.*\.rb/
- return nil if bt =~ /irb\.rb/
- when 3
- return nil if bt =~ /irb\/.*\.rb/
- return nil if bt =~ /irb\.rb/
- bt = bt.sub(/:\s*in `irb_binding'/, '')
- end
- bt
- end
-
- def IRB.delete_caller
- end
- end
-end
diff --git a/ruby_1_9_3/lib/irb/ws-for-case-2.rb b/ruby_1_9_3/lib/irb/ws-for-case-2.rb
deleted file mode 100644
index 9f3af49f30..0000000000
--- a/ruby_1_9_3/lib/irb/ws-for-case-2.rb
+++ /dev/null
@@ -1,14 +0,0 @@
-#
-# irb/ws-for-case-2.rb -
-# $Release Version: 0.9.6$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-while true
- IRB::BINDING_QUEUE.push _ = binding
-end
diff --git a/ruby_1_9_3/lib/irb/xmp.rb b/ruby_1_9_3/lib/irb/xmp.rb
deleted file mode 100644
index bcef964020..0000000000
--- a/ruby_1_9_3/lib/irb/xmp.rb
+++ /dev/null
@@ -1,97 +0,0 @@
-#
-# xmp.rb - irb version of gotoken xmp
-# $Release Version: 0.9$
-# $Revision$
-# by Keiju ISHITSUKA(Nippon Rational Inc.)
-#
-# --
-#
-#
-#
-
-require "irb"
-require "irb/frame"
-
-class XMP
- @RCS_ID='-$Id$-'
-
- def initialize(bind = nil)
- IRB.init_config(nil)
- #IRB.parse_opts
- #IRB.load_modules
-
- IRB.conf[:PROMPT_MODE] = :XMP
-
- bind = IRB::Frame.top(1) unless bind
- ws = IRB::WorkSpace.new(bind)
- @io = StringInputMethod.new
- @irb = IRB::Irb.new(ws, @io)
- @irb.context.ignore_sigint = false
-
-# IRB.conf[:IRB_RC].call(@irb.context) if IRB.conf[:IRB_RC]
- IRB.conf[:MAIN_CONTEXT] = @irb.context
- end
-
- def puts(exps)
- @io.puts exps
-
- if @irb.context.ignore_sigint
- begin
- trap_proc_b = trap("SIGINT"){@irb.signal_handle}
- catch(:IRB_EXIT) do
- @irb.eval_input
- end
- ensure
- trap("SIGINT", trap_proc_b)
- end
- else
- catch(:IRB_EXIT) do
- @irb.eval_input
- end
- end
- end
-
- class StringInputMethod < IRB::InputMethod
- def initialize
- super
- @exps = []
- end
-
- def eof?
- @exps.empty?
- end
-
- def gets
- while l = @exps.shift
- next if /^\s+$/ =~ l
- l.concat "\n"
- print @prompt, l
- break
- end
- l
- end
-
- def puts(exps)
- if @encoding and exps.encoding != @encoding
- enc = Encoding.compatible?(@exps.join("\n"), exps)
- if enc.nil?
- raise Encoding::CompatibilityError, "Encoding in which the passed expression is encoded is not compatible to the preceding's one"
- else
- @encoding = enc
- end
- else
- @encoding = exps.encoding
- end
- @exps.concat exps.split(/\n/)
- end
-
- attr_reader :encoding
- end
-end
-
-def xmp(exps, bind = nil)
- bind = IRB::Frame.top(1) unless bind
- xmp = XMP.new(bind)
- xmp.puts exps
- xmp
-end
diff --git a/ruby_1_9_3/lib/logger.rb b/ruby_1_9_3/lib/logger.rb
deleted file mode 100644
index 6092959399..0000000000
--- a/ruby_1_9_3/lib/logger.rb
+++ /dev/null
@@ -1,801 +0,0 @@
-# logger.rb - simple logging utility
-# Copyright (C) 2000-2003, 2005, 2008, 2011 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
-#
-# Documentation:: NAKAMURA, Hiroshi and Gavin Sinclair
-# License::
-# You can redistribute it and/or modify it under the same terms of Ruby's
-# license; either the dual license version in 2003, or any later version.
-# Revision:: $Id$
-#
-# A simple system for logging messages. See Logger for more documentation.
-
-require 'monitor'
-
-# == Description
-#
-# The Logger class provides a simple but sophisticated logging utility that
-# you can use to output messages.
-#
-# The messages have associated levels, such as +INFO+ or +ERROR+ that indicate
-# their importance. You can then give the Logger a level, and only messages
-# at that level of higher will be printed.
-#
-# The levels are:
-#
-# +FATAL+:: an unhandleable error that results in a program crash
-# +ERROR+:: a handleable error condition
-# +WARN+:: a warning
-# +INFO+:: generic (useful) information about system operation
-# +DEBUG+:: low-level information for developers
-#
-# For instance, in a production system, you may have your Logger set to
-# +INFO+ or even +WARN+
-# When you are developing the system, however, you probably
-# want to know about the program's internal state, and would set the Logger to
-# +DEBUG+.
-#
-# *Note*: Logger does not escape or sanitize any messages passed to it.
-# Developers should be aware of when potentially malicious data (user-input)
-# is passed to Logger, and manually escape the untrusted data:
-#
-# logger.info("User-input: #{input.dump}")
-# logger.info("User-input: %p" % input)
-#
-# You can use #formatter= for escaping all data.
-#
-# original_formatter = Logger::Formatter.new
-# logger.formatter = proc { |severity, datetime, progname, msg|
-# original_formatter.call(severity, datetime, progname, msg.dump)
-# }
-# logger.info(input)
-#
-# === Example
-#
-# This creates a logger to the standard output stream, with a level of +WARN+
-#
-# log = Logger.new(STDOUT)
-# log.level = Logger::WARN
-#
-# log.debug("Created logger")
-# log.info("Program started")
-# log.warn("Nothing to do!")
-#
-# begin
-# File.each_line(path) do |line|
-# unless line =~ /^(\w+) = (.*)$/
-# log.error("Line in wrong format: #{line}")
-# end
-# end
-# rescue => err
-# log.fatal("Caught exception; exiting")
-# log.fatal(err)
-# end
-#
-# Because the Logger's level is set to +WARN+, only the warning, error, and
-# fatal messages are recorded. The debug and info messages are silently
-# discarded.
-#
-# === Features
-#
-# There are several interesting features that Logger provides, like
-# auto-rolling of log files, setting the format of log messages, and
-# specifying a program name in conjunction with the message. The next section
-# shows you how to achieve these things.
-#
-#
-# == HOWTOs
-#
-# === How to create a logger
-#
-# The options below give you various choices, in more or less increasing
-# complexity.
-#
-# 1. Create a logger which logs messages to STDERR/STDOUT.
-#
-# logger = Logger.new(STDERR)
-# logger = Logger.new(STDOUT)
-#
-# 2. Create a logger for the file which has the specified name.
-#
-# logger = Logger.new('logfile.log')
-#
-# 3. Create a logger for the specified file.
-#
-# file = File.open('foo.log', File::WRONLY | File::APPEND)
-# # To create new (and to remove old) logfile, add File::CREAT like;
-# # file = open('foo.log', File::WRONLY | File::APPEND | File::CREAT)
-# logger = Logger.new(file)
-#
-# 4. Create a logger which ages logfile once it reaches a certain size. Leave
-# 10 "old log files" and each file is about 1,024,000 bytes.
-#
-# logger = Logger.new('foo.log', 10, 1024000)
-#
-# 5. Create a logger which ages logfile daily/weekly/monthly.
-#
-# logger = Logger.new('foo.log', 'daily')
-# logger = Logger.new('foo.log', 'weekly')
-# logger = Logger.new('foo.log', 'monthly')
-#
-# === How to log a message
-#
-# Notice the different methods (+fatal+, +error+, +info+) being used to log
-# messages of various levels? Other methods in this family are +warn+ and
-# +debug+. +add+ is used below to log a message of an arbitrary (perhaps
-# dynamic) level.
-#
-# 1. Message in block.
-#
-# logger.fatal { "Argument 'foo' not given." }
-#
-# 2. Message as a string.
-#
-# logger.error "Argument #{ @foo } mismatch."
-#
-# 3. With progname.
-#
-# logger.info('initialize') { "Initializing..." }
-#
-# 4. With severity.
-#
-# logger.add(Logger::FATAL) { 'Fatal error!' }
-#
-# The block form allows you to create potentially complex log messages,
-# but to delay their evaluation until and unless the message is
-# logged. For example, if we have the following:
-#
-# logger.debug { "This is a " + potentially + " expensive operation" }
-#
-# If the logger's level is +INFO+ or higher, no debug messages will be logged,
-# and the entire block will not even be evaluated. Compare to this:
-#
-# logger.debug("This is a " + potentially + " expensive operation")
-#
-# Here, the string concatenation is done every time, even if the log
-# level is not set to show the debug message.
-#
-# === How to close a logger
-#
-# logger.close
-#
-# === Setting severity threshold
-#
-# 1. Original interface.
-#
-# logger.sev_threshold = Logger::WARN
-#
-# 2. Log4r (somewhat) compatible interface.
-#
-# logger.level = Logger::INFO
-#
-# DEBUG < INFO < WARN < ERROR < FATAL < UNKNOWN
-#
-#
-# == Format
-#
-# Log messages are rendered in the output stream in a certain format by
-# default. The default format and a sample are shown below:
-#
-# Log format:
-# SeverityID, [Date Time mSec #pid] SeverityLabel -- ProgName: message
-#
-# Log sample:
-# I, [Wed Mar 03 02:34:24 JST 1999 895701 #19074] INFO -- Main: info.
-#
-# You may change the date and time format via #datetime_format=
-#
-# logger.datetime_format = "%Y-%m-%d %H:%M:%S"
-# # e.g. "2004-01-03 00:54:26"
-#
-# Or, you may change the overall format with #formatter= method.
-#
-# logger.formatter = proc do |severity, datetime, progname, msg|
-# "#{datetime}: #{msg}\n"
-# end
-# # e.g. "Thu Sep 22 08:51:08 GMT+9:00 2005: hello world"
-#
-class Logger
- VERSION = "1.2.7"
- _, name, rev = %w$Id$
- if name
- name = name.chomp(",v")
- else
- name = File.basename(__FILE__)
- end
- rev ||= "v#{VERSION}"
- ProgName = "#{name}/#{rev}"
-
- class Error < RuntimeError # :nodoc:
- end
- # not used after 1.2.7. just for compat.
- class ShiftingError < Error # :nodoc:
- end
-
- # Logging severity.
- module Severity
- # Low-level information, mostly for developers
- DEBUG = 0
- # generic, useful information about system operation
- INFO = 1
- # a warning
- WARN = 2
- # a handleable error condition
- ERROR = 3
- # an unhandleable error that results in a program crash
- FATAL = 4
- # an unknown message that should always be logged
- UNKNOWN = 5
- end
- include Severity
-
- # Logging severity threshold (e.g. <tt>Logger::INFO</tt>).
- attr_accessor :level
-
- # program name to include in log messages.
- attr_accessor :progname
-
- # Set date-time format.
- #
- # +datetime_format+:: A string suitable for passing to +strftime+.
- def datetime_format=(datetime_format)
- @default_formatter.datetime_format = datetime_format
- end
-
- # Returns the date format being used. See #datetime_format=
- def datetime_format
- @default_formatter.datetime_format
- end
-
- # Logging formatter, as a +Proc+ that will take four arguments and
- # return the formatted message. The arguments are:
- #
- # +severity+:: The Severity of the log message
- # +time+:: A Time instance representing when the message was logged
- # +progname+:: The #progname configured, or passed to the logger method
- # +msg+:: The _Object_ the user passed to the log message; not necessarily a
- # String.
- #
- # The block should return an Object that can be written to the logging
- # device via +write+. The default formatter is used when no formatter is
- # set.
- attr_accessor :formatter
-
- alias sev_threshold level
- alias sev_threshold= level=
-
- # Returns +true+ iff the current severity level allows for the printing of
- # +DEBUG+ messages.
- def debug?; @level <= DEBUG; end
-
- # Returns +true+ iff the current severity level allows for the printing of
- # +INFO+ messages.
- def info?; @level <= INFO; end
-
- # Returns +true+ iff the current severity level allows for the printing of
- # +WARN+ messages.
- def warn?; @level <= WARN; end
-
- # Returns +true+ iff the current severity level allows for the printing of
- # +ERROR+ messages.
- def error?; @level <= ERROR; end
-
- # Returns +true+ iff the current severity level allows for the printing of
- # +FATAL+ messages.
- def fatal?; @level <= FATAL; end
-
- #
- # === Synopsis
- #
- # Logger.new(name, shift_age = 7, shift_size = 1048576)
- # Logger.new(name, shift_age = 'weekly')
- #
- # === Args
- #
- # +logdev+::
- # The log device. This is a filename (String) or IO object (typically
- # +STDOUT+, +STDERR+, or an open file).
- # +shift_age+::
- # Number of old log files to keep, *or* frequency of rotation (+daily+,
- # +weekly+ or +monthly+).
- # +shift_size+::
- # Maximum logfile size (only applies when +shift_age+ is a number).
- #
- # === Description
- #
- # Create an instance.
- #
- def initialize(logdev, shift_age = 0, shift_size = 1048576)
- @progname = nil
- @level = DEBUG
- @default_formatter = Formatter.new
- @formatter = nil
- @logdev = nil
- if logdev
- @logdev = LogDevice.new(logdev, :shift_age => shift_age,
- :shift_size => shift_size)
- end
- end
-
- #
- # === Synopsis
- #
- # Logger#add(severity, message = nil, progname = nil) { ... }
- #
- # === Args
- #
- # +severity+::
- # Severity. Constants are defined in Logger namespace: +DEBUG+, +INFO+,
- # +WARN+, +ERROR+, +FATAL+, or +UNKNOWN+.
- # +message+::
- # The log message. A String or Exception.
- # +progname+::
- # Program name string. Can be omitted. Treated as a message if no
- # +message+ and +block+ are given.
- # +block+::
- # Can be omitted. Called to get a message string if +message+ is nil.
- #
- # === Return
- #
- # +true+ if successful, +false+ otherwise.
- #
- # When the given severity is not high enough (for this particular logger), log
- # no message, and return +true+.
- #
- # === Description
- #
- # Log a message if the given severity is high enough. This is the generic
- # logging method. Users will be more inclined to use #debug, #info, #warn,
- # #error, and #fatal.
- #
- # <b>Message format</b>: +message+ can be any object, but it has to be
- # converted to a String in order to log it. Generally, +inspect+ is used
- # if the given object is not a String.
- # A special case is an +Exception+ object, which will be printed in detail,
- # including message, class, and backtrace. See #msg2str for the
- # implementation if required.
- #
- # === Bugs
- #
- # * Logfile is not locked.
- # * Append open does not need to lock file.
- # * If the OS which supports multi I/O, records possibly be mixed.
- #
- def add(severity, message = nil, progname = nil, &block)
- severity ||= UNKNOWN
- if @logdev.nil? or severity < @level
- return true
- end
- progname ||= @progname
- if message.nil?
- if block_given?
- message = yield
- else
- message = progname
- progname = @progname
- end
- end
- @logdev.write(
- format_message(format_severity(severity), Time.now, progname, message))
- true
- end
- alias log add
-
- #
- # Dump given message to the log device without any formatting. If no log
- # device exists, return +nil+.
- #
- def <<(msg)
- unless @logdev.nil?
- @logdev.write(msg)
- end
- end
-
- #
- # Log a +DEBUG+ message.
- #
- # See #info for more information.
- #
- def debug(progname = nil, &block)
- add(DEBUG, nil, progname, &block)
- end
-
- #
- # :call-seq:
- # info(message)
- # info(progname,&block)
- #
- # Log an +INFO+ message.
- #
- # +message+:: the message to log; does not need to be a String
- # +progname+:: in the block form, this is the #progname to use in the
- # the log message. The default can be set with #progname=
- # <tt>&block</tt>:: evaluates to the message to log. This is not evaluated
- # unless the logger's level is sufficient
- # to log the message. This allows you to create
- # potentially expensive logging messages that are
- # only called when the logger is configured to show them.
- #
- # === Examples
- #
- # logger.info("MainApp") { "Received connection from #{ip}" }
- # # ...
- # logger.info "Waiting for input from user"
- # # ...
- # logger.info { "User typed #{input}" }
- #
- # You'll probably stick to the second form above, unless you want to provide a
- # program name (which you can do with #progname= as well).
- #
- # === Return
- #
- # See #add.
- #
- def info(progname = nil, &block)
- add(INFO, nil, progname, &block)
- end
-
- #
- # Log a +WARN+ message.
- #
- # See #info for more information.
- #
- def warn(progname = nil, &block)
- add(WARN, nil, progname, &block)
- end
-
- #
- # Log an +ERROR+ message.
- #
- # See #info for more information.
- #
- def error(progname = nil, &block)
- add(ERROR, nil, progname, &block)
- end
-
- #
- # Log a +FATAL+ message.
- #
- # See #info for more information.
- #
- def fatal(progname = nil, &block)
- add(FATAL, nil, progname, &block)
- end
-
- #
- # Log an +UNKNOWN+ message. This will be printed no matter what the logger's
- # level.
- #
- # See #info for more information.
- #
- def unknown(progname = nil, &block)
- add(UNKNOWN, nil, progname, &block)
- end
-
- #
- # Close the logging device.
- #
- def close
- @logdev.close if @logdev
- end
-
-private
-
- # Severity label for logging. (max 5 char)
- SEV_LABEL = %w(DEBUG INFO WARN ERROR FATAL ANY)
-
- def format_severity(severity)
- SEV_LABEL[severity] || 'ANY'
- end
-
- def format_message(severity, datetime, progname, msg)
- (@formatter || @default_formatter).call(severity, datetime, progname, msg)
- end
-
-
- # Default formatter for log messages
- class Formatter
- Format = "%s, [%s#%d] %5s -- %s: %s\n"
-
- attr_accessor :datetime_format
-
- def initialize
- @datetime_format = nil
- end
-
- def call(severity, time, progname, msg)
- Format % [severity[0..0], format_datetime(time), $$, severity, progname,
- msg2str(msg)]
- end
-
- private
-
- def format_datetime(time)
- if @datetime_format.nil?
- time.strftime("%Y-%m-%dT%H:%M:%S.") << "%06d " % time.usec
- else
- time.strftime(@datetime_format)
- end
- end
-
- def msg2str(msg)
- case msg
- when ::String
- msg
- when ::Exception
- "#{ msg.message } (#{ msg.class })\n" <<
- (msg.backtrace || []).join("\n")
- else
- msg.inspect
- end
- end
- end
-
-
- # Device used for logging messages.
- class LogDevice
- attr_reader :dev
- attr_reader :filename
-
- class LogDeviceMutex
- include MonitorMixin
- end
-
- def initialize(log = nil, opt = {})
- @dev = @filename = @shift_age = @shift_size = nil
- @mutex = LogDeviceMutex.new
- if log.respond_to?(:write) and log.respond_to?(:close)
- @dev = log
- else
- @dev = open_logfile(log)
- @dev.sync = true
- @filename = log
- @shift_age = opt[:shift_age] || 7
- @shift_size = opt[:shift_size] || 1048576
- end
- end
-
- def write(message)
- begin
- @mutex.synchronize do
- if @shift_age and @dev.respond_to?(:stat)
- begin
- check_shift_log
- rescue
- warn("log shifting failed. #{$!}")
- end
- end
- begin
- @dev.write(message)
- rescue
- warn("log writing failed. #{$!}")
- end
- end
- rescue Exception => ignored
- warn("log writing failed. #{ignored}")
- end
- end
-
- def close
- begin
- @mutex.synchronize do
- @dev.close rescue nil
- end
- rescue Exception
- @dev.close rescue nil
- end
- end
-
- private
-
- def open_logfile(filename)
- if (FileTest.exist?(filename))
- open(filename, (File::WRONLY | File::APPEND))
- else
- create_logfile(filename)
- end
- end
-
- def create_logfile(filename)
- logdev = open(filename, (File::WRONLY | File::APPEND | File::CREAT))
- logdev.sync = true
- add_log_header(logdev)
- logdev
- end
-
- def add_log_header(file)
- file.write(
- "# Logfile created on %s by %s\n" % [Time.now.to_s, Logger::ProgName]
- )
- end
-
- SiD = 24 * 60 * 60
-
- def check_shift_log
- if @shift_age.is_a?(Integer)
- # Note: always returns false if '0'.
- if @filename && (@shift_age > 0) && (@dev.stat.size > @shift_size)
- shift_log_age
- end
- else
- now = Time.now
- period_end = previous_period_end(now)
- if @dev.stat.mtime <= period_end
- shift_log_period(period_end)
- end
- end
- end
-
- def shift_log_age
- (@shift_age-3).downto(0) do |i|
- if FileTest.exist?("#{@filename}.#{i}")
- File.rename("#{@filename}.#{i}", "#{@filename}.#{i+1}")
- end
- end
- @dev.close rescue nil
- File.rename("#{@filename}", "#{@filename}.0")
- @dev = create_logfile(@filename)
- return true
- end
-
- def shift_log_period(period_end)
- postfix = period_end.strftime("%Y%m%d") # YYYYMMDD
- age_file = "#{@filename}.#{postfix}"
- if FileTest.exist?(age_file)
- # try to avoid filename crash caused by Timestamp change.
- idx = 0
- # .99 can be overridden; avoid too much file search with 'loop do'
- while idx < 100
- idx += 1
- age_file = "#{@filename}.#{postfix}.#{idx}"
- break unless FileTest.exist?(age_file)
- end
- end
- @dev.close rescue nil
- File.rename("#{@filename}", age_file)
- @dev = create_logfile(@filename)
- return true
- end
-
- def previous_period_end(now)
- case @shift_age
- when /^daily$/
- eod(now - 1 * SiD)
- when /^weekly$/
- eod(now - ((now.wday + 1) * SiD))
- when /^monthly$/
- eod(now - now.mday * SiD)
- else
- now
- end
- end
-
- def eod(t)
- Time.mktime(t.year, t.month, t.mday, 23, 59, 59)
- end
- end
-
-
- #
- # == Description
- #
- # Application -- Add logging support to your application.
- #
- # == Usage
- #
- # 1. Define your application class as a sub-class of this class.
- # 2. Override 'run' method in your class to do many things.
- # 3. Instantiate it and invoke 'start'.
- #
- # == Example
- #
- # class FooApp < Application
- # def initialize(foo_app, application_specific, arguments)
- # super('FooApp') # Name of the application.
- # end
- #
- # def run
- # ...
- # log(WARN, 'warning', 'my_method1')
- # ...
- # @log.error('my_method2') { 'Error!' }
- # ...
- # end
- # end
- #
- # status = FooApp.new(....).start
- #
- class Application
- include Logger::Severity
-
- # Name of the application given at initialize.
- attr_reader :appname
-
- #
- # == Synopsis
- #
- # Application.new(appname = '')
- #
- # == Args
- #
- # +appname+:: Name of the application.
- #
- # == Description
- #
- # Create an instance. Log device is +STDERR+ by default. This can be
- # changed with #set_log.
- #
- def initialize(appname = nil)
- @appname = appname
- @log = Logger.new(STDERR)
- @log.progname = @appname
- @level = @log.level
- end
-
- #
- # Start the application. Return the status code.
- #
- def start
- status = -1
- begin
- log(INFO, "Start of #{ @appname }.")
- status = run
- rescue
- log(FATAL, "Detected an exception. Stopping ... #{$!} (#{$!.class})\n" << $@.join("\n"))
- ensure
- log(INFO, "End of #{ @appname }. (status: #{ status.to_s })")
- end
- status
- end
-
- # Logger for this application. See the class Logger for an explanation.
- def logger
- @log
- end
-
- #
- # Sets the logger for this application. See the class Logger for an
- # explanation.
- #
- def logger=(logger)
- @log = logger
- @log.progname = @appname
- @log.level = @level
- end
-
- #
- # Sets the log device for this application. See <tt>Logger.new</tt> for
- # an explanation of the arguments.
- #
- def set_log(logdev, shift_age = 0, shift_size = 1024000)
- @log = Logger.new(logdev, shift_age, shift_size)
- @log.progname = @appname
- @log.level = @level
- end
-
- def log=(logdev)
- set_log(logdev)
- end
-
- #
- # Set the logging threshold, just like <tt>Logger#level=</tt>.
- #
- def level=(level)
- @level = level
- @log.level = @level
- end
-
- #
- # See Logger#add. This application's +appname+ is used.
- #
- def log(severity, message = nil, &block)
- @log.add(severity, message, @appname, &block) if @log
- end
-
- private
-
- def run
- # TODO: should be an NotImplementedError
- raise RuntimeError.new('Method run must be defined in the derived class.')
- end
- end
-end
diff --git a/ruby_1_9_3/lib/mathn.rb b/ruby_1_9_3/lib/mathn.rb
deleted file mode 100644
index aae4620c3f..0000000000
--- a/ruby_1_9_3/lib/mathn.rb
+++ /dev/null
@@ -1,324 +0,0 @@
-#--
-# $Release Version: 0.5 $
-# $Revision: 1.1.1.1.4.1 $
-
-##
-# = mathn
-#
-# mathn is a library for changing the way Ruby does math. If you need
-# more precise rounding with multiple division or exponentiation
-# operations, then mathn is the right tool.
-#
-# Without mathn:
-#
-# 3 / 2 => 1 # Integer
-#
-# With mathn:
-#
-# 3 / 2 => 3/2 # Rational
-#
-# mathn features late rounding and lacks truncation of intermediate results:
-#
-# Without mathn:
-#
-# 20 / 9 * 3 * 14 / 7 * 3 / 2 # => 18
-#
-# With mathn:
-#
-# 20 / 9 * 3 * 14 / 7 * 3 / 2 # => 20
-#
-#
-# When you require 'mathn', the libraries for Prime, CMath, Matrix and Vector
-# are also loaded.
-#
-# == Copyright
-#
-# Author: Keiju ISHITSUKA (SHL Japan Inc.)
-#--
-# class Numeric follows to make this documentation findable in a reasonable
-# location
-
-class Numeric; end
-
-require "cmath.rb"
-require "matrix.rb"
-require "prime.rb"
-
-require "mathn/rational"
-require "mathn/complex"
-
-unless defined?(Math.exp!)
- Object.instance_eval{remove_const :Math}
- Math = CMath # :nodoc:
-end
-
-##
-# When mathn is required, Fixnum's division and exponentiation are enhanced to
-# return more precise values from mathematical expressions.
-#
-# 2/3*3 # => 0
-# require 'mathn'
-# 2/3*3 # => 2
-
-class Fixnum
- remove_method :/
-
- ##
- # +/+ defines the Rational division for Fixnum.
- #
- # 1/3 # => (1/3)
-
- alias / quo
-
- alias power! ** unless method_defined? :power!
-
- ##
- # Exponentiate by +other+
-
- def ** (other)
- if self < 0 && other.round != other
- Complex(self, 0.0) ** other
- else
- power!(other)
- end
- end
-
-end
-
-##
-# When mathn is required Bignum's division and exponentiation are enhanced to
-# return more precise values from mathematical expressions.
-
-class Bignum
- remove_method :/
-
- ##
- # +/+ defines the Rational division for Bignum.
- #
- # (2**72) / ((2**70) * 3) # => 4/3
-
- alias / quo
-
- alias power! ** unless method_defined? :power!
-
- ##
- # Exponentiate by +other+
-
- def ** (other)
- if self < 0 && other.round != other
- Complex(self, 0.0) ** other
- else
- power!(other)
- end
- end
-
-end
-
-##
-# When mathn is required Rational is changed to simplify the use of Rational
-# operations.
-#
-# Normal behaviour:
-#
-# Rational.new!(1,3) ** 2 # => Rational(1, 9)
-# (1 / 3) ** 2 # => 0
-#
-# require 'mathn' behaviour:
-#
-# (1 / 3) ** 2 # => 1/9
-
-class Rational
- remove_method :**
-
- ##
- # Exponentiate by +other+
- #
- # (1/3) ** 2 # => 1/9
-
- def ** (other)
- if other.kind_of?(Rational)
- other2 = other
- if self < 0
- return Complex(self, 0.0) ** other
- elsif other == 0
- return Rational(1,1)
- elsif self == 0
- return Rational(0,1)
- elsif self == 1
- return Rational(1,1)
- end
-
- npd = numerator.prime_division
- dpd = denominator.prime_division
- if other < 0
- other = -other
- npd, dpd = dpd, npd
- end
-
- for elm in npd
- elm[1] = elm[1] * other
- if !elm[1].kind_of?(Integer) and elm[1].denominator != 1
- return Float(self) ** other2
- end
- elm[1] = elm[1].to_i
- end
-
- for elm in dpd
- elm[1] = elm[1] * other
- if !elm[1].kind_of?(Integer) and elm[1].denominator != 1
- return Float(self) ** other2
- end
- elm[1] = elm[1].to_i
- end
-
- num = Integer.from_prime_division(npd)
- den = Integer.from_prime_division(dpd)
-
- Rational(num,den)
-
- elsif other.kind_of?(Integer)
- if other > 0
- num = numerator ** other
- den = denominator ** other
- elsif other < 0
- num = denominator ** -other
- den = numerator ** -other
- elsif other == 0
- num = 1
- den = 1
- end
- Rational(num, den)
- elsif other.kind_of?(Float)
- Float(self) ** other
- else
- x , y = other.coerce(self)
- x ** y
- end
- end
-end
-
-##
-# When mathn is required, the Math module changes as follows:
-#
-# Standard Math module behaviour:
-# Math.sqrt(4/9) # => 0.0
-# Math.sqrt(4.0/9.0) # => 0.666666666666667
-# Math.sqrt(- 4/9) # => Errno::EDOM: Numerical argument out of domain - sqrt
-#
-# After require 'mathn', this is changed to:
-#
-# require 'mathn'
-# Math.sqrt(4/9) # => 2/3
-# Math.sqrt(4.0/9.0) # => 0.666666666666667
-# Math.sqrt(- 4/9) # => Complex(0, 2/3)
-
-module Math
- remove_method(:sqrt)
-
- ##
- # Computes the square root of +a+. It makes use of Complex and
- # Rational to have no rounding errors if possible.
- #
- # Math.sqrt(4/9) # => 2/3
- # Math.sqrt(- 4/9) # => Complex(0, 2/3)
- # Math.sqrt(4.0/9.0) # => 0.666666666666667
-
- def sqrt(a)
- if a.kind_of?(Complex)
- abs = sqrt(a.real*a.real + a.imag*a.imag)
-# if not abs.kind_of?(Rational)
-# return a**Rational(1,2)
-# end
- x = sqrt((a.real + abs)/Rational(2))
- y = sqrt((-a.real + abs)/Rational(2))
-# if !(x.kind_of?(Rational) and y.kind_of?(Rational))
-# return a**Rational(1,2)
-# end
- if a.imag >= 0
- Complex(x, y)
- else
- Complex(x, -y)
- end
- elsif a.respond_to?(:nan?) and a.nan?
- a
- elsif a >= 0
- rsqrt(a)
- else
- Complex(0,rsqrt(-a))
- end
- end
-
- ##
- # Compute square root of a non negative number. This method is
- # internally used by +Math.sqrt+.
-
- def rsqrt(a)
- if a.kind_of?(Float)
- sqrt!(a)
- elsif a.kind_of?(Rational)
- rsqrt(a.numerator)/rsqrt(a.denominator)
- else
- src = a
- max = 2 ** 32
- byte_a = [src & 0xffffffff]
- # ruby's bug
- while (src >= max) and (src >>= 32)
- byte_a.unshift src & 0xffffffff
- end
-
- answer = 0
- main = 0
- side = 0
- for elm in byte_a
- main = (main << 32) + elm
- side <<= 16
- if answer != 0
- if main * 4 < side * side
- applo = main.div(side)
- else
- applo = ((sqrt!(side * side + 4 * main) - side)/2.0).to_i + 1
- end
- else
- applo = sqrt!(main).to_i + 1
- end
-
- while (x = (side + applo) * applo) > main
- applo -= 1
- end
- main -= x
- answer = (answer << 16) + applo
- side += applo * 2
- end
- if main == 0
- answer
- else
- sqrt!(a)
- end
- end
- end
-
- class << self
- remove_method(:sqrt)
- end
- module_function :sqrt
- module_function :rsqrt
-end
-
-##
-# When mathn is required, Float is changed to handle Complex numbers.
-
-class Float
- alias power! **
-
- ##
- # Exponentiate by +other+
-
- def ** (other)
- if self < 0 && other.round != other
- Complex(self, 0.0) ** other
- else
- power!(other)
- end
- end
-
-end
diff --git a/ruby_1_9_3/lib/matrix.rb b/ruby_1_9_3/lib/matrix.rb
deleted file mode 100644
index 3c078c0c06..0000000000
--- a/ruby_1_9_3/lib/matrix.rb
+++ /dev/null
@@ -1,1866 +0,0 @@
-# encoding: utf-8
-#
-# = matrix.rb
-#
-# An implementation of Matrix and Vector classes.
-#
-# See classes Matrix and Vector for documentation.
-#
-# Current Maintainer:: Marc-André Lafortune
-# Original Author:: Keiju ISHITSUKA
-# Original Documentation:: Gavin Sinclair (sourced from <i>Ruby in a Nutshell</i> (Matsumoto, O'Reilly))
-##
-
-require "e2mmap.rb"
-
-module ExceptionForMatrix # :nodoc:
- extend Exception2MessageMapper
- def_e2message(TypeError, "wrong argument type %s (expected %s)")
- def_e2message(ArgumentError, "Wrong # of arguments(%d for %d)")
-
- def_exception("ErrDimensionMismatch", "\#{self.name} dimension mismatch")
- def_exception("ErrNotRegular", "Not Regular Matrix")
- def_exception("ErrOperationNotDefined", "Operation(%s) can\\'t be defined: %s op %s")
- def_exception("ErrOperationNotImplemented", "Sorry, Operation(%s) not implemented: %s op %s")
-end
-
-#
-# The +Matrix+ class represents a mathematical matrix. It provides methods for creating
-# matrices, operating on them arithmetically and algebraically,
-# and determining their mathematical properties (trace, rank, inverse, determinant).
-#
-# == Method Catalogue
-#
-# To create a matrix:
-# * <tt> Matrix[*rows] </tt>
-# * <tt> Matrix.[](*rows) </tt>
-# * <tt> Matrix.rows(rows, copy = true) </tt>
-# * <tt> Matrix.columns(columns) </tt>
-# * <tt> Matrix.build(row_size, column_size, &block) </tt>
-# * <tt> Matrix.diagonal(*values) </tt>
-# * <tt> Matrix.scalar(n, value) </tt>
-# * <tt> Matrix.identity(n) </tt>
-# * <tt> Matrix.unit(n) </tt>
-# * <tt> Matrix.I(n) </tt>
-# * <tt> Matrix.zero(n) </tt>
-# * <tt> Matrix.row_vector(row) </tt>
-# * <tt> Matrix.column_vector(column) </tt>
-#
-# To access Matrix elements/columns/rows/submatrices/properties:
-# * <tt> [](i, j) </tt>
-# * <tt> #row_size </tt>
-# * <tt> #column_size </tt>
-# * <tt> #row(i) </tt>
-# * <tt> #column(j) </tt>
-# * <tt> #collect </tt>
-# * <tt> #map </tt>
-# * <tt> #each </tt>
-# * <tt> #each_with_index </tt>
-# * <tt> #find_index </tt>
-# * <tt> #minor(*param) </tt>
-#
-# Properties of a matrix:
-# * <tt> #diagonal? </tt>
-# * <tt> #empty? </tt>
-# * <tt> #hermitian? </tt>
-# * <tt> #lower_triangular? </tt>
-# * <tt> #normal? </tt>
-# * <tt> #orthogonal? </tt>
-# * <tt> #permutation? </tt>
-# * <tt> #real? </tt>
-# * <tt> #regular? </tt>
-# * <tt> #singular? </tt>
-# * <tt> #square? </tt>
-# * <tt> #symmetric? </tt>
-# * <tt> #unitary? </tt>
-# * <tt> #upper_triangular? </tt>
-# * <tt> #zero? </tt>
-#
-# Matrix arithmetic:
-# * <tt> *(m) </tt>
-# * <tt> +(m) </tt>
-# * <tt> -(m) </tt>
-# * <tt> #/(m) </tt>
-# * <tt> #inverse </tt>
-# * <tt> #inv </tt>
-# * <tt> ** </tt>
-#
-# Matrix functions:
-# * <tt> #determinant </tt>
-# * <tt> #det </tt>
-# * <tt> #rank </tt>
-# * <tt> #round </tt>
-# * <tt> #trace </tt>
-# * <tt> #tr </tt>
-# * <tt> #transpose </tt>
-# * <tt> #t </tt>
-#
-# Matrix decompositions:
-# * <tt> #eigen </tt>
-# * <tt> #eigensystem </tt>
-# * <tt> #lup </tt>
-# * <tt> #lup_decomposition </tt>
-#
-# Complex arithmetic:
-# * <tt> conj </tt>
-# * <tt> conjugate </tt>
-# * <tt> imag </tt>
-# * <tt> imaginary </tt>
-# * <tt> real </tt>
-# * <tt> rect </tt>
-# * <tt> rectangular </tt>
-#
-# Conversion to other data types:
-# * <tt> #coerce(other) </tt>
-# * <tt> #row_vectors </tt>
-# * <tt> #column_vectors </tt>
-# * <tt> #to_a </tt>
-#
-# String representations:
-# * <tt> #to_s </tt>
-# * <tt> #inspect </tt>
-#
-class Matrix
- include Enumerable
- include ExceptionForMatrix
- autoload :EigenvalueDecomposition, "matrix/eigenvalue_decomposition"
- autoload :LUPDecomposition, "matrix/lup_decomposition"
-
- # instance creations
- private_class_method :new
- attr_reader :rows
- protected :rows
-
- #
- # Creates a matrix where each argument is a row.
- # Matrix[ [25, 93], [-1, 66] ]
- # => 25 93
- # -1 66
- #
- def Matrix.[](*rows)
- Matrix.rows(rows, false)
- end
-
- #
- # Creates a matrix where +rows+ is an array of arrays, each of which is a row
- # of the matrix. If the optional argument +copy+ is false, use the given
- # arrays as the internal structure of the matrix without copying.
- # Matrix.rows([[25, 93], [-1, 66]])
- # => 25 93
- # -1 66
- #
- def Matrix.rows(rows, copy = true)
- rows = convert_to_array(rows)
- rows.map! do |row|
- convert_to_array(row, copy)
- end
- size = (rows[0] || []).size
- rows.each do |row|
- Matrix.Raise ErrDimensionMismatch, "row size differs (#{row.size} should be #{size})" unless row.size == size
- end
- new rows, size
- end
-
- #
- # Creates a matrix using +columns+ as an array of column vectors.
- # Matrix.columns([[25, 93], [-1, 66]])
- # => 25 -1
- # 93 66
- #
- def Matrix.columns(columns)
- Matrix.rows(columns, false).transpose
- end
-
- #
- # Creates a matrix of size +row_size+ x +column_size+.
- # It fills the values by calling the given block,
- # passing the current row and column.
- # Returns an enumerator if no block is given.
- #
- # m = Matrix.build(2, 4) {|row, col| col - row }
- # => Matrix[[0, 1, 2, 3], [-1, 0, 1, 2]]
- # m = Matrix.build(3) { rand }
- # => a 3x3 matrix with random elements
- #
- def Matrix.build(row_size, column_size = row_size)
- row_size = CoercionHelper.coerce_to_int(row_size)
- column_size = CoercionHelper.coerce_to_int(column_size)
- raise ArgumentError if row_size < 0 || column_size < 0
- return to_enum :build, row_size, column_size unless block_given?
- rows = Array.new(row_size) do |i|
- Array.new(column_size) do |j|
- yield i, j
- end
- end
- new rows, column_size
- end
-
- #
- # Creates a matrix where the diagonal elements are composed of +values+.
- # Matrix.diagonal(9, 5, -3)
- # => 9 0 0
- # 0 5 0
- # 0 0 -3
- #
- def Matrix.diagonal(*values)
- size = values.size
- rows = Array.new(size) {|j|
- row = Array.new(size, 0)
- row[j] = values[j]
- row
- }
- new rows
- end
-
- #
- # Creates an +n+ by +n+ diagonal matrix where each diagonal element is
- # +value+.
- # Matrix.scalar(2, 5)
- # => 5 0
- # 0 5
- #
- def Matrix.scalar(n, value)
- Matrix.diagonal(*Array.new(n, value))
- end
-
- #
- # Creates an +n+ by +n+ identity matrix.
- # Matrix.identity(2)
- # => 1 0
- # 0 1
- #
- def Matrix.identity(n)
- Matrix.scalar(n, 1)
- end
- class << Matrix
- alias unit identity
- alias I identity
- end
-
- #
- # Creates a zero matrix.
- # Matrix.zero(2)
- # => 0 0
- # 0 0
- #
- def Matrix.zero(row_size, column_size = row_size)
- rows = Array.new(row_size){Array.new(column_size, 0)}
- new rows, column_size
- end
-
- #
- # Creates a single-row matrix where the values of that row are as given in
- # +row+.
- # Matrix.row_vector([4,5,6])
- # => 4 5 6
- #
- def Matrix.row_vector(row)
- row = convert_to_array(row)
- new [row]
- end
-
- #
- # Creates a single-column matrix where the values of that column are as given
- # in +column+.
- # Matrix.column_vector([4,5,6])
- # => 4
- # 5
- # 6
- #
- def Matrix.column_vector(column)
- column = convert_to_array(column)
- new [column].transpose, 1
- end
-
- #
- # Creates a empty matrix of +row_size+ x +column_size+.
- # At least one of +row_size+ or +column_size+ must be 0.
- #
- # m = Matrix.empty(2, 0)
- # m == Matrix[ [], [] ]
- # => true
- # n = Matrix.empty(0, 3)
- # n == Matrix.columns([ [], [], [] ])
- # => true
- # m * n
- # => Matrix[[0, 0, 0], [0, 0, 0]]
- #
- def Matrix.empty(row_size = 0, column_size = 0)
- Matrix.Raise ArgumentError, "One size must be 0" if column_size != 0 && row_size != 0
- Matrix.Raise ArgumentError, "Negative size" if column_size < 0 || row_size < 0
-
- new([[]]*row_size, column_size)
- end
-
- #
- # Matrix.new is private; use Matrix.rows, columns, [], etc... to create.
- #
- def initialize(rows, column_size = rows[0].size)
- # No checking is done at this point. rows must be an Array of Arrays.
- # column_size must be the size of the first row, if there is one,
- # otherwise it *must* be specified and can be any integer >= 0
- @rows = rows
- @column_size = column_size
- end
-
- def new_matrix(rows, column_size = rows[0].size) # :nodoc:
- Matrix.send(:new, rows, column_size) # bypass privacy of Matrix.new
- end
- private :new_matrix
-
- #
- # Returns element (+i+,+j+) of the matrix. That is: row +i+, column +j+.
- #
- def [](i, j)
- @rows.fetch(i){return nil}[j]
- end
- alias element []
- alias component []
-
- def []=(i, j, v)
- @rows[i][j] = v
- end
- alias set_element []=
- alias set_component []=
- private :[]=, :set_element, :set_component
-
- #
- # Returns the number of rows.
- #
- def row_size
- @rows.size
- end
-
- #
- # Returns the number of columns.
- #
- attr_reader :column_size
-
- #
- # Returns row vector number +i+ of the matrix as a Vector (starting at 0 like
- # an array). When a block is given, the elements of that vector are iterated.
- #
- def row(i, &block) # :yield: e
- if block_given?
- @rows.fetch(i){return self}.each(&block)
- self
- else
- Vector.elements(@rows.fetch(i){return nil})
- end
- end
-
- #
- # Returns column vector number +j+ of the matrix as a Vector (starting at 0
- # like an array). When a block is given, the elements of that vector are
- # iterated.
- #
- def column(j) # :yield: e
- if block_given?
- return self if j >= column_size || j < -column_size
- row_size.times do |i|
- yield @rows[i][j]
- end
- self
- else
- return nil if j >= column_size || j < -column_size
- col = Array.new(row_size) {|i|
- @rows[i][j]
- }
- Vector.elements(col, false)
- end
- end
-
- #
- # Returns a matrix that is the result of iteration of the given block over all
- # elements of the matrix.
- # Matrix[ [1,2], [3,4] ].collect { |e| e**2 }
- # => 1 4
- # 9 16
- #
- def collect(&block) # :yield: e
- return to_enum(:collect) unless block_given?
- rows = @rows.collect{|row| row.collect(&block)}
- new_matrix rows, column_size
- end
- alias map collect
-
- #
- # Yields all elements of the matrix, starting with those of the first row,
- # or returns an Enumerator is no block given.
- # Elements can be restricted by passing an argument:
- # * :all (default): yields all elements
- # * :diagonal: yields only elements on the diagonal
- # * :off_diagonal: yields all elements except on the diagonal
- # * :lower: yields only elements on or below the diagonal
- # * :strict_lower: yields only elements below the diagonal
- # * :strict_upper: yields only elements above the diagonal
- # * :upper: yields only elements on or above the diagonal
- #
- # Matrix[ [1,2], [3,4] ].each { |e| puts e }
- # # => prints the numbers 1 to 4
- # Matrix[ [1,2], [3,4] ].each(:strict_lower).to_a # => [3]
- #
- def each(which = :all) # :yield: e
- return to_enum :each, which unless block_given?
- last = column_size - 1
- case which
- when :all
- block = Proc.new
- @rows.each do |row|
- row.each(&block)
- end
- when :diagonal
- @rows.each_with_index do |row, row_index|
- yield row.fetch(row_index){return self}
- end
- when :off_diagonal
- @rows.each_with_index do |row, row_index|
- column_size.times do |col_index|
- yield row[col_index] unless row_index == col_index
- end
- end
- when :lower
- @rows.each_with_index do |row, row_index|
- 0.upto([row_index, last].min) do |col_index|
- yield row[col_index]
- end
- end
- when :strict_lower
- @rows.each_with_index do |row, row_index|
- [row_index, column_size].min.times do |col_index|
- yield row[col_index]
- end
- end
- when :strict_upper
- @rows.each_with_index do |row, row_index|
- (row_index+1).upto(last) do |col_index|
- yield row[col_index]
- end
- end
- when :upper
- @rows.each_with_index do |row, row_index|
- row_index.upto(last) do |col_index|
- yield row[col_index]
- end
- end
- else
- Matrix.Raise ArgumentError, "expected #{which.inspect} to be one of :all, :diagonal, :off_diagonal, :lower, :strict_lower, :strict_upper or :upper"
- end
- self
- end
-
- #
- # Same as #each, but the row index and column index in addition to the element
- #
- # Matrix[ [1,2], [3,4] ].each_with_index do |e, row, col|
- # puts "#{e} at #{row}, #{col}"
- # end
- # # => Prints:
- # # 1 at 0, 0
- # # 2 at 0, 1
- # # 3 at 1, 0
- # # 4 at 1, 1
- #
- def each_with_index(which = :all) # :yield: e, row, column
- return to_enum :each_with_index, which unless block_given?
- last = column_size - 1
- case which
- when :all
- @rows.each_with_index do |row, row_index|
- row.each_with_index do |e, col_index|
- yield e, row_index, col_index
- end
- end
- when :diagonal
- @rows.each_with_index do |row, row_index|
- yield row.fetch(row_index){return self}, row_index, row_index
- end
- when :off_diagonal
- @rows.each_with_index do |row, row_index|
- column_size.times do |col_index|
- yield row[col_index], row_index, col_index unless row_index == col_index
- end
- end
- when :lower
- @rows.each_with_index do |row, row_index|
- 0.upto([row_index, last].min) do |col_index|
- yield row[col_index], row_index, col_index
- end
- end
- when :strict_lower
- @rows.each_with_index do |row, row_index|
- [row_index, column_size].min.times do |col_index|
- yield row[col_index], row_index, col_index
- end
- end
- when :strict_upper
- @rows.each_with_index do |row, row_index|
- (row_index+1).upto(last) do |col_index|
- yield row[col_index], row_index, col_index
- end
- end
- when :upper
- @rows.each_with_index do |row, row_index|
- row_index.upto(last) do |col_index|
- yield row[col_index], row_index, col_index
- end
- end
- else
- Matrix.Raise ArgumentError, "expected #{which.inspect} to be one of :all, :diagonal, :off_diagonal, :lower, :strict_lower, :strict_upper or :upper"
- end
- self
- end
-
- SELECTORS = {all: true, diagonal: true, off_diagonal: true, lower: true, strict_lower: true, strict_upper: true, upper: true}.freeze
- #
- # :call-seq:
- # index(value, selector = :all) -> [row, column]
- # index(selector = :all){ block } -> [row, column]
- # index(selector = :all) -> an_enumerator
- #
- # The index method is specialized to return the index as [row, column]
- # It also accepts an optional +selector+ argument, see #each for details.
- #
- # Matrix[ [1,2], [3,4] ].index(&:even?) # => [0, 1]
- # Matrix[ [1,1], [1,1] ].index(1, :strict_lower) # => [1, 0]
- #
- def index(*args)
- raise ArgumentError, "wrong number of arguments(#{args.size} for 0-2)" if args.size > 2
- which = (args.size == 2 || SELECTORS.include?(args.last)) ? args.pop : :all
- return to_enum :find_index, which, *args unless block_given? || args.size == 1
- if args.size == 1
- value = args.first
- each_with_index(which) do |e, row_index, col_index|
- return row_index, col_index if e == value
- end
- else
- each_with_index(which) do |e, row_index, col_index|
- return row_index, col_index if yield e
- end
- end
- nil
- end
- alias_method :find_index, :index
- #
- # Returns a section of the matrix. The parameters are either:
- # * start_row, nrows, start_col, ncols; OR
- # * row_range, col_range
- #
- # Matrix.diagonal(9, 5, -3).minor(0..1, 0..2)
- # => 9 0 0
- # 0 5 0
- #
- # Like Array#[], negative indices count backward from the end of the
- # row or column (-1 is the last element). Returns nil if the starting
- # row or column is greater than row_size or column_size respectively.
- #
- def minor(*param)
- case param.size
- when 2
- row_range, col_range = param
- from_row = row_range.first
- from_row += row_size if from_row < 0
- to_row = row_range.end
- to_row += row_size if to_row < 0
- to_row += 1 unless row_range.exclude_end?
- size_row = to_row - from_row
-
- from_col = col_range.first
- from_col += column_size if from_col < 0
- to_col = col_range.end
- to_col += column_size if to_col < 0
- to_col += 1 unless col_range.exclude_end?
- size_col = to_col - from_col
- when 4
- from_row, size_row, from_col, size_col = param
- return nil if size_row < 0 || size_col < 0
- from_row += row_size if from_row < 0
- from_col += column_size if from_col < 0
- else
- Matrix.Raise ArgumentError, param.inspect
- end
-
- return nil if from_row > row_size || from_col > column_size || from_row < 0 || from_col < 0
- rows = @rows[from_row, size_row].collect{|row|
- row[from_col, size_col]
- }
- new_matrix rows, [column_size - from_col, size_col].min
- end
-
- #--
- # TESTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
- #++
-
- #
- # Returns +true+ is this is a diagonal matrix.
- # Raises an error if matrix is not square.
- #
- def diagonal?
- Matrix.Raise ErrDimensionMismatch unless square?
- each(:off_diagonal).all?(&:zero?)
- end
-
- #
- # Returns +true+ if this is an empty matrix, i.e. if the number of rows
- # or the number of columns is 0.
- #
- def empty?
- column_size == 0 || row_size == 0
- end
-
- #
- # Returns +true+ is this is an hermitian matrix.
- # Raises an error if matrix is not square.
- #
- def hermitian?
- Matrix.Raise ErrDimensionMismatch unless square?
- each_with_index(:strict_upper).all? do |e, row, col|
- e == rows[col][row].conj
- end
- end
-
- #
- # Returns +true+ is this is a lower triangular matrix.
- #
- def lower_triangular?
- each(:strict_upper).all?(&:zero?)
- end
-
- #
- # Returns +true+ is this is a normal matrix.
- # Raises an error if matrix is not square.
- #
- def normal?
- Matrix.Raise ErrDimensionMismatch unless square?
- rows.each_with_index do |row_i, i|
- rows.each_with_index do |row_j, j|
- s = 0
- rows.each_with_index do |row_k, k|
- s += row_i[k] * row_j[k].conj - row_k[i].conj * row_k[j]
- end
- return false unless s == 0
- end
- end
- true
- end
-
- #
- # Returns +true+ is this is an orthogonal matrix
- # Raises an error if matrix is not square.
- #
- def orthogonal?
- Matrix.Raise ErrDimensionMismatch unless square?
- rows.each_with_index do |row, i|
- column_size.times do |j|
- s = 0
- row_size.times do |k|
- s += row[k] * rows[k][j]
- end
- return false unless s == (i == j ? 1 : 0)
- end
- end
- true
- end
-
- #
- # Returns +true+ is this is a permutation matrix
- # Raises an error if matrix is not square.
- #
- def permutation?
- Matrix.Raise ErrDimensionMismatch unless square?
- cols = Array.new(column_size)
- rows.each_with_index do |row, i|
- found = false
- row.each_with_index do |e, j|
- if e == 1
- return false if found || cols[j]
- found = cols[j] = true
- elsif e != 0
- return false
- end
- end
- return false unless found
- end
- true
- end
-
- #
- # Returns +true+ if all entries of the matrix are real.
- #
- def real?
- all?(&:real?)
- end
-
- #
- # Returns +true+ if this is a regular (i.e. non-singular) matrix.
- #
- def regular?
- not singular?
- end
-
- #
- # Returns +true+ is this is a singular matrix.
- #
- def singular?
- determinant == 0
- end
-
- #
- # Returns +true+ is this is a square matrix.
- #
- def square?
- column_size == row_size
- end
-
- #
- # Returns +true+ is this is a symmetric matrix.
- # Raises an error if matrix is not square.
- #
- def symmetric?
- Matrix.Raise ErrDimensionMismatch unless square?
- each_with_index(:strict_upper).all? do |e, row, col|
- e == rows[col][row]
- end
- end
-
- #
- # Returns +true+ is this is a unitary matrix
- # Raises an error if matrix is not square.
- #
- def unitary?
- Matrix.Raise ErrDimensionMismatch unless square?
- rows.each_with_index do |row, i|
- column_size.times do |j|
- s = 0
- row_size.times do |k|
- s += row[k].conj * rows[k][j]
- end
- return false unless s == (i == j ? 1 : 0)
- end
- end
- true
- end
-
- #
- # Returns +true+ is this is an upper triangular matrix.
- #
- def upper_triangular?
- each(:strict_lower).all?(&:zero?)
- end
-
- #
- # Returns +true+ is this is a matrix with only zero elements
- #
- def zero?
- all?(&:zero?)
- end
-
- #--
- # OBJECT METHODS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
- #++
-
- #
- # Returns +true+ if and only if the two matrices contain equal elements.
- #
- def ==(other)
- return false unless Matrix === other &&
- column_size == other.column_size # necessary for empty matrices
- rows == other.rows
- end
-
- def eql?(other)
- return false unless Matrix === other &&
- column_size == other.column_size # necessary for empty matrices
- rows.eql? other.rows
- end
-
- #
- # Returns a clone of the matrix, so that the contents of each do not reference
- # identical objects.
- # There should be no good reason to do this since Matrices are immutable.
- #
- def clone
- new_matrix @rows.map(&:dup), column_size
- end
-
- #
- # Returns a hash-code for the matrix.
- #
- def hash
- @rows.hash
- end
-
- #--
- # ARITHMETIC -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
- #++
-
- #
- # Matrix multiplication.
- # Matrix[[2,4], [6,8]] * Matrix.identity(2)
- # => 2 4
- # 6 8
- #
- def *(m) # m is matrix or vector or number
- case(m)
- when Numeric
- rows = @rows.collect {|row|
- row.collect {|e| e * m }
- }
- return new_matrix rows, column_size
- when Vector
- m = Matrix.column_vector(m)
- r = self * m
- return r.column(0)
- when Matrix
- Matrix.Raise ErrDimensionMismatch if column_size != m.row_size
-
- rows = Array.new(row_size) {|i|
- Array.new(m.column_size) {|j|
- (0 ... column_size).inject(0) do |vij, k|
- vij + self[i, k] * m[k, j]
- end
- }
- }
- return new_matrix rows, m.column_size
- else
- return apply_through_coercion(m, __method__)
- end
- end
-
- #
- # Matrix addition.
- # Matrix.scalar(2,5) + Matrix[[1,0], [-4,7]]
- # => 6 0
- # -4 12
- #
- def +(m)
- case m
- when Numeric
- Matrix.Raise ErrOperationNotDefined, "+", self.class, m.class
- when Vector
- m = Matrix.column_vector(m)
- when Matrix
- else
- return apply_through_coercion(m, __method__)
- end
-
- Matrix.Raise ErrDimensionMismatch unless row_size == m.row_size and column_size == m.column_size
-
- rows = Array.new(row_size) {|i|
- Array.new(column_size) {|j|
- self[i, j] + m[i, j]
- }
- }
- new_matrix rows, column_size
- end
-
- #
- # Matrix subtraction.
- # Matrix[[1,5], [4,2]] - Matrix[[9,3], [-4,1]]
- # => -8 2
- # 8 1
- #
- def -(m)
- case m
- when Numeric
- Matrix.Raise ErrOperationNotDefined, "-", self.class, m.class
- when Vector
- m = Matrix.column_vector(m)
- when Matrix
- else
- return apply_through_coercion(m, __method__)
- end
-
- Matrix.Raise ErrDimensionMismatch unless row_size == m.row_size and column_size == m.column_size
-
- rows = Array.new(row_size) {|i|
- Array.new(column_size) {|j|
- self[i, j] - m[i, j]
- }
- }
- new_matrix rows, column_size
- end
-
- #
- # Matrix division (multiplication by the inverse).
- # Matrix[[7,6], [3,9]] / Matrix[[2,9], [3,1]]
- # => -7 1
- # -3 -6
- #
- def /(other)
- case other
- when Numeric
- rows = @rows.collect {|row|
- row.collect {|e| e / other }
- }
- return new_matrix rows, column_size
- when Matrix
- return self * other.inverse
- else
- return apply_through_coercion(other, __method__)
- end
- end
-
- #
- # Returns the inverse of the matrix.
- # Matrix[[-1, -1], [0, -1]].inverse
- # => -1 1
- # 0 -1
- #
- def inverse
- Matrix.Raise ErrDimensionMismatch unless square?
- Matrix.I(row_size).send(:inverse_from, self)
- end
- alias inv inverse
-
- def inverse_from(src) # :nodoc:
- last = row_size - 1
- a = src.to_a
-
- 0.upto(last) do |k|
- i = k
- akk = a[k][k].abs
- (k+1).upto(last) do |j|
- v = a[j][k].abs
- if v > akk
- i = j
- akk = v
- end
- end
- Matrix.Raise ErrNotRegular if akk == 0
- if i != k
- a[i], a[k] = a[k], a[i]
- @rows[i], @rows[k] = @rows[k], @rows[i]
- end
- akk = a[k][k]
-
- 0.upto(last) do |ii|
- next if ii == k
- q = a[ii][k].quo(akk)
- a[ii][k] = 0
-
- (k + 1).upto(last) do |j|
- a[ii][j] -= a[k][j] * q
- end
- 0.upto(last) do |j|
- @rows[ii][j] -= @rows[k][j] * q
- end
- end
-
- (k+1).upto(last) do |j|
- a[k][j] = a[k][j].quo(akk)
- end
- 0.upto(last) do |j|
- @rows[k][j] = @rows[k][j].quo(akk)
- end
- end
- self
- end
- private :inverse_from
-
- #
- # Matrix exponentiation.
- # Equivalent to multiplying the matrix by itself N times.
- # Non integer exponents will be handled by diagonalizing the matrix.
- #
- # Matrix[[7,6], [3,9]] ** 2
- # => 67 96
- # 48 99
- #
- def ** (other)
- case other
- when Integer
- x = self
- if other <= 0
- x = self.inverse
- return Matrix.identity(self.column_size) if other == 0
- other = -other
- end
- z = nil
- loop do
- z = z ? z * x : x if other[0] == 1
- return z if (other >>= 1).zero?
- x *= x
- end
- when Numeric
- v, d, v_inv = eigensystem
- v * Matrix.diagonal(*d.each(:diagonal).map{|e| e ** other}) * v_inv
- else
- Matrix.Raise ErrOperationNotDefined, "**", self.class, other.class
- end
- end
-
- #--
- # MATRIX FUNCTIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
- #++
-
- #
- # Returns the determinant of the matrix.
- #
- # Beware that using Float values can yield erroneous results
- # because of their lack of precision.
- # Consider using exact types like Rational or BigDecimal instead.
- #
- # Matrix[[7,6], [3,9]].determinant
- # => 45
- #
- def determinant
- Matrix.Raise ErrDimensionMismatch unless square?
- m = @rows
- case row_size
- # Up to 4x4, give result using Laplacian expansion by minors.
- # This will typically be faster, as well as giving good results
- # in case of Floats
- when 0
- +1
- when 1
- + m[0][0]
- when 2
- + m[0][0] * m[1][1] - m[0][1] * m[1][0]
- when 3
- m0, m1, m2 = m
- + m0[0] * m1[1] * m2[2] - m0[0] * m1[2] * m2[1] \
- - m0[1] * m1[0] * m2[2] + m0[1] * m1[2] * m2[0] \
- + m0[2] * m1[0] * m2[1] - m0[2] * m1[1] * m2[0]
- when 4
- m0, m1, m2, m3 = m
- + m0[0] * m1[1] * m2[2] * m3[3] - m0[0] * m1[1] * m2[3] * m3[2] \
- - m0[0] * m1[2] * m2[1] * m3[3] + m0[0] * m1[2] * m2[3] * m3[1] \
- + m0[0] * m1[3] * m2[1] * m3[2] - m0[0] * m1[3] * m2[2] * m3[1] \
- - m0[1] * m1[0] * m2[2] * m3[3] + m0[1] * m1[0] * m2[3] * m3[2] \
- + m0[1] * m1[2] * m2[0] * m3[3] - m0[1] * m1[2] * m2[3] * m3[0] \
- - m0[1] * m1[3] * m2[0] * m3[2] + m0[1] * m1[3] * m2[2] * m3[0] \
- + m0[2] * m1[0] * m2[1] * m3[3] - m0[2] * m1[0] * m2[3] * m3[1] \
- - m0[2] * m1[1] * m2[0] * m3[3] + m0[2] * m1[1] * m2[3] * m3[0] \
- + m0[2] * m1[3] * m2[0] * m3[1] - m0[2] * m1[3] * m2[1] * m3[0] \
- - m0[3] * m1[0] * m2[1] * m3[2] + m0[3] * m1[0] * m2[2] * m3[1] \
- + m0[3] * m1[1] * m2[0] * m3[2] - m0[3] * m1[1] * m2[2] * m3[0] \
- - m0[3] * m1[2] * m2[0] * m3[1] + m0[3] * m1[2] * m2[1] * m3[0]
- else
- # For bigger matrices, use an efficient and general algorithm.
- # Currently, we use the Gauss-Bareiss algorithm
- determinant_bareiss
- end
- end
- alias_method :det, :determinant
-
- #
- # Private. Use Matrix#determinant
- #
- # Returns the determinant of the matrix, using
- # Bareiss' multistep integer-preserving gaussian elimination.
- # It has the same computational cost order O(n^3) as standard Gaussian elimination.
- # Intermediate results are fraction free and of lower complexity.
- # A matrix of Integers will have thus intermediate results that are also Integers,
- # with smaller bignums (if any), while a matrix of Float will usually have
- # intermediate results with better precision.
- #
- def determinant_bareiss
- size = row_size
- last = size - 1
- a = to_a
- no_pivot = Proc.new{ return 0 }
- sign = +1
- pivot = 1
- size.times do |k|
- previous_pivot = pivot
- if (pivot = a[k][k]) == 0
- switch = (k+1 ... size).find(no_pivot) {|row|
- a[row][k] != 0
- }
- a[switch], a[k] = a[k], a[switch]
- pivot = a[k][k]
- sign = -sign
- end
- (k+1).upto(last) do |i|
- ai = a[i]
- (k+1).upto(last) do |j|
- ai[j] = (pivot * ai[j] - ai[k] * a[k][j]) / previous_pivot
- end
- end
- end
- sign * pivot
- end
- private :determinant_bareiss
-
- #
- # deprecated; use Matrix#determinant
- #
- def determinant_e
- warn "#{caller(1)[0]}: warning: Matrix#determinant_e is deprecated; use #determinant"
- rank
- end
- alias det_e determinant_e
-
- #
- # Returns the rank of the matrix.
- # Beware that using Float values can yield erroneous results
- # because of their lack of precision.
- # Consider using exact types like Rational or BigDecimal instead.
- #
- # Matrix[[7,6], [3,9]].rank
- # => 2
- #
- def rank
- # We currently use Bareiss' multistep integer-preserving gaussian elimination
- # (see comments on determinant)
- a = to_a
- last_column = column_size - 1
- last_row = row_size - 1
- pivot_row = 0
- previous_pivot = 1
- 0.upto(last_column) do |k|
- switch_row = (pivot_row .. last_row).find {|row|
- a[row][k] != 0
- }
- if switch_row
- a[switch_row], a[pivot_row] = a[pivot_row], a[switch_row] unless pivot_row == switch_row
- pivot = a[pivot_row][k]
- (pivot_row+1).upto(last_row) do |i|
- ai = a[i]
- (k+1).upto(last_column) do |j|
- ai[j] = (pivot * ai[j] - ai[k] * a[pivot_row][j]) / previous_pivot
- end
- end
- pivot_row += 1
- previous_pivot = pivot
- end
- end
- pivot_row
- end
-
- #
- # deprecated; use Matrix#rank
- #
- def rank_e
- warn "#{caller(1)[0]}: warning: Matrix#rank_e is deprecated; use #rank"
- rank
- end
-
- # Returns a matrix with entries rounded to the given precision
- # (see Float#round)
- #
- def round(ndigits=0)
- map{|e| e.round(ndigits)}
- end
-
- #
- # Returns the trace (sum of diagonal elements) of the matrix.
- # Matrix[[7,6], [3,9]].trace
- # => 16
- #
- def trace
- Matrix.Raise ErrDimensionMismatch unless square?
- (0...column_size).inject(0) do |tr, i|
- tr + @rows[i][i]
- end
- end
- alias tr trace
-
- #
- # Returns the transpose of the matrix.
- # Matrix[[1,2], [3,4], [5,6]]
- # => 1 2
- # 3 4
- # 5 6
- # Matrix[[1,2], [3,4], [5,6]].transpose
- # => 1 3 5
- # 2 4 6
- #
- def transpose
- return Matrix.empty(column_size, 0) if row_size.zero?
- new_matrix @rows.transpose, row_size
- end
- alias t transpose
-
- #--
- # DECOMPOSITIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- #++
-
- #
- # Returns the Eigensystem of the matrix; see +EigenvalueDecomposition+.
- # m = Matrix[[1, 2], [3, 4]]
- # v, d, v_inv = m.eigensystem
- # d.diagonal? # => true
- # v.inv == v_inv # => true
- # (v * d * v_inv).round(5) == m # => true
- #
- def eigensystem
- EigenvalueDecomposition.new(self)
- end
- alias eigen eigensystem
-
- #
- # Returns the LUP decomposition of the matrix; see +LUPDecomposition+.
- # a = Matrix[[1, 2], [3, 4]]
- # l, u, p = a.lup
- # l.lower_triangular? # => true
- # u.upper_triangular? # => true
- # p.permutation? # => true
- # l * u == a * p # => true
- # a.lup.solve([2, 5]) # => Vector[(1/1), (1/2)]
- #
- def lup
- LUPDecomposition.new(self)
- end
- alias lup_decomposition lup
-
- #--
- # COMPLEX ARITHMETIC -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- #++
-
- #
- # Returns the conjugate of the matrix.
- # Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]]
- # => 1+2i i 0
- # 1 2 3
- # Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]].conjugate
- # => 1-2i -i 0
- # 1 2 3
- #
- def conjugate
- collect(&:conjugate)
- end
- alias conj conjugate
-
- #
- # Returns the imaginary part of the matrix.
- # Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]]
- # => 1+2i i 0
- # 1 2 3
- # Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]].imaginary
- # => 2i i 0
- # 0 0 0
- #
- def imaginary
- collect(&:imaginary)
- end
- alias imag imaginary
-
- #
- # Returns the real part of the matrix.
- # Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]]
- # => 1+2i i 0
- # 1 2 3
- # Matrix[[Complex(1,2), Complex(0,1), 0], [1, 2, 3]].real
- # => 1 0 0
- # 1 2 3
- #
- def real
- collect(&:real)
- end
-
- #
- # Returns an array containing matrices corresponding to the real and imaginary
- # parts of the matrix
- #
- # m.rect == [m.real, m.imag] # ==> true for all matrices m
- #
- def rect
- [real, imag]
- end
- alias rectangular rect
-
- #--
- # CONVERTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
- #++
-
- #
- # The coerce method provides support for Ruby type coercion.
- # This coercion mechanism is used by Ruby to handle mixed-type
- # numeric operations: it is intended to find a compatible common
- # type between the two operands of the operator.
- # See also Numeric#coerce.
- #
- def coerce(other)
- case other
- when Numeric
- return Scalar.new(other), self
- else
- raise TypeError, "#{self.class} can't be coerced into #{other.class}"
- end
- end
-
- #
- # Returns an array of the row vectors of the matrix. See Vector.
- #
- def row_vectors
- Array.new(row_size) {|i|
- row(i)
- }
- end
-
- #
- # Returns an array of the column vectors of the matrix. See Vector.
- #
- def column_vectors
- Array.new(column_size) {|i|
- column(i)
- }
- end
-
- #
- # Returns an array of arrays that describe the rows of the matrix.
- #
- def to_a
- @rows.collect(&:dup)
- end
-
- def elements_to_f
- warn "#{caller(1)[0]}: warning: Matrix#elements_to_f is deprecated, use map(&:to_f)"
- map(&:to_f)
- end
-
- def elements_to_i
- warn "#{caller(1)[0]}: warning: Matrix#elements_to_i is deprecated, use map(&:to_i)"
- map(&:to_i)
- end
-
- def elements_to_r
- warn "#{caller(1)[0]}: warning: Matrix#elements_to_r is deprecated, use map(&:to_r)"
- map(&:to_r)
- end
-
- #--
- # PRINTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
- #++
-
- #
- # Overrides Object#to_s
- #
- def to_s
- if empty?
- "Matrix.empty(#{row_size}, #{column_size})"
- else
- "Matrix[" + @rows.collect{|row|
- "[" + row.collect{|e| e.to_s}.join(", ") + "]"
- }.join(", ")+"]"
- end
- end
-
- #
- # Overrides Object#inspect
- #
- def inspect
- if empty?
- "Matrix.empty(#{row_size}, #{column_size})"
- else
- "Matrix#{@rows.inspect}"
- end
- end
-
- # Private helper modules
-
- module ConversionHelper # :nodoc:
- #
- # Converts the obj to an Array. If copy is set to true
- # a copy of obj will be made if necessary.
- #
- def convert_to_array(obj, copy = false) # :nodoc:
- case obj
- when Array
- copy ? obj.dup : obj
- when Vector
- obj.to_a
- else
- begin
- converted = obj.to_ary
- rescue Exception => e
- raise TypeError, "can't convert #{obj.class} into an Array (#{e.message})"
- end
- raise TypeError, "#{obj.class}#to_ary should return an Array" unless converted.is_a? Array
- converted
- end
- end
- private :convert_to_array
- end
-
- extend ConversionHelper
-
- module CoercionHelper # :nodoc:
- #
- # Applies the operator +oper+ with argument +obj+
- # through coercion of +obj+
- #
- def apply_through_coercion(obj, oper)
- coercion = obj.coerce(self)
- raise TypeError unless coercion.is_a?(Array) && coercion.length == 2
- coercion[0].public_send(oper, coercion[1])
- rescue
- raise TypeError, "#{obj.inspect} can't be coerced into #{self.class}"
- end
- private :apply_through_coercion
-
- #
- # Helper method to coerce a value into a specific class.
- # Raises a TypeError if the coercion fails or the returned value
- # is not of the right class.
- # (from Rubinius)
- #
- def self.coerce_to(obj, cls, meth) # :nodoc:
- return obj if obj.kind_of?(cls)
-
- begin
- ret = obj.__send__(meth)
- rescue Exception => e
- raise TypeError, "Coercion error: #{obj.inspect}.#{meth} => #{cls} failed:\n" \
- "(#{e.message})"
- end
- raise TypeError, "Coercion error: obj.#{meth} did NOT return a #{cls} (was #{ret.class})" unless ret.kind_of? cls
- ret
- end
-
- def self.coerce_to_int(obj)
- coerce_to(obj, Integer, :to_int)
- end
- end
-
- include CoercionHelper
-
- # Private CLASS
-
- class Scalar < Numeric # :nodoc:
- include ExceptionForMatrix
- include CoercionHelper
-
- def initialize(value)
- @value = value
- end
-
- # ARITHMETIC
- def +(other)
- case other
- when Numeric
- Scalar.new(@value + other)
- when Vector, Matrix
- Scalar.Raise ErrOperationNotDefined, "+", @value.class, other.class
- else
- apply_through_coercion(other, __method__)
- end
- end
-
- def -(other)
- case other
- when Numeric
- Scalar.new(@value - other)
- when Vector, Matrix
- Scalar.Raise ErrOperationNotDefined, "-", @value.class, other.class
- else
- apply_through_coercion(other, __method__)
- end
- end
-
- def *(other)
- case other
- when Numeric
- Scalar.new(@value * other)
- when Vector, Matrix
- other.collect{|e| @value * e}
- else
- apply_through_coercion(other, __method__)
- end
- end
-
- def / (other)
- case other
- when Numeric
- Scalar.new(@value / other)
- when Vector
- Scalar.Raise ErrOperationNotDefined, "/", @value.class, other.class
- when Matrix
- self * other.inverse
- else
- apply_through_coercion(other, __method__)
- end
- end
-
- def ** (other)
- case other
- when Numeric
- Scalar.new(@value ** other)
- when Vector
- Scalar.Raise ErrOperationNotDefined, "**", @value.class, other.class
- when Matrix
- #other.powered_by(self)
- Scalar.Raise ErrOperationNotImplemented, "**", @value.class, other.class
- else
- apply_through_coercion(other, __method__)
- end
- end
- end
-
-end
-
-
-#
-# The +Vector+ class represents a mathematical vector, which is useful in its own right, and
-# also constitutes a row or column of a Matrix.
-#
-# == Method Catalogue
-#
-# To create a Vector:
-# * <tt> Vector.[](*array) </tt>
-# * <tt> Vector.elements(array, copy = true) </tt>
-#
-# To access elements:
-# * <tt> [](i) </tt>
-#
-# To enumerate the elements:
-# * <tt> #each2(v) </tt>
-# * <tt> #collect2(v) </tt>
-#
-# Vector arithmetic:
-# * <tt> *(x) "is matrix or number" </tt>
-# * <tt> +(v) </tt>
-# * <tt> -(v) </tt>
-#
-# Vector functions:
-# * <tt> #inner_product(v) </tt>
-# * <tt> #collect </tt>
-# * <tt> #magnitude </tt>
-# * <tt> #map </tt>
-# * <tt> #map2(v) </tt>
-# * <tt> #norm </tt>
-# * <tt> #normalize </tt>
-# * <tt> #r </tt>
-# * <tt> #size </tt>
-#
-# Conversion to other data types:
-# * <tt> #covector </tt>
-# * <tt> #to_a </tt>
-# * <tt> #coerce(other) </tt>
-#
-# String representations:
-# * <tt> #to_s </tt>
-# * <tt> #inspect </tt>
-#
-class Vector
- include ExceptionForMatrix
- include Enumerable
- include Matrix::CoercionHelper
- extend Matrix::ConversionHelper
- #INSTANCE CREATION
-
- private_class_method :new
- attr_reader :elements
- protected :elements
-
- #
- # Creates a Vector from a list of elements.
- # Vector[7, 4, ...]
- #
- def Vector.[](*array)
- new convert_to_array(array, false)
- end
-
- #
- # Creates a vector from an Array. The optional second argument specifies
- # whether the array itself or a copy is used internally.
- #
- def Vector.elements(array, copy = true)
- new convert_to_array(array, copy)
- end
-
- #
- # Vector.new is private; use Vector[] or Vector.elements to create.
- #
- def initialize(array)
- # No checking is done at this point.
- @elements = array
- end
-
- # ACCESSING
-
- #
- # Returns element number +i+ (starting at zero) of the vector.
- #
- def [](i)
- @elements[i]
- end
- alias element []
- alias component []
-
- def []=(i, v)
- @elements[i]= v
- end
- alias set_element []=
- alias set_component []=
- private :[]=, :set_element, :set_component
-
- #
- # Returns the number of elements in the vector.
- #
- def size
- @elements.size
- end
-
- #--
- # ENUMERATIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
- #++
-
- #
- # Iterate over the elements of this vector
- #
- def each(&block)
- return to_enum(:each) unless block_given?
- @elements.each(&block)
- self
- end
-
- #
- # Iterate over the elements of this vector and +v+ in conjunction.
- #
- def each2(v) # :yield: e1, e2
- raise TypeError, "Integer is not like Vector" if v.kind_of?(Integer)
- Vector.Raise ErrDimensionMismatch if size != v.size
- return to_enum(:each2, v) unless block_given?
- size.times do |i|
- yield @elements[i], v[i]
- end
- self
- end
-
- #
- # Collects (as in Enumerable#collect) over the elements of this vector and +v+
- # in conjunction.
- #
- def collect2(v) # :yield: e1, e2
- raise TypeError, "Integer is not like Vector" if v.kind_of?(Integer)
- Vector.Raise ErrDimensionMismatch if size != v.size
- return to_enum(:collect2, v) unless block_given?
- Array.new(size) do |i|
- yield @elements[i], v[i]
- end
- end
-
- #--
- # COMPARING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
- #++
-
- #
- # Returns +true+ iff the two vectors have the same elements in the same order.
- #
- def ==(other)
- return false unless Vector === other
- @elements == other.elements
- end
-
- def eql?(other)
- return false unless Vector === other
- @elements.eql? other.elements
- end
-
- #
- # Return a copy of the vector.
- #
- def clone
- Vector.elements(@elements)
- end
-
- #
- # Return a hash-code for the vector.
- #
- def hash
- @elements.hash
- end
-
- #--
- # ARITHMETIC -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
- #++
-
- #
- # Multiplies the vector by +x+, where +x+ is a number or another vector.
- #
- def *(x)
- case x
- when Numeric
- els = @elements.collect{|e| e * x}
- Vector.elements(els, false)
- when Matrix
- Matrix.column_vector(self) * x
- when Vector
- Vector.Raise ErrOperationNotDefined, "*", self.class, x.class
- else
- apply_through_coercion(x, __method__)
- end
- end
-
- #
- # Vector addition.
- #
- def +(v)
- case v
- when Vector
- Vector.Raise ErrDimensionMismatch if size != v.size
- els = collect2(v) {|v1, v2|
- v1 + v2
- }
- Vector.elements(els, false)
- when Matrix
- Matrix.column_vector(self) + v
- else
- apply_through_coercion(v, __method__)
- end
- end
-
- #
- # Vector subtraction.
- #
- def -(v)
- case v
- when Vector
- Vector.Raise ErrDimensionMismatch if size != v.size
- els = collect2(v) {|v1, v2|
- v1 - v2
- }
- Vector.elements(els, false)
- when Matrix
- Matrix.column_vector(self) - v
- else
- apply_through_coercion(v, __method__)
- end
- end
-
- #
- # Vector division.
- #
- def /(x)
- case x
- when Numeric
- els = @elements.collect{|e| e / x}
- Vector.elements(els, false)
- when Matrix, Vector
- Vector.Raise ErrOperationNotDefined, "/", self.class, x.class
- else
- apply_through_coercion(x, __method__)
- end
- end
-
- #--
- # VECTOR FUNCTIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
- #++
-
- #
- # Returns the inner product of this vector with the other.
- # Vector[4,7].inner_product Vector[10,1] => 47
- #
- def inner_product(v)
- Vector.Raise ErrDimensionMismatch if size != v.size
-
- p = 0
- each2(v) {|v1, v2|
- p += v1 * v2
- }
- p
- end
-
- #
- # Like Array#collect.
- #
- def collect(&block) # :yield: e
- return to_enum(:collect) unless block_given?
- els = @elements.collect(&block)
- Vector.elements(els, false)
- end
- alias map collect
-
- #
- # Returns the modulus (Pythagorean distance) of the vector.
- # Vector[5,8,2].r => 9.643650761
- #
- def magnitude
- Math.sqrt(@elements.inject(0) {|v, e| v + e*e})
- end
- alias r magnitude
- alias norm magnitude
-
- #
- # Like Vector#collect2, but returns a Vector instead of an Array.
- #
- def map2(v, &block) # :yield: e1, e2
- return to_enum(:map2, v) unless block_given?
- els = collect2(v, &block)
- Vector.elements(els, false)
- end
-
- class ZeroVectorError < StandardError
- end
- #
- # Returns a new vector with the same direction but with norm 1.
- # v = Vector[5,8,2].normalize
- # # => Vector[0.5184758473652127, 0.8295613557843402, 0.20739033894608505]
- # v.norm => 1.0
- #
- def normalize
- n = magnitude
- raise ZeroVectorError, "Zero vectors can not be normalized" if n == 0
- self / n
- end
-
- #--
- # CONVERTING
- #++
-
- #
- # Creates a single-row matrix from this vector.
- #
- def covector
- Matrix.row_vector(self)
- end
-
- #
- # Returns the elements of the vector in an array.
- #
- def to_a
- @elements.dup
- end
-
- def elements_to_f
- warn "#{caller(1)[0]}: warning: Vector#elements_to_f is deprecated"
- map(&:to_f)
- end
-
- def elements_to_i
- warn "#{caller(1)[0]}: warning: Vector#elements_to_i is deprecated"
- map(&:to_i)
- end
-
- def elements_to_r
- warn "#{caller(1)[0]}: warning: Vector#elements_to_r is deprecated"
- map(&:to_r)
- end
-
- #
- # The coerce method provides support for Ruby type coercion.
- # This coercion mechanism is used by Ruby to handle mixed-type
- # numeric operations: it is intended to find a compatible common
- # type between the two operands of the operator.
- # See also Numeric#coerce.
- #
- def coerce(other)
- case other
- when Numeric
- return Matrix::Scalar.new(other), self
- else
- raise TypeError, "#{self.class} can't be coerced into #{other.class}"
- end
- end
-
- #--
- # PRINTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
- #++
-
- #
- # Overrides Object#to_s
- #
- def to_s
- "Vector[" + @elements.join(", ") + "]"
- end
-
- #
- # Overrides Object#inspect
- #
- def inspect
- "Vector" + @elements.inspect
- end
-end
diff --git a/ruby_1_9_3/lib/matrix/eigenvalue_decomposition.rb b/ruby_1_9_3/lib/matrix/eigenvalue_decomposition.rb
deleted file mode 100644
index 55e41aaf7c..0000000000
--- a/ruby_1_9_3/lib/matrix/eigenvalue_decomposition.rb
+++ /dev/null
@@ -1,886 +0,0 @@
-class Matrix
- # Adapted from JAMA: http://math.nist.gov/javanumerics/jama/
-
- # Eigenvalues and eigenvectors of a real matrix.
- #
- # Computes the eigenvalues and eigenvectors of a matrix A.
- #
- # If A is diagonalizable, this provides matrices V and D
- # such that A = V*D*V.inv, where D is the diagonal matrix with entries
- # equal to the eigenvalues and V is formed by the eigenvectors.
- #
- # If A is symmetric, then V is orthogonal and thus A = V*D*V.t
-
- class EigenvalueDecomposition
-
- # Constructs the eigenvalue decomposition for a square matrix +A+
- #
- def initialize(a)
- # @d, @e: Arrays for internal storage of eigenvalues.
- # @v: Array for internal storage of eigenvectors.
- # @h: Array for internal storage of nonsymmetric Hessenberg form.
- raise TypeError, "Expected Matrix but got #{a.class}" unless a.is_a?(Matrix)
- @size = a.row_size
- @d = Array.new(@size, 0)
- @e = Array.new(@size, 0)
-
- if (@symmetric = a.symmetric?)
- @v = a.to_a
- tridiagonalize
- diagonalize
- else
- @v = Array.new(@size) { Array.new(@size, 0) }
- @h = a.to_a
- @ort = Array.new(@size, 0)
- reduce_to_hessenberg
- hessenberg_to_real_schur
- end
- end
-
- # Returns the eigenvector matrix +V+
- #
- def eigenvector_matrix
- Matrix.send :new, build_eigenvectors.transpose
- end
- alias v eigenvector_matrix
-
- # Returns the inverse of the eigenvector matrix +V+
- #
- def eigenvector_matrix_inv
- r = Matrix.send :new, build_eigenvectors
- r = r.transpose.inverse unless @symmetric
- r
- end
- alias v_inv eigenvector_matrix_inv
-
- # Returns the eigenvalues in an array
- #
- def eigenvalues
- values = @d.dup
- @e.each_with_index{|imag, i| values[i] = Complex(values[i], imag) unless imag == 0}
- values
- end
-
- # Returns an array of the eigenvectors
- #
- def eigenvectors
- build_eigenvectors.map{|ev| Vector.send :new, ev}
- end
-
- # Returns the block diagonal eigenvalue matrix +D+
- #
- def eigenvalue_matrix
- Matrix.diagonal(*eigenvalues)
- end
- alias d eigenvalue_matrix
-
- # Returns [eigenvector_matrix, eigenvalue_matrix, eigenvector_matrix_inv]
- #
- def to_ary
- [v, d, v_inv]
- end
- alias_method :to_a, :to_ary
-
- private
- def build_eigenvectors
- # JAMA stores complex eigenvectors in a strange way
- # See http://cio.nist.gov/esd/emaildir/lists/jama/msg01021.html
- @e.each_with_index.map do |imag, i|
- if imag == 0
- Array.new(@size){|j| @v[j][i]}
- elsif imag > 0
- Array.new(@size){|j| Complex(@v[j][i], @v[j][i+1])}
- else
- Array.new(@size){|j| Complex(@v[j][i], -@v[j][i-1])}
- end
- end
- end
- # Complex scalar division.
-
- def cdiv(xr, xi, yr, yi)
- if (yr.abs > yi.abs)
- r = yi/yr
- d = yr + r*yi
- [(xr + r*xi)/d, (xi - r*xr)/d]
- else
- r = yr/yi
- d = yi + r*yr
- [(r*xr + xi)/d, (r*xi - xr)/d]
- end
- end
-
-
- # Symmetric Householder reduction to tridiagonal form.
-
- def tridiagonalize
-
- # This is derived from the Algol procedures tred2 by
- # Bowdler, Martin, Reinsch, and Wilkinson, Handbook for
- # Auto. Comp., Vol.ii-Linear Algebra, and the corresponding
- # Fortran subroutine in EISPACK.
-
- @size.times do |j|
- @d[j] = @v[@size-1][j]
- end
-
- # Householder reduction to tridiagonal form.
-
- (@size-1).downto(0+1) do |i|
-
- # Scale to avoid under/overflow.
-
- scale = 0.0
- h = 0.0
- i.times do |k|
- scale = scale + @d[k].abs
- end
- if (scale == 0.0)
- @e[i] = @d[i-1]
- i.times do |j|
- @d[j] = @v[i-1][j]
- @v[i][j] = 0.0
- @v[j][i] = 0.0
- end
- else
-
- # Generate Householder vector.
-
- i.times do |k|
- @d[k] /= scale
- h += @d[k] * @d[k]
- end
- f = @d[i-1]
- g = Math.sqrt(h)
- if (f > 0)
- g = -g
- end
- @e[i] = scale * g
- h -= f * g
- @d[i-1] = f - g
- i.times do |j|
- @e[j] = 0.0
- end
-
- # Apply similarity transformation to remaining columns.
-
- i.times do |j|
- f = @d[j]
- @v[j][i] = f
- g = @e[j] + @v[j][j] * f
- (j+1).upto(i-1) do |k|
- g += @v[k][j] * @d[k]
- @e[k] += @v[k][j] * f
- end
- @e[j] = g
- end
- f = 0.0
- i.times do |j|
- @e[j] /= h
- f += @e[j] * @d[j]
- end
- hh = f / (h + h)
- i.times do |j|
- @e[j] -= hh * @d[j]
- end
- i.times do |j|
- f = @d[j]
- g = @e[j]
- j.upto(i-1) do |k|
- @v[k][j] -= (f * @e[k] + g * @d[k])
- end
- @d[j] = @v[i-1][j]
- @v[i][j] = 0.0
- end
- end
- @d[i] = h
- end
-
- # Accumulate transformations.
-
- 0.upto(@size-1-1) do |i|
- @v[@size-1][i] = @v[i][i]
- @v[i][i] = 1.0
- h = @d[i+1]
- if (h != 0.0)
- 0.upto(i) do |k|
- @d[k] = @v[k][i+1] / h
- end
- 0.upto(i) do |j|
- g = 0.0
- 0.upto(i) do |k|
- g += @v[k][i+1] * @v[k][j]
- end
- 0.upto(i) do |k|
- @v[k][j] -= g * @d[k]
- end
- end
- end
- 0.upto(i) do |k|
- @v[k][i+1] = 0.0
- end
- end
- @size.times do |j|
- @d[j] = @v[@size-1][j]
- @v[@size-1][j] = 0.0
- end
- @v[@size-1][@size-1] = 1.0
- @e[0] = 0.0
- end
-
-
- # Symmetric tridiagonal QL algorithm.
-
- def diagonalize
- # This is derived from the Algol procedures tql2, by
- # Bowdler, Martin, Reinsch, and Wilkinson, Handbook for
- # Auto. Comp., Vol.ii-Linear Algebra, and the corresponding
- # Fortran subroutine in EISPACK.
-
- 1.upto(@size-1) do |i|
- @e[i-1] = @e[i]
- end
- @e[@size-1] = 0.0
-
- f = 0.0
- tst1 = 0.0
- eps = Float::EPSILON
- @size.times do |l|
-
- # Find small subdiagonal element
-
- tst1 = [tst1, @d[l].abs + @e[l].abs].max
- m = l
- while (m < @size) do
- if (@e[m].abs <= eps*tst1)
- break
- end
- m+=1
- end
-
- # If m == l, @d[l] is an eigenvalue,
- # otherwise, iterate.
-
- if (m > l)
- iter = 0
- begin
- iter = iter + 1 # (Could check iteration count here.)
-
- # Compute implicit shift
-
- g = @d[l]
- p = (@d[l+1] - g) / (2.0 * @e[l])
- r = Math.hypot(p, 1.0)
- if (p < 0)
- r = -r
- end
- @d[l] = @e[l] / (p + r)
- @d[l+1] = @e[l] * (p + r)
- dl1 = @d[l+1]
- h = g - @d[l]
- (l+2).upto(@size-1) do |i|
- @d[i] -= h
- end
- f += h
-
- # Implicit QL transformation.
-
- p = @d[m]
- c = 1.0
- c2 = c
- c3 = c
- el1 = @e[l+1]
- s = 0.0
- s2 = 0.0
- (m-1).downto(l) do |i|
- c3 = c2
- c2 = c
- s2 = s
- g = c * @e[i]
- h = c * p
- r = Math.hypot(p, @e[i])
- @e[i+1] = s * r
- s = @e[i] / r
- c = p / r
- p = c * @d[i] - s * g
- @d[i+1] = h + s * (c * g + s * @d[i])
-
- # Accumulate transformation.
-
- @size.times do |k|
- h = @v[k][i+1]
- @v[k][i+1] = s * @v[k][i] + c * h
- @v[k][i] = c * @v[k][i] - s * h
- end
- end
- p = -s * s2 * c3 * el1 * @e[l] / dl1
- @e[l] = s * p
- @d[l] = c * p
-
- # Check for convergence.
-
- end while (@e[l].abs > eps*tst1)
- end
- @d[l] = @d[l] + f
- @e[l] = 0.0
- end
-
- # Sort eigenvalues and corresponding vectors.
-
- 0.upto(@size-2) do |i|
- k = i
- p = @d[i]
- (i+1).upto(@size-1) do |j|
- if (@d[j] < p)
- k = j
- p = @d[j]
- end
- end
- if (k != i)
- @d[k] = @d[i]
- @d[i] = p
- @size.times do |j|
- p = @v[j][i]
- @v[j][i] = @v[j][k]
- @v[j][k] = p
- end
- end
- end
- end
-
- # Nonsymmetric reduction to Hessenberg form.
-
- def reduce_to_hessenberg
- # This is derived from the Algol procedures orthes and ortran,
- # by Martin and Wilkinson, Handbook for Auto. Comp.,
- # Vol.ii-Linear Algebra, and the corresponding
- # Fortran subroutines in EISPACK.
-
- low = 0
- high = @size-1
-
- (low+1).upto(high-1) do |m|
-
- # Scale column.
-
- scale = 0.0
- m.upto(high) do |i|
- scale = scale + @h[i][m-1].abs
- end
- if (scale != 0.0)
-
- # Compute Householder transformation.
-
- h = 0.0
- high.downto(m) do |i|
- @ort[i] = @h[i][m-1]/scale
- h += @ort[i] * @ort[i]
- end
- g = Math.sqrt(h)
- if (@ort[m] > 0)
- g = -g
- end
- h -= @ort[m] * g
- @ort[m] = @ort[m] - g
-
- # Apply Householder similarity transformation
- # @h = (I-u*u'/h)*@h*(I-u*u')/h)
-
- m.upto(@size-1) do |j|
- f = 0.0
- high.downto(m) do |i|
- f += @ort[i]*@h[i][j]
- end
- f = f/h
- m.upto(high) do |i|
- @h[i][j] -= f*@ort[i]
- end
- end
-
- 0.upto(high) do |i|
- f = 0.0
- high.downto(m) do |j|
- f += @ort[j]*@h[i][j]
- end
- f = f/h
- m.upto(high) do |j|
- @h[i][j] -= f*@ort[j]
- end
- end
- @ort[m] = scale*@ort[m]
- @h[m][m-1] = scale*g
- end
- end
-
- # Accumulate transformations (Algol's ortran).
-
- @size.times do |i|
- @size.times do |j|
- @v[i][j] = (i == j ? 1.0 : 0.0)
- end
- end
-
- (high-1).downto(low+1) do |m|
- if (@h[m][m-1] != 0.0)
- (m+1).upto(high) do |i|
- @ort[i] = @h[i][m-1]
- end
- m.upto(high) do |j|
- g = 0.0
- m.upto(high) do |i|
- g += @ort[i] * @v[i][j]
- end
- # Double division avoids possible underflow
- g = (g / @ort[m]) / @h[m][m-1]
- m.upto(high) do |i|
- @v[i][j] += g * @ort[i]
- end
- end
- end
- end
- end
-
-
-
- # Nonsymmetric reduction from Hessenberg to real Schur form.
-
- def hessenberg_to_real_schur
-
- # This is derived from the Algol procedure hqr2,
- # by Martin and Wilkinson, Handbook for Auto. Comp.,
- # Vol.ii-Linear Algebra, and the corresponding
- # Fortran subroutine in EISPACK.
-
- # Initialize
-
- nn = @size
- n = nn-1
- low = 0
- high = nn-1
- eps = Float::EPSILON
- exshift = 0.0
- p=q=r=s=z=0
-
- # Store roots isolated by balanc and compute matrix norm
-
- norm = 0.0
- nn.times do |i|
- if (i < low || i > high)
- @d[i] = @h[i][i]
- @e[i] = 0.0
- end
- ([i-1, 0].max).upto(nn-1) do |j|
- norm = norm + @h[i][j].abs
- end
- end
-
- # Outer loop over eigenvalue index
-
- iter = 0
- while (n >= low) do
-
- # Look for single small sub-diagonal element
-
- l = n
- while (l > low) do
- s = @h[l-1][l-1].abs + @h[l][l].abs
- if (s == 0.0)
- s = norm
- end
- if (@h[l][l-1].abs < eps * s)
- break
- end
- l-=1
- end
-
- # Check for convergence
- # One root found
-
- if (l == n)
- @h[n][n] = @h[n][n] + exshift
- @d[n] = @h[n][n]
- @e[n] = 0.0
- n-=1
- iter = 0
-
- # Two roots found
-
- elsif (l == n-1)
- w = @h[n][n-1] * @h[n-1][n]
- p = (@h[n-1][n-1] - @h[n][n]) / 2.0
- q = p * p + w
- z = Math.sqrt(q.abs)
- @h[n][n] = @h[n][n] + exshift
- @h[n-1][n-1] = @h[n-1][n-1] + exshift
- x = @h[n][n]
-
- # Real pair
-
- if (q >= 0)
- if (p >= 0)
- z = p + z
- else
- z = p - z
- end
- @d[n-1] = x + z
- @d[n] = @d[n-1]
- if (z != 0.0)
- @d[n] = x - w / z
- end
- @e[n-1] = 0.0
- @e[n] = 0.0
- x = @h[n][n-1]
- s = x.abs + z.abs
- p = x / s
- q = z / s
- r = Math.sqrt(p * p+q * q)
- p /= r
- q /= r
-
- # Row modification
-
- (n-1).upto(nn-1) do |j|
- z = @h[n-1][j]
- @h[n-1][j] = q * z + p * @h[n][j]
- @h[n][j] = q * @h[n][j] - p * z
- end
-
- # Column modification
-
- 0.upto(n) do |i|
- z = @h[i][n-1]
- @h[i][n-1] = q * z + p * @h[i][n]
- @h[i][n] = q * @h[i][n] - p * z
- end
-
- # Accumulate transformations
-
- low.upto(high) do |i|
- z = @v[i][n-1]
- @v[i][n-1] = q * z + p * @v[i][n]
- @v[i][n] = q * @v[i][n] - p * z
- end
-
- # Complex pair
-
- else
- @d[n-1] = x + p
- @d[n] = x + p
- @e[n-1] = z
- @e[n] = -z
- end
- n -= 2
- iter = 0
-
- # No convergence yet
-
- else
-
- # Form shift
-
- x = @h[n][n]
- y = 0.0
- w = 0.0
- if (l < n)
- y = @h[n-1][n-1]
- w = @h[n][n-1] * @h[n-1][n]
- end
-
- # Wilkinson's original ad hoc shift
-
- if (iter == 10)
- exshift += x
- low.upto(n) do |i|
- @h[i][i] -= x
- end
- s = @h[n][n-1].abs + @h[n-1][n-2].abs
- x = y = 0.75 * s
- w = -0.4375 * s * s
- end
-
- # MATLAB's new ad hoc shift
-
- if (iter == 30)
- s = (y - x) / 2.0
- s *= s + w
- if (s > 0)
- s = Math.sqrt(s)
- if (y < x)
- s = -s
- end
- s = x - w / ((y - x) / 2.0 + s)
- low.upto(n) do |i|
- @h[i][i] -= s
- end
- exshift += s
- x = y = w = 0.964
- end
- end
-
- iter = iter + 1 # (Could check iteration count here.)
-
- # Look for two consecutive small sub-diagonal elements
-
- m = n-2
- while (m >= l) do
- z = @h[m][m]
- r = x - z
- s = y - z
- p = (r * s - w) / @h[m+1][m] + @h[m][m+1]
- q = @h[m+1][m+1] - z - r - s
- r = @h[m+2][m+1]
- s = p.abs + q.abs + r.abs
- p /= s
- q /= s
- r /= s
- if (m == l)
- break
- end
- if (@h[m][m-1].abs * (q.abs + r.abs) <
- eps * (p.abs * (@h[m-1][m-1].abs + z.abs +
- @h[m+1][m+1].abs)))
- break
- end
- m-=1
- end
-
- (m+2).upto(n) do |i|
- @h[i][i-2] = 0.0
- if (i > m+2)
- @h[i][i-3] = 0.0
- end
- end
-
- # Double QR step involving rows l:n and columns m:n
-
- m.upto(n-1) do |k|
- notlast = (k != n-1)
- if (k != m)
- p = @h[k][k-1]
- q = @h[k+1][k-1]
- r = (notlast ? @h[k+2][k-1] : 0.0)
- x = p.abs + q.abs + r.abs
- if (x != 0.0)
- p /= x
- q /= x
- r /= x
- end
- end
- if (x == 0.0)
- break
- end
- s = Math.sqrt(p * p + q * q + r * r)
- if (p < 0)
- s = -s
- end
- if (s != 0)
- if (k != m)
- @h[k][k-1] = -s * x
- elsif (l != m)
- @h[k][k-1] = -@h[k][k-1]
- end
- p += s
- x = p / s
- y = q / s
- z = r / s
- q /= p
- r /= p
-
- # Row modification
-
- k.upto(nn-1) do |j|
- p = @h[k][j] + q * @h[k+1][j]
- if (notlast)
- p += r * @h[k+2][j]
- @h[k+2][j] = @h[k+2][j] - p * z
- end
- @h[k][j] = @h[k][j] - p * x
- @h[k+1][j] = @h[k+1][j] - p * y
- end
-
- # Column modification
-
- 0.upto([n, k+3].min) do |i|
- p = x * @h[i][k] + y * @h[i][k+1]
- if (notlast)
- p += z * @h[i][k+2]
- @h[i][k+2] = @h[i][k+2] - p * r
- end
- @h[i][k] = @h[i][k] - p
- @h[i][k+1] = @h[i][k+1] - p * q
- end
-
- # Accumulate transformations
-
- low.upto(high) do |i|
- p = x * @v[i][k] + y * @v[i][k+1]
- if (notlast)
- p += z * @v[i][k+2]
- @v[i][k+2] = @v[i][k+2] - p * r
- end
- @v[i][k] = @v[i][k] - p
- @v[i][k+1] = @v[i][k+1] - p * q
- end
- end # (s != 0)
- end # k loop
- end # check convergence
- end # while (n >= low)
-
- # Backsubstitute to find vectors of upper triangular form
-
- if (norm == 0.0)
- return
- end
-
- (nn-1).downto(0) do |n|
- p = @d[n]
- q = @e[n]
-
- # Real vector
-
- if (q == 0)
- l = n
- @h[n][n] = 1.0
- (n-1).downto(0) do |i|
- w = @h[i][i] - p
- r = 0.0
- l.upto(n) do |j|
- r += @h[i][j] * @h[j][n]
- end
- if (@e[i] < 0.0)
- z = w
- s = r
- else
- l = i
- if (@e[i] == 0.0)
- if (w != 0.0)
- @h[i][n] = -r / w
- else
- @h[i][n] = -r / (eps * norm)
- end
-
- # Solve real equations
-
- else
- x = @h[i][i+1]
- y = @h[i+1][i]
- q = (@d[i] - p) * (@d[i] - p) + @e[i] * @e[i]
- t = (x * s - z * r) / q
- @h[i][n] = t
- if (x.abs > z.abs)
- @h[i+1][n] = (-r - w * t) / x
- else
- @h[i+1][n] = (-s - y * t) / z
- end
- end
-
- # Overflow control
-
- t = @h[i][n].abs
- if ((eps * t) * t > 1)
- i.upto(n) do |j|
- @h[j][n] = @h[j][n] / t
- end
- end
- end
- end
-
- # Complex vector
-
- elsif (q < 0)
- l = n-1
-
- # Last vector component imaginary so matrix is triangular
-
- if (@h[n][n-1].abs > @h[n-1][n].abs)
- @h[n-1][n-1] = q / @h[n][n-1]
- @h[n-1][n] = -(@h[n][n] - p) / @h[n][n-1]
- else
- cdivr, cdivi = cdiv(0.0, -@h[n-1][n], @h[n-1][n-1]-p, q)
- @h[n-1][n-1] = cdivr
- @h[n-1][n] = cdivi
- end
- @h[n][n-1] = 0.0
- @h[n][n] = 1.0
- (n-2).downto(0) do |i|
- ra = 0.0
- sa = 0.0
- l.upto(n) do |j|
- ra = ra + @h[i][j] * @h[j][n-1]
- sa = sa + @h[i][j] * @h[j][n]
- end
- w = @h[i][i] - p
-
- if (@e[i] < 0.0)
- z = w
- r = ra
- s = sa
- else
- l = i
- if (@e[i] == 0)
- cdivr, cdivi = cdiv(-ra, -sa, w, q)
- @h[i][n-1] = cdivr
- @h[i][n] = cdivi
- else
-
- # Solve complex equations
-
- x = @h[i][i+1]
- y = @h[i+1][i]
- vr = (@d[i] - p) * (@d[i] - p) + @e[i] * @e[i] - q * q
- vi = (@d[i] - p) * 2.0 * q
- if (vr == 0.0 && vi == 0.0)
- vr = eps * norm * (w.abs + q.abs +
- x.abs + y.abs + z.abs)
- end
- cdivr, cdivi = cdiv(x*r-z*ra+q*sa, x*s-z*sa-q*ra, vr, vi)
- @h[i][n-1] = cdivr
- @h[i][n] = cdivi
- if (x.abs > (z.abs + q.abs))
- @h[i+1][n-1] = (-ra - w * @h[i][n-1] + q * @h[i][n]) / x
- @h[i+1][n] = (-sa - w * @h[i][n] - q * @h[i][n-1]) / x
- else
- cdivr, cdivi = cdiv(-r-y*@h[i][n-1], -s-y*@h[i][n], z, q)
- @h[i+1][n-1] = cdivr
- @h[i+1][n] = cdivi
- end
- end
-
- # Overflow control
-
- t = [@h[i][n-1].abs, @h[i][n].abs].max
- if ((eps * t) * t > 1)
- i.upto(n) do |j|
- @h[j][n-1] = @h[j][n-1] / t
- @h[j][n] = @h[j][n] / t
- end
- end
- end
- end
- end
- end
-
- # Vectors of isolated roots
-
- nn.times do |i|
- if (i < low || i > high)
- i.upto(nn-1) do |j|
- @v[i][j] = @h[i][j]
- end
- end
- end
-
- # Back transformation to get eigenvectors of original matrix
-
- (nn-1).downto(low) do |j|
- low.upto(high) do |i|
- z = 0.0
- low.upto([j, high].min) do |k|
- z += @v[i][k] * @h[k][j]
- end
- @v[i][j] = z
- end
- end
- end
-
- end
-end
diff --git a/ruby_1_9_3/lib/matrix/lup_decomposition.rb b/ruby_1_9_3/lib/matrix/lup_decomposition.rb
deleted file mode 100644
index 8f5aac2e5a..0000000000
--- a/ruby_1_9_3/lib/matrix/lup_decomposition.rb
+++ /dev/null
@@ -1,218 +0,0 @@
-class Matrix
- # Adapted from JAMA: http://math.nist.gov/javanumerics/jama/
-
- #
- # For an m-by-n matrix A with m >= n, the LU decomposition is an m-by-n
- # unit lower triangular matrix L, an n-by-n upper triangular matrix U,
- # and a m-by-m permutation matrix P so that L*U = P*A.
- # If m < n, then L is m-by-m and U is m-by-n.
- #
- # The LUP decomposition with pivoting always exists, even if the matrix is
- # singular, so the constructor will never fail. The primary use of the
- # LU decomposition is in the solution of square systems of simultaneous
- # linear equations. This will fail if singular? returns true.
- #
-
- class LUPDecomposition
- # Returns the lower triangular factor +L+
-
- include Matrix::ConversionHelper
-
- def l
- Matrix.build(@row_size, @col_size) do |i, j|
- if (i > j)
- @lu[i][j]
- elsif (i == j)
- 1
- else
- 0
- end
- end
- end
-
- # Returns the upper triangular factor +U+
-
- def u
- Matrix.build(@col_size, @col_size) do |i, j|
- if (i <= j)
- @lu[i][j]
- else
- 0
- end
- end
- end
-
- # Returns the permutation matrix +P+
-
- def p
- rows = Array.new(@row_size){Array.new(@col_size, 0)}
- @pivots.each_with_index{|p, i| rows[i][p] = 1}
- Matrix.send :new, rows, @col_size
- end
-
- # Returns +L+, +U+, +P+ in an array
-
- def to_ary
- [l, u, p]
- end
- alias_method :to_a, :to_ary
-
- # Returns the pivoting indices
-
- attr_reader :pivots
-
- # Returns +true+ if +U+, and hence +A+, is singular.
-
- def singular? ()
- @col_size.times do |j|
- if (@lu[j][j] == 0)
- return true
- end
- end
- false
- end
-
- # Returns the determinant of +A+, calculated efficiently
- # from the factorization.
-
- def det
- if (@row_size != @col_size)
- Matrix.Raise Matrix::ErrDimensionMismatch unless square?
- end
- d = @pivot_sign
- @col_size.times do |j|
- d *= @lu[j][j]
- end
- d
- end
- alias_method :determinant, :det
-
- # Returns +m+ so that <tt>A*m = b</tt>,
- # or equivalently so that <tt>L*U*m = P*b</tt>
- # +b+ can be a Matrix or a Vector
-
- def solve b
- if (singular?)
- Matrix.Raise Matrix::ErrNotRegular, "Matrix is singular."
- end
- if b.is_a? Matrix
- if (b.row_size != @row_size)
- Matrix.Raise Matrix::ErrDimensionMismatch
- end
-
- # Copy right hand side with pivoting
- nx = b.column_size
- m = @pivots.map{|row| b.row(row).to_a}
-
- # Solve L*Y = P*b
- @col_size.times do |k|
- (k+1).upto(@col_size-1) do |i|
- nx.times do |j|
- m[i][j] -= m[k][j]*@lu[i][k]
- end
- end
- end
- # Solve U*m = Y
- (@col_size-1).downto(0) do |k|
- nx.times do |j|
- m[k][j] = m[k][j].quo(@lu[k][k])
- end
- k.times do |i|
- nx.times do |j|
- m[i][j] -= m[k][j]*@lu[i][k]
- end
- end
- end
- Matrix.send :new, m, nx
- else # same algorithm, specialized for simpler case of a vector
- b = convert_to_array(b)
- if (b.size != @row_size)
- Matrix.Raise Matrix::ErrDimensionMismatch
- end
-
- # Copy right hand side with pivoting
- m = b.values_at(*@pivots)
-
- # Solve L*Y = P*b
- @col_size.times do |k|
- (k+1).upto(@col_size-1) do |i|
- m[i] -= m[k]*@lu[i][k]
- end
- end
- # Solve U*m = Y
- (@col_size-1).downto(0) do |k|
- m[k] = m[k].quo(@lu[k][k])
- k.times do |i|
- m[i] -= m[k]*@lu[i][k]
- end
- end
- Vector.elements(m, false)
- end
- end
-
- def initialize a
- raise TypeError, "Expected Matrix but got #{a.class}" unless a.is_a?(Matrix)
- # Use a "left-looking", dot-product, Crout/Doolittle algorithm.
- @lu = a.to_a
- @row_size = a.row_size
- @col_size = a.column_size
- @pivots = Array.new(@row_size)
- @row_size.times do |i|
- @pivots[i] = i
- end
- @pivot_sign = 1
- lu_col_j = Array.new(@row_size)
-
- # Outer loop.
-
- @col_size.times do |j|
-
- # Make a copy of the j-th column to localize references.
-
- @row_size.times do |i|
- lu_col_j[i] = @lu[i][j]
- end
-
- # Apply previous transformations.
-
- @row_size.times do |i|
- lu_row_i = @lu[i]
-
- # Most of the time is spent in the following dot product.
-
- kmax = [i, j].min
- s = 0
- kmax.times do |k|
- s += lu_row_i[k]*lu_col_j[k]
- end
-
- lu_row_i[j] = lu_col_j[i] -= s
- end
-
- # Find pivot and exchange if necessary.
-
- p = j
- (j+1).upto(@row_size-1) do |i|
- if (lu_col_j[i].abs > lu_col_j[p].abs)
- p = i
- end
- end
- if (p != j)
- @col_size.times do |k|
- t = @lu[p][k]; @lu[p][k] = @lu[j][k]; @lu[j][k] = t
- end
- k = @pivots[p]; @pivots[p] = @pivots[j]; @pivots[j] = k
- @pivot_sign = -@pivot_sign
- end
-
- # Compute multipliers.
-
- if (j < @row_size && @lu[j][j] != 0)
- (j+1).upto(@row_size-1) do |i|
- @lu[i][j] = @lu[i][j].quo(@lu[j][j])
- end
- end
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/minitest/README.txt b/ruby_1_9_3/lib/minitest/README.txt
deleted file mode 100644
index 7b1e6e681f..0000000000
--- a/ruby_1_9_3/lib/minitest/README.txt
+++ /dev/null
@@ -1,269 +0,0 @@
-= minitest/*
-
-* http://rubyforge.org/projects/bfts
-
-== DESCRIPTION:
-
-minitest provides a complete suite of testing facilities supporting
-TDD, BDD, mocking, and benchmarking.
-
-minitest/unit is a small and incredibly fast unit testing framework.
-It provides a rich set of assertions to make your tests clean and
-readable.
-
-minitest/spec is a functionally complete spec engine. It hooks onto
-minitest/unit and seamlessly bridges test assertions over to spec
-expectations.
-
-minitest/benchmark is an awesome way to assert the performance of your
-algorithms in a repeatable manner. Now you can assert that your newb
-co-worker doesn't replace your linear algorithm with an exponential
-one!
-
-minitest/mock by Steven Baker, is a beautifully tiny mock object
-framework.
-
-minitest/pride shows pride in testing and adds coloring to your test
-output.
-
-minitest/unit is meant to have a clean implementation for language
-implementors that need a minimal set of methods to bootstrap a working
-test suite. For example, there is no magic involved for test-case
-discovery.
-
-== FEATURES/PROBLEMS:
-
-* minitest/autorun - the easy and explicit way to run all your tests.
-* minitest/unit - a very fast, simple, and clean test system.
-* minitest/spec - a very fast, simple, and clean spec system.
-* minitest/mock - a simple and clean mock system.
-* minitest/benchmark - an awesome way to assert your algorithm's performance.
-* minitest/pride - show your pride in testing!
-* Incredibly small and fast runner, but no bells and whistles.
-
-== RATIONALE:
-
-See design_rationale.rb to see how specs and tests work in minitest.
-
-== SYNOPSIS:
-
-Given that you'd like to test the following class:
-
- class Meme
- def i_can_has_cheezburger?
- "OHAI!"
- end
-
- def will_it_blend?
- "YES!"
- end
- end
-
-=== Unit tests
-
- require 'minitest/autorun'
-
- class TestMeme < MiniTest::Unit::TestCase
- def setup
- @meme = Meme.new
- end
-
- def test_that_kitty_can_eat
- assert_equal "OHAI!", @meme.i_can_has_cheezburger?
- end
-
- def test_that_it_will_not_blend
- refute_match /^no/i, @meme.will_it_blend?
- end
- end
-
-=== Specs
-
- require 'minitest/autorun'
-
- describe Meme do
- before do
- @meme = Meme.new
- end
-
- describe "when asked about cheeseburgers" do
- it "must respond positively" do
- @meme.i_can_has_cheezburger?.must_equal "OHAI!"
- end
- end
-
- describe "when asked about blending possibilities" do
- it "won't say no" do
- @meme.will_it_blend?.wont_match /^no/i
- end
- end
- end
-
-=== Benchmarks
-
-Add benchmarks to your regular unit tests. If the unit tests fail, the
-benchmarks won't run.
-
- # optionally run benchmarks, good for CI-only work!
- require 'minitest/benchmark' if ENV["BENCH"]
-
- class TestMeme < MiniTest::Unit::TestCase
- # Override self.bench_range or default range is [1, 10, 100, 1_000, 10_000]
- def bench_my_algorithm
- assert_performance_linear 0.9999 do |n| # n is a range value
- n.times do
- @obj.my_algorithm
- end
- end
- end
- end
-
-Or add them to your specs. If you make benchmarks optional, you'll
-need to wrap your benchmarks in a conditional since the methods won't
-be defined.
-
- describe Meme do
- if ENV["BENCH"] then
- bench_performance_linear "my_algorithm", 0.9999 do |n|
- 100.times do
- @obj.my_algorithm(n)
- end
- end
- end
- end
-
-outputs something like:
-
- # Running benchmarks:
-
- TestBlah 100 1000 10000
- bench_my_algorithm 0.006167 0.079279 0.786993
- bench_other_algorithm 0.061679 0.792797 7.869932
-
-Output is tab-delimited to make it easy to paste into a spreadsheet.
-
-=== Mocks
-
- class MemeAsker
- def initialize(meme)
- @meme = meme
- end
-
- def ask(question)
- method = question.tr(" ","_") + "?"
- @meme.send(method)
- end
- end
-
- require 'minitest/autorun'
-
- describe MemeAsker do
- before do
- @meme = MiniTest::Mock.new
- @meme_asker = MemeAsker.new @meme
- end
-
- describe "#ask" do
- describe "when passed an unpunctuated question" do
- it "should invoke the appropriate predicate method on the meme" do
- @meme.expect :will_it_blend?, :return_value
- @meme_asker.ask "will it blend"
- @meme.verify
- end
- end
- end
- end
-
-=== Customizable Test Runner Types:
-
-MiniTest::Unit.runner=(runner) provides an easy way of creating custom
-test runners for specialized needs. Justin Weiss provides the
-following real-world example to create an alternative to regular
-fixture loading:
-
- class MiniTestWithHooks::Unit < MiniTest::Unit
- def before_suites
- end
-
- def after_suites
- end
-
- def _run_suites(suites, type)
- begin
- before_suites
- super(suites, type)
- ensure
- after_suites
- end
- end
-
- def _run_suite(suite, type)
- begin
- suite.before_suite
- super(suite, type)
- ensure
- suite.after_suite
- end
- end
- end
-
- module MiniTestWithTransactions
- class Unit < MiniTestWithHooks::Unit
- include TestSetupHelper
-
- def before_suites
- super
- setup_nested_transactions
- # load any data we want available for all tests
- end
-
- def after_suites
- teardown_nested_transactions
- super
- end
- end
- end
-
- MiniTest::Unit.runner = MiniTestWithTransactions::Unit.new
-
-== REQUIREMENTS:
-
-* Ruby 1.8, maybe even 1.6 or lower. No magic is involved.
-
-== INSTALL:
-
- sudo gem install minitest
-
-On 1.9, you already have it. To get newer candy you can still install
-the gem, but you'll need to activate the gem explicitly to use it:
-
- require 'rubygems'
- gem 'minitest' # ensures you're using the gem, and not the built in MT
- require 'minitest/autorun'
-
- # ... usual testing stuffs ...
-
-== LICENSE:
-
-(The MIT License)
-
-Copyright (c) Ryan Davis, Seattle.rb
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-'Software'), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/ruby_1_9_3/lib/minitest/autorun.rb b/ruby_1_9_3/lib/minitest/autorun.rb
deleted file mode 100644
index 443f2f61d4..0000000000
--- a/ruby_1_9_3/lib/minitest/autorun.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-######################################################################
-# This file is imported from the minitest project.
-# DO NOT make modifications in this repo. They _will_ be reverted!
-# File a patch instead and assign it to Ryan Davis.
-######################################################################
-
-begin
- require 'rubygems'
- gem 'minitest'
-rescue Gem::LoadError
- # do nothing
-end
-
-require 'minitest/unit'
-require 'minitest/spec'
-require 'minitest/mock'
-
-MiniTest::Unit.autorun
diff --git a/ruby_1_9_3/lib/minitest/benchmark.rb b/ruby_1_9_3/lib/minitest/benchmark.rb
deleted file mode 100644
index 77c0afafb7..0000000000
--- a/ruby_1_9_3/lib/minitest/benchmark.rb
+++ /dev/null
@@ -1,372 +0,0 @@
-######################################################################
-# This file is imported from the minitest project.
-# DO NOT make modifications in this repo. They _will_ be reverted!
-# File a patch instead and assign it to Ryan Davis.
-######################################################################
-
-require 'minitest/unit'
-require 'minitest/spec'
-
-class MiniTest::Unit
- attr_accessor :runner
-
- def run_benchmarks # :nodoc:
- _run_anything :benchmark
- end
-
- def benchmark_suite_header suite # :nodoc:
- "\n#{suite}\t#{suite.bench_range.join("\t")}"
- end
-
- class TestCase
- ##
- # Returns a set of ranges stepped exponentially from +min+ to
- # +max+ by powers of +base+. Eg:
- #
- # bench_exp(2, 16, 2) # => [2, 4, 8, 16]
-
- def self.bench_exp min, max, base = 10
- min = (Math.log10(min) / Math.log10(base)).to_i
- max = (Math.log10(max) / Math.log10(base)).to_i
-
- (min..max).map { |m| base ** m }.to_a
- end
-
- ##
- # Returns a set of ranges stepped linearly from +min+ to +max+ by
- # +step+. Eg:
- #
- # bench_linear(20, 40, 10) # => [20, 30, 40]
-
- def self.bench_linear min, max, step = 10
- (min..max).step(step).to_a
- rescue LocalJumpError # 1.8.6
- r = []; (min..max).step(step) { |n| r << n }; r
- end
-
- ##
- # Returns the benchmark methods (methods that start with bench_)
- # for that class.
-
- def self.benchmark_methods # :nodoc:
- public_instance_methods(true).grep(/^bench_/).map { |m| m.to_s }.sort
- end
-
- ##
- # Returns all test suites that have benchmark methods.
-
- def self.benchmark_suites
- TestCase.test_suites.reject { |s| s.benchmark_methods.empty? }
- end
-
- ##
- # Specifies the ranges used for benchmarking for that class.
- # Defaults to exponential growth from 1 to 10k by powers of 10.
- # Override if you need different ranges for your benchmarks.
- #
- # See also: ::bench_exp and ::bench_linear.
-
- def self.bench_range
- bench_exp 1, 10_000
- end
-
- ##
- # Runs the given +work+, gathering the times of each run. Range
- # and times are then passed to a given +validation+ proc. Outputs
- # the benchmark name and times in tab-separated format, making it
- # easy to paste into a spreadsheet for graphing or further
- # analysis.
- #
- # Ranges are specified by ::bench_range.
- #
- # Eg:
- #
- # def bench_algorithm
- # validation = proc { |x, y| ... }
- # assert_performance validation do |x|
- # @obj.algorithm
- # end
- # end
-
- def assert_performance validation, &work
- range = self.class.bench_range
-
- io.print "#{__name__}"
-
- times = []
-
- range.each do |x|
- GC.start
- t0 = Time.now
- instance_exec(x, &work)
- t = Time.now - t0
-
- io.print "\t%9.6f" % t
- times << t
- end
- io.puts
-
- validation[range, times]
- end
-
- ##
- # Runs the given +work+ and asserts that the times gathered fit to
- # match a constant rate (eg, linear slope == 0) within a given
- # +threshold+. Note: because we're testing for a slope of 0, R^2
- # is not a good determining factor for the fit, so the threshold
- # is applied against the slope itself. As such, you probably want
- # to tighten it from the default.
- #
- # See http://www.graphpad.com/curvefit/goodness_of_fit.htm for
- # more details.
- #
- # Fit is calculated by #fit_linear.
- #
- # Ranges are specified by ::bench_range.
- #
- # Eg:
- #
- # def bench_algorithm
- # assert_performance_constant 0.9999 do |x|
- # @obj.algorithm
- # end
- # end
-
- def assert_performance_constant threshold = 0.99, &work
- validation = proc do |range, times|
- a, b, rr = fit_linear range, times
- assert_in_delta 0, b, 1 - threshold
- [a, b, rr]
- end
-
- assert_performance validation, &work
- end
-
- ##
- # Runs the given +work+ and asserts that the times gathered fit to
- # match a exponential curve within a given error +threshold+.
- #
- # Fit is calculated by #fit_exponential.
- #
- # Ranges are specified by ::bench_range.
- #
- # Eg:
- #
- # def bench_algorithm
- # assert_performance_exponential 0.9999 do |x|
- # @obj.algorithm
- # end
- # end
-
- def assert_performance_exponential threshold = 0.99, &work
- assert_performance validation_for_fit(:exponential, threshold), &work
- end
-
- ##
- # Runs the given +work+ and asserts that the times gathered fit to
- # match a straight line within a given error +threshold+.
- #
- # Fit is calculated by #fit_linear.
- #
- # Ranges are specified by ::bench_range.
- #
- # Eg:
- #
- # def bench_algorithm
- # assert_performance_linear 0.9999 do |x|
- # @obj.algorithm
- # end
- # end
-
- def assert_performance_linear threshold = 0.99, &work
- assert_performance validation_for_fit(:linear, threshold), &work
- end
-
- ##
- # Runs the given +work+ and asserts that the times gathered curve
- # fit to match a power curve within a given error +threshold+.
- #
- # Fit is calculated by #fit_power.
- #
- # Ranges are specified by ::bench_range.
- #
- # Eg:
- #
- # def bench_algorithm
- # assert_performance_power 0.9999 do |x|
- # @obj.algorithm
- # end
- # end
-
- def assert_performance_power threshold = 0.99, &work
- assert_performance validation_for_fit(:power, threshold), &work
- end
-
- ##
- # Takes an array of x/y pairs and calculates the general R^2 value.
- #
- # See: http://en.wikipedia.org/wiki/Coefficient_of_determination
-
- def fit_error xys
- y_bar = sigma(xys) { |x, y| y } / xys.size.to_f
- ss_tot = sigma(xys) { |x, y| (y - y_bar) ** 2 }
- ss_err = sigma(xys) { |x, y| (yield(x) - y) ** 2 }
-
- 1 - (ss_err / ss_tot)
- end
-
- ##
- # To fit a functional form: y = ae^(bx).
- #
- # Takes x and y values and returns [a, b, r^2].
- #
- # See: http://mathworld.wolfram.com/LeastSquaresFittingExponential.html
-
- def fit_exponential xs, ys
- n = xs.size
- xys = xs.zip(ys)
- sxlny = sigma(xys) { |x,y| x * Math.log(y) }
- slny = sigma(xys) { |x,y| Math.log(y) }
- sx2 = sigma(xys) { |x,y| x * x }
- sx = sigma xs
-
- c = n * sx2 - sx ** 2
- a = (slny * sx2 - sx * sxlny) / c
- b = ( n * sxlny - sx * slny ) / c
-
- return Math.exp(a), b, fit_error(xys) { |x| Math.exp(a + b * x) }
- end
-
- ##
- # Fits the functional form: a + bx.
- #
- # Takes x and y values and returns [a, b, r^2].
- #
- # See: http://mathworld.wolfram.com/LeastSquaresFitting.html
-
- def fit_linear xs, ys
- n = xs.size
- xys = xs.zip(ys)
- sx = sigma xs
- sy = sigma ys
- sx2 = sigma(xs) { |x| x ** 2 }
- sxy = sigma(xys) { |x,y| x * y }
-
- c = n * sx2 - sx**2
- a = (sy * sx2 - sx * sxy) / c
- b = ( n * sxy - sx * sy ) / c
-
- return a, b, fit_error(xys) { |x| a + b * x }
- end
-
- ##
- # To fit a functional form: y = ax^b.
- #
- # Takes x and y values and returns [a, b, r^2].
- #
- # See: http://mathworld.wolfram.com/LeastSquaresFittingPowerLaw.html
-
- def fit_power xs, ys
- n = xs.size
- xys = xs.zip(ys)
- slnxlny = sigma(xys) { |x, y| Math.log(x) * Math.log(y) }
- slnx = sigma(xs) { |x | Math.log(x) }
- slny = sigma(ys) { | y| Math.log(y) }
- slnx2 = sigma(xs) { |x | Math.log(x) ** 2 }
-
- b = (n * slnxlny - slnx * slny) / (n * slnx2 - slnx ** 2);
- a = (slny - b * slnx) / n
-
- return Math.exp(a), b, fit_error(xys) { |x| (Math.exp(a) * (x ** b)) }
- end
-
- ##
- # Enumerates over +enum+ mapping +block+ if given, returning the
- # sum of the result. Eg:
- #
- # sigma([1, 2, 3]) # => 1 + 2 + 3 => 7
- # sigma([1, 2, 3]) { |n| n ** 2 } # => 1 + 4 + 9 => 14
-
- def sigma enum, &block
- enum = enum.map(&block) if block
- enum.inject { |sum, n| sum + n }
- end
-
- ##
- # Returns a proc that calls the specified fit method and asserts
- # that the error is within a tolerable threshold.
-
- def validation_for_fit msg, threshold
- proc do |range, times|
- a, b, rr = send "fit_#{msg}", range, times
- assert_operator rr, :>=, threshold
- [a, b, rr]
- end
- end
- end
-end
-
-class MiniTest::Spec
- ##
- # This is used to define a new benchmark method. You usually don't
- # use this directly and is intended for those needing to write new
- # performance curve fits (eg: you need a specific polynomial fit).
- #
- # See ::bench_performance_linear for an example of how to use this.
-
- def self.bench name, &block
- define_method "bench_#{name.gsub(/\W+/, '_')}", &block
- end
-
- def self.bench_range &block
- return super unless block
-
- meta = (class << self; self; end)
- meta.send :define_method, "bench_range", &block
- end
-
- ##
- # Create a benchmark that verifies that the performance is linear.
- #
- # describe "my class" do
- # bench_performance_linear "fast_algorithm", 0.9999 do
- # @obj.fast_algorithm
- # end
- # end
-
- def self.bench_performance_linear name, threshold = 0.99, &work
- bench name do
- assert_performance_linear threshold, &work
- end
- end
-
- ##
- # Create a benchmark that verifies that the performance is constant.
- #
- # describe "my class" do
- # bench_performance_constant "zoom_algorithm!" do
- # @obj.zoom_algorithm!
- # end
- # end
-
- def self.bench_performance_constant name, threshold = 0.99, &work
- bench name do
- assert_performance_constant threshold, &work
- end
- end
-
- ##
- # Create a benchmark that verifies that the performance is exponential.
- #
- # describe "my class" do
- # bench_performance_exponential "algorithm" do
- # @obj.algorithm
- # end
- # end
-
- def self.bench_performance_exponential name, threshold = 0.99, &work
- bench name do
- assert_performance_exponential threshold, &work
- end
- end
-end
diff --git a/ruby_1_9_3/lib/minitest/mock.rb b/ruby_1_9_3/lib/minitest/mock.rb
deleted file mode 100644
index c342c04995..0000000000
--- a/ruby_1_9_3/lib/minitest/mock.rb
+++ /dev/null
@@ -1,106 +0,0 @@
-######################################################################
-# This file is imported from the minitest project.
-# DO NOT make modifications in this repo. They _will_ be reverted!
-# File a patch instead and assign it to Ryan Davis.
-######################################################################
-
-class MockExpectationError < StandardError; end
-
-##
-# A simple and clean mock object framework.
-
-module MiniTest
-
- ##
- # All mock objects are an instance of Mock
-
- class Mock
- alias :__respond_to? :respond_to?
-
- skip_methods = %w(object_id respond_to_missing? inspect === to_s)
-
- instance_methods.each do |m|
- undef_method m unless skip_methods.include?(m.to_s) || m =~ /^__/
- end
-
- def initialize # :nodoc:
- @expected_calls = {}
- @actual_calls = Hash.new {|h,k| h[k] = [] }
- end
-
- ##
- # Expect that method +name+ is called, optionally with +args+, and returns
- # +retval+.
- #
- # @mock.expect(:meaning_of_life, 42)
- # @mock.meaning_of_life # => 42
- #
- # @mock.expect(:do_something_with, true, [some_obj, true])
- # @mock.do_something_with(some_obj, true) # => true
- #
- # +args+ is compared to the expected args using case equality (ie, the
- # '===' operator), allowing for less specific expectations.
- #
- # @mock.expect(:uses_any_string, true, [String])
- # @mock.uses_any_string("foo") # => true
- # @mock.verify # => true
- #
- # @mock.expect(:uses_one_string, true, ["foo"]
- # @mock.uses_one_string("bar") # => true
- # @mock.verify # => raises MockExpectationError
-
- def expect(name, retval, args=[])
- @expected_calls[name] = { :retval => retval, :args => args }
- self
- end
-
- ##
- # Verify that all methods were called as expected. Raises
- # +MockExpectationError+ if the mock object was not called as
- # expected.
-
- def verify
- @expected_calls.each_key do |name|
- expected = @expected_calls[name]
- msg1 = "expected #{name}, #{expected.inspect}"
- msg2 = "#{msg1}, got #{@actual_calls[name].inspect}"
-
- raise MockExpectationError, msg2 if
- @actual_calls.has_key? name and
- not @actual_calls[name].include?(expected)
-
- raise MockExpectationError, msg1 unless
- @actual_calls.has_key? name and @actual_calls[name].include?(expected)
- end
- true
- end
-
- def method_missing(sym, *args) # :nodoc:
- expected = @expected_calls[sym]
-
- unless expected then
- raise NoMethodError, "unmocked method %p, expected one of %p" %
- [sym, @expected_calls.keys.sort_by(&:to_s)]
- end
-
- expected_args, retval = expected[:args], expected[:retval]
-
- unless expected_args.size == args.size
- raise ArgumentError, "mocked method %p expects %d arguments, got %d" %
- [sym, expected[:args].size, args.size]
- end
-
- @actual_calls[sym] << {
- :retval => retval,
- :args => expected_args.zip(args).map { |mod, a| mod if mod === a }
- }
-
- retval
- end
-
- def respond_to?(sym) # :nodoc:
- return true if @expected_calls.has_key?(sym)
- return __respond_to?(sym)
- end
- end
-end
diff --git a/ruby_1_9_3/lib/minitest/pride.rb b/ruby_1_9_3/lib/minitest/pride.rb
deleted file mode 100644
index ac7745695c..0000000000
--- a/ruby_1_9_3/lib/minitest/pride.rb
+++ /dev/null
@@ -1,99 +0,0 @@
-######################################################################
-# This file is imported from the minitest project.
-# DO NOT make modifications in this repo. They _will_ be reverted!
-# File a patch instead and assign it to Ryan Davis.
-######################################################################
-
-require "minitest/unit"
-
-##
-# Show your testing pride!
-
-class PrideIO
- ESC = "\e["
- NND = "#{ESC}0m"
-
- attr_reader :io
-
- def initialize io
- @io = io
- # stolen from /System/Library/Perl/5.10.0/Term/ANSIColor.pm
- # also reference http://en.wikipedia.org/wiki/ANSI_escape_code
- @colors ||= (31..36).to_a
- @size = @colors.size
- @index = 0
- # io.sync = true
- end
-
- def print o
- case o
- when "." then
- io.print pride o
- when "E", "F" then
- io.print "#{ESC}41m#{ESC}37m#{o}#{NND}"
- else
- io.print o
- end
- end
-
- def puts(*o)
- o.map! { |s|
- s.sub(/Finished tests/) {
- @index = 0
- 'Fabulous tests'.split(//).map { |c|
- pride(c)
- }.join
- }
- }
-
- super
- end
-
- def pride string
- string = "*" if string == "."
- c = @colors[@index % @size]
- @index += 1
- "#{ESC}#{c}m#{string}#{NND}"
- end
-
- def method_missing msg, *args
- io.send(msg, *args)
- end
-end
-
-class PrideLOL < PrideIO # inspired by lolcat, but massively cleaned up
- PI_3 = Math::PI / 3
-
- def initialize io
- # walk red, green, and blue around a circle separated by equal thirds.
- #
- # To visualize, type this into wolfram-alpha:
- #
- # plot (3*sin(x)+3), (3*sin(x+2*pi/3)+3), (3*sin(x+4*pi/3)+3)
-
- # 6 has wide pretty gradients. 3 == lolcat, about half the width
- @colors = (0...(6 * 7)).map { |n|
- n *= 1.0 / 6
- r = (3 * Math.sin(n ) + 3).to_i
- g = (3 * Math.sin(n + 2 * PI_3) + 3).to_i
- b = (3 * Math.sin(n + 4 * PI_3) + 3).to_i
-
- # Then we take rgb and encode them in a single number using base 6.
- # For some mysterious reason, we add 16... to clear the bottom 4 bits?
- # Yes... they're ugly.
-
- 36 * r + 6 * g + b + 16
- }
-
- super
- end
-
- def pride string
- c = @colors[@index % @size]
- @index += 1
- "#{ESC}38;5;#{c}m#{string}#{NND}"
- end
-end
-
-klass = ENV['TERM'] =~ /^xterm(-256color)?$/ ? PrideLOL : PrideIO
-MiniTest::Unit.output = klass.new(MiniTest::Unit.output)
diff --git a/ruby_1_9_3/lib/minitest/spec.rb b/ruby_1_9_3/lib/minitest/spec.rb
deleted file mode 100644
index a70bbdd405..0000000000
--- a/ruby_1_9_3/lib/minitest/spec.rb
+++ /dev/null
@@ -1,519 +0,0 @@
-######################################################################
-# This file is imported from the minitest project.
-# DO NOT make modifications in this repo. They _will_ be reverted!
-# File a patch instead and assign it to Ryan Davis.
-######################################################################
-
-#!/usr/bin/ruby -w
-
-require 'minitest/unit'
-
-class Module # :nodoc:
- def infect_an_assertion meth, new_name, dont_flip = false # :nodoc:
- # warn "%-22p -> %p %p" % [meth, new_name, dont_flip]
- self.class_eval <<-EOM
- def #{new_name} *args, &block
- return MiniTest::Spec.current.#{meth}(*args, &self) if
- Proc === self
- return MiniTest::Spec.current.#{meth}(args.first, self) if
- args.size == 1 unless #{!!dont_flip}
- return MiniTest::Spec.current.#{meth}(self, *args)
- end
- EOM
- end
-
- ##
- # infect_with_assertions has been removed due to excessive clever.
- # Use infect_an_assertion directly instead.
-
- def infect_with_assertions(pos_prefix, neg_prefix,
- skip_re,
- dont_flip_re = /\c0/,
- map = {})
- abort "infect_with_assertions is dead. Use infect_an_assertion directly"
- end
-end
-
-module Kernel # :nodoc:
- ##
- # Describe a series of expectations for a given target +desc+.
- #
- # TODO: find good tutorial url.
- #
- # Defines a test class subclassing from either MiniTest::Spec or
- # from the surrounding describe's class. The surrounding class may
- # subclass MiniTest::Spec manually in order to easily share code:
- #
- # class MySpec < MiniTest::Spec
- # # ... shared code ...
- # end
- #
- # class TestStuff < MySpec
- # it "does stuff" do
- # # shared code available here
- # end
- # describe "inner stuff" do
- # it "still does stuff" do
- # # ...and here
- # end
- # end
- # end
-
- def describe desc, additional_desc = nil, &block # :doc:
- stack = MiniTest::Spec.describe_stack
- name = [stack.last, desc, additional_desc].compact.join("::")
- sclas = stack.last || if Class === self && self < MiniTest::Spec then
- self
- else
- MiniTest::Spec.spec_type desc
- end
-
- cls = sclas.create name, desc
-
- stack.push cls
- cls.class_eval(&block)
- stack.pop
- cls
- end
- private :describe
-end
-
-##
-# MiniTest::Spec -- The faster, better, less-magical spec framework!
-#
-# For a list of expectations, see MiniTest::Expectations.
-
-class MiniTest::Spec < MiniTest::Unit::TestCase
- ##
- # Contains pairs of matchers and Spec classes to be used to
- # calculate the superclass of a top-level describe. This allows for
- # automatically customizable spec types.
- #
- # See: register_spec_type and spec_type
-
- TYPES = [[//, MiniTest::Spec]]
-
- ##
- # Register a new type of spec that matches the spec's description.
- # This method can take either a Regexp and a spec class or a spec
- # class and a block that takes the description and returns true if
- # it matches.
- #
- # Eg:
- #
- # register_spec_type(/Controller$/, MiniTest::Spec::Rails)
- #
- # or:
- #
- # register_spec_type(MiniTest::Spec::RailsModel) do |desc|
- # desc.superclass == ActiveRecord::Base
- # end
-
- def self.register_spec_type(*args, &block)
- if block then
- matcher, klass = block, args.first
- else
- matcher, klass = *args
- end
- TYPES.unshift [matcher, klass]
- end
-
- ##
- # Figure out the spec class to use based on a spec's description. Eg:
- #
- # spec_type("BlahController") # => MiniTest::Spec::Rails
-
- def self.spec_type desc
- TYPES.find { |matcher, klass|
- if matcher.respond_to? :call then
- matcher.call desc
- else
- matcher === desc.to_s
- end
- }.last
- end
-
- @@describe_stack = []
- def self.describe_stack # :nodoc:
- @@describe_stack
- end
-
- def self.current # :nodoc:
- @@current_spec
- end
-
- ##
- # Returns the children of this spec.
-
- def self.children
- @children ||= []
- end
-
- def initialize name # :nodoc:
- super
- @@current_spec = self
- end
-
- def self.nuke_test_methods! # :nodoc:
- self.public_instance_methods.grep(/^test_/).each do |name|
- self.send :undef_method, name
- end
- end
-
- ##
- # Define a 'before' action. Inherits the way normal methods should.
- #
- # NOTE: +type+ is ignored and is only there to make porting easier.
- #
- # Equivalent to MiniTest::Unit::TestCase#setup.
-
- def self.before type = :each, &block
- raise "unsupported before type: #{type}" unless type == :each
-
- add_setup_hook {|tc| tc.instance_eval(&block) }
- end
-
- ##
- # Define an 'after' action. Inherits the way normal methods should.
- #
- # NOTE: +type+ is ignored and is only there to make porting easier.
- #
- # Equivalent to MiniTest::Unit::TestCase#teardown.
-
- def self.after type = :each, &block
- raise "unsupported after type: #{type}" unless type == :each
-
- add_teardown_hook {|tc| tc.instance_eval(&block) }
- end
-
- ##
- # Define an expectation with name +desc+. Name gets morphed to a
- # proper test method name. For some freakish reason, people who
- # write specs don't like class inheritence, so this goes way out of
- # its way to make sure that expectations aren't inherited.
- #
- # Hint: If you _do_ want inheritence, use minitest/unit. You can mix
- # and match between assertions and expectations as much as you want.
-
- def self.it desc, &block
- block ||= proc { skip "(no tests defined)" }
-
- @specs ||= 0
- @specs += 1
-
- name = "test_%04d_%s" % [ @specs, desc.gsub(/\W+/, '_').downcase ]
-
- define_method name, &block
-
- self.children.each do |mod|
- mod.send :undef_method, name if mod.public_method_defined? name
- end
- end
-
- def self.let name, &block
- define_method name do
- @_memoized ||= {}
- @_memoized.fetch(name) { |k| @_memoized[k] = instance_eval(&block) }
- end
- end
-
- def self.subject &block
- let :subject, &block
- end
-
- def self.create name, desc # :nodoc:
- cls = Class.new(self) do
- @name = name
- @desc = desc
-
- nuke_test_methods!
- end
-
- children << cls
-
- cls
- end
-
- def self.to_s # :nodoc:
- defined?(@name) ? @name : super
- end
-
- # :stopdoc:
- class << self
- attr_reader :name, :desc
- end
- # :startdoc:
-end
-
-module MiniTest::Expectations
- ##
- # See MiniTest::Assertions#assert_empty.
- #
- # collection.must_be_empty
- #
- # :method: must_be_empty
-
- infect_an_assertion :assert_empty, :must_be_empty
-
- ##
- # See MiniTest::Assertions#assert_equal
- #
- # a.must_equal b
- #
- # :method: must_equal
-
- infect_an_assertion :assert_equal, :must_equal
-
- ##
- # See MiniTest::Assertions#assert_in_delta
- #
- # n.must_be_close_to m [, delta]
- #
- # :method: must_be_within_delta
-
- infect_an_assertion :assert_in_delta, :must_be_close_to
-
- alias :must_be_within_delta :must_be_close_to
-
- ##
- # See MiniTest::Assertions#assert_in_epsilon
- #
- # n.must_be_within_epsilon m [, epsilon]
- #
- # :method: must_be_within_epsilon
-
- infect_an_assertion :assert_in_epsilon, :must_be_within_epsilon
-
- ##
- # See MiniTest::Assertions#assert_includes
- #
- # collection.must_include obj
- #
- # :method: must_include
-
- infect_an_assertion :assert_includes, :must_include, :reverse
-
- ##
- # See MiniTest::Assertions#assert_instance_of
- #
- # obj.must_be_instance_of klass
- #
- # :method: must_be_instance_of
-
- infect_an_assertion :assert_instance_of, :must_be_instance_of
-
- ##
- # See MiniTest::Assertions#assert_kind_of
- #
- # obj.must_be_kind_of mod
- #
- # :method: must_be_kind_of
-
- infect_an_assertion :assert_kind_of, :must_be_kind_of
-
- ##
- # See MiniTest::Assertions#assert_match
- #
- # a.must_match b
- #
- # :method: must_match
-
- infect_an_assertion :assert_match, :must_match
-
- ##
- # See MiniTest::Assertions#assert_nil
- #
- # obj.must_be_nil
- #
- # :method: must_be_nil
-
- infect_an_assertion :assert_nil, :must_be_nil
-
- ##
- # See MiniTest::Assertions#assert_operator
- #
- # n.must_be :<=, 42
- #
- # :method: must_be
-
- infect_an_assertion :assert_operator, :must_be
-
- ##
- # See MiniTest::Assertions#assert_output
- #
- # proc { ... }.must_output out_or_nil [, err]
- #
- # :method: must_output
-
- infect_an_assertion :assert_output, :must_output
-
- ##
- # See MiniTest::Assertions#assert_raises
- #
- # proc { ... }.must_raise exception
- #
- # :method: must_raise
-
- infect_an_assertion :assert_raises, :must_raise
-
- ##
- # See MiniTest::Assertions#assert_respond_to
- #
- # obj.must_respond_to msg
- #
- # :method: must_respond_to
-
- infect_an_assertion :assert_respond_to, :must_respond_to, :reverse
-
- ##
- # See MiniTest::Assertions#assert_same
- #
- # a.must_be_same_as b
- #
- # :method: must_be_same_as
-
- infect_an_assertion :assert_same, :must_be_same_as
-
- ##
- # See MiniTest::Assertions#assert_send
- # TODO: remove me
- #
- # a.must_send
- #
- # :method: must_send
-
- infect_an_assertion :assert_send, :must_send
-
- ##
- # See MiniTest::Assertions#assert_silent
- #
- # proc { ... }.must_be_silent
- #
- # :method: must_be_silent
-
- infect_an_assertion :assert_silent, :must_be_silent
-
- ##
- # See MiniTest::Assertions#assert_throws
- #
- # proc { ... }.must_throw sym
- #
- # :method: must_throw
-
- infect_an_assertion :assert_throws, :must_throw
-
- ##
- # See MiniTest::Assertions#refute_empty
- #
- # collection.wont_be_empty
- #
- # :method: wont_be_empty
-
- infect_an_assertion :refute_empty, :wont_be_empty
-
- ##
- # See MiniTest::Assertions#refute_equal
- #
- # a.wont_equal b
- #
- # :method: wont_equal
-
- infect_an_assertion :refute_equal, :wont_equal
-
- ##
- # See MiniTest::Assertions#refute_in_delta
- #
- # n.wont_be_close_to m [, delta]
- #
- # :method: wont_be_within_delta
-
- infect_an_assertion :refute_in_delta, :wont_be_within_delta
-
- alias :wont_be_close_to :wont_be_within_delta
- # FIX: reverse aliases
-
- ##
- # See MiniTest::Assertions#refute_in_epsilon
- #
- # n.wont_be_within_epsilon m [, epsilon]
- #
- # :method: wont_be_within_epsilon
-
- infect_an_assertion :refute_in_epsilon, :wont_be_within_epsilon
-
- ##
- # See MiniTest::Assertions#refute_includes
- #
- # collection.wont_include obj
- #
- # :method: wont_include
-
- infect_an_assertion :refute_includes, :wont_include, :reverse
-
- ##
- # See MiniTest::Assertions#refute_instance_of
- #
- # obj.wont_be_instance_of klass
- #
- # :method: wont_be_instance_of
-
- infect_an_assertion :refute_instance_of, :wont_be_instance_of
-
- ##
- # See MiniTest::Assertions#refute_kind_of
- #
- # obj.wont_be_kind_of mod
- #
- # :method: wont_be_kind_of
-
- infect_an_assertion :refute_kind_of, :wont_be_kind_of
-
- ##
- # See MiniTest::Assertions#refute_match
- #
- # a.wont_match b
- #
- # :method: wont_match
-
- infect_an_assertion :refute_match, :wont_match
-
- ##
- # See MiniTest::Assertions#refute_nil
- #
- # obj.wont_be_nil
- #
- # :method: wont_be_nil
-
- infect_an_assertion :refute_nil, :wont_be_nil
-
- ##
- # See MiniTest::Assertions#refute_operator
- #
- # n.wont_be :<=, 42
- #
- # :method: wont_be
-
- infect_an_assertion :refute_operator, :wont_be
-
- ##
- # See MiniTest::Assertions#refute_respond_to
- #
- # obj.wont_respond_to msg
- #
- # :method: wont_respond_to
-
- infect_an_assertion :refute_respond_to, :wont_respond_to, :reverse
-
- ##
- # See MiniTest::Assertions#refute_same
- #
- # a.wont_be_same_as b
- #
- # :method: wont_be_same_as
-
- infect_an_assertion :refute_same, :wont_be_same_as
-end
-
-class Object
- include MiniTest::Expectations
-end
diff --git a/ruby_1_9_3/lib/minitest/unit.rb b/ruby_1_9_3/lib/minitest/unit.rb
deleted file mode 100644
index 922ef70183..0000000000
--- a/ruby_1_9_3/lib/minitest/unit.rb
+++ /dev/null
@@ -1,1169 +0,0 @@
-######################################################################
-# This file is imported from the minitest project.
-# DO NOT make modifications in this repo. They _will_ be reverted!
-# File a patch instead and assign it to Ryan Davis.
-######################################################################
-
-require 'optparse'
-require 'rbconfig'
-
-##
-# Minimal (mostly drop-in) replacement for test-unit.
-#
-# :include: README.txt
-
-module MiniTest
-
- ##
- # Assertion base class
-
- class Assertion < Exception; end
-
- ##
- # Assertion raised when skipping a test
-
- class Skip < Assertion; end
-
- file = if RUBY_VERSION =~ /^1\.9/ then # bt's expanded, but __FILE__ isn't :(
- File.expand_path __FILE__
- elsif __FILE__ =~ /^[^\.]/ then # assume both relative
- require 'pathname'
- pwd = Pathname.new Dir.pwd
- pn = Pathname.new File.expand_path(__FILE__)
- relpath = pn.relative_path_from(pwd) rescue pn
- pn = File.join ".", relpath unless pn.relative?
- pn.to_s
- else # assume both are expanded
- __FILE__
- end
-
- # './lib' in project dir, or '/usr/local/blahblah' if installed
- MINI_DIR = File.dirname(File.dirname(file)) # :nodoc:
-
- def self.filter_backtrace bt # :nodoc:
- return ["No backtrace"] unless bt
-
- new_bt = []
-
- unless $DEBUG then
- bt.each do |line|
- break if line.rindex MINI_DIR, 0
- new_bt << line
- end
-
- new_bt = bt.reject { |line| line.rindex MINI_DIR, 0 } if new_bt.empty?
- new_bt = bt.dup if new_bt.empty?
- else
- new_bt = bt.dup
- end
-
- new_bt
- end
-
- ##
- # MiniTest Assertions. All assertion methods accept a +msg+ which is
- # printed if the assertion fails.
-
- module Assertions
-
- WINDOZE = RbConfig::CONFIG['host_os'] =~ /mswin|mingw/
-
- ##
- # Returns the diff command to use in #diff. Tries to intelligently
- # figure out what diff to use.
-
- def self.diff
- @diff = if WINDOZE
- "diff.exe -u"
- else
- if system("gdiff", __FILE__, __FILE__)
- "gdiff -u" # solaris and kin suck
- elsif system("diff", __FILE__, __FILE__)
- "diff -u"
- else
- nil
- end
- end unless defined? @diff
-
- @diff
- end
-
- ##
- # Set the diff command to use in #diff.
-
- def self.diff= o
- @diff = o
- end
-
- ##
- # Returns a diff between +exp+ and +act+. If there is no known
- # diff command or if it doesn't make sense to diff the output
- # (single line, short output), then it simply returns a basic
- # comparison between the two.
-
- def diff exp, act
- require "tempfile"
-
- expect = mu_pp_for_diff exp
- butwas = mu_pp_for_diff act
- result = nil
-
- need_to_diff =
- MiniTest::Assertions.diff &&
- (expect.include?("\n") ||
- butwas.include?("\n") ||
- expect.size > 30 ||
- butwas.size > 30 ||
- expect == butwas)
-
- return "Expected: #{mu_pp exp}\n Actual: #{mu_pp act}" unless
- need_to_diff
-
- Tempfile.open("expect") do |a|
- a.puts expect
- a.flush
-
- Tempfile.open("butwas") do |b|
- b.puts butwas
- b.flush
-
- result = `#{MiniTest::Assertions.diff} #{a.path} #{b.path}`
- result.sub!(/^\-\-\- .+/, "--- expected")
- result.sub!(/^\+\+\+ .+/, "+++ actual")
-
- if result.empty? then
- klass = exp.class
- result = [
- "No visible difference.",
- "You should look at your implementation of #{klass}#==.",
- expect
- ].join "\n"
- end
- end
- end
-
- result
- end
-
- ##
- # This returns a human-readable version of +obj+. By default
- # #inspect is called. You can override this to use #pretty_print
- # if you want.
-
- def mu_pp obj
- s = obj.inspect
- s = s.encode Encoding.default_external if defined? Encoding
- s
- end
-
- ##
- # This returns a diff-able human-readable version of +obj+. This
- # differs from the regular mu_pp because it expands escaped
- # newlines and makes hex-values generic (like object_ids). This
- # uses mu_pp to do the first pass and then cleans it up.
-
- def mu_pp_for_diff obj # TODO: possibly rename
- mu_pp(obj).gsub(/\\n/, "\n").gsub(/0x[a-f0-9]+/m, '0xXXXXXX')
- end
-
- def _assertions= n # :nodoc:
- @_assertions = n
- end
-
- def _assertions # :nodoc:
- @_assertions ||= 0
- end
-
- ##
- # Fails unless +test+ is a true value.
-
- def assert test, msg = nil
- msg ||= "Failed assertion, no message given."
- self._assertions += 1
- unless test then
- msg = msg.call if Proc === msg
- raise MiniTest::Assertion, msg
- end
- true
- end
-
- ##
- # Fails unless the block returns a true value.
-
- def assert_block msg = nil
- msg = message(msg) { "Expected block to return true value" }
- assert yield, msg
- end
-
- ##
- # Fails unless +obj+ is empty.
-
- def assert_empty obj, msg = nil
- msg = message(msg) { "Expected #{mu_pp(obj)} to be empty" }
- assert_respond_to obj, :empty?
- assert obj.empty?, msg
- end
-
- ##
- # Fails unless <tt>exp == act</tt> printing the difference between
- # the two, if possible.
- #
- # If there is no visible difference but the assertion fails, you
- # should suspect that your #== is buggy, or your inspect output is
- # missing crucial details.
- #
- # For floats use assert_in_delta.
- #
- # See also: MiniTest::Assertions.diff
-
- def assert_equal exp, act, msg = nil
- msg = message(msg, "") { diff exp, act }
- assert(exp == act, msg)
- end
-
- ##
- # For comparing Floats. Fails unless +exp+ and +act+ are within +delta+
- # of each other.
- #
- # assert_in_delta Math::PI, (22.0 / 7.0), 0.01
-
- def assert_in_delta exp, act, delta = 0.001, msg = nil
- n = (exp - act).abs
- msg = message(msg) { "Expected #{exp} - #{act} (#{n}) to be < #{delta}" }
- assert delta >= n, msg
- end
-
- ##
- # For comparing Floats. Fails unless +exp+ and +act+ have a relative
- # error less than +epsilon+.
-
- def assert_in_epsilon a, b, epsilon = 0.001, msg = nil
- assert_in_delta a, b, [a, b].min * epsilon, msg
- end
-
- ##
- # Fails unless +collection+ includes +obj+.
-
- def assert_includes collection, obj, msg = nil
- msg = message(msg) {
- "Expected #{mu_pp(collection)} to include #{mu_pp(obj)}"
- }
- assert_respond_to collection, :include?
- assert collection.include?(obj), msg
- end
-
- ##
- # Fails unless +obj+ is an instace of +cls+.
-
- def assert_instance_of cls, obj, msg = nil
- msg = message(msg) {
- "Expected #{mu_pp(obj)} to be an instance of #{cls}, not #{obj.class}"
- }
-
- assert obj.instance_of?(cls), msg
- end
-
- ##
- # Fails unless +obj+ is a kind of +cls+.
-
- def assert_kind_of cls, obj, msg = nil # TODO: merge with instance_of
- msg = message(msg) {
- "Expected #{mu_pp(obj)} to be a kind of #{cls}, not #{obj.class}" }
-
- assert obj.kind_of?(cls), msg
- end
-
- ##
- # Fails unless +exp+ is <tt>=~</tt> +act+.
-
- def assert_match exp, act, msg = nil
- msg = message(msg) { "Expected #{mu_pp(exp)} to match #{mu_pp(act)}" }
- assert_respond_to act, :"=~"
- exp = Regexp.new Regexp.escape exp if String === exp and String === act
- assert exp =~ act, msg
- end
-
- ##
- # Fails unless +obj+ is nil
-
- def assert_nil obj, msg = nil
- msg = message(msg) { "Expected #{mu_pp(obj)} to be nil" }
- assert obj.nil?, msg
- end
-
- ##
- # For testing equality operators and so-forth.
- #
- # assert_operator 5, :<=, 4
-
- def assert_operator o1, op, o2, msg = nil
- msg = message(msg) { "Expected #{mu_pp(o1)} to be #{op} #{mu_pp(o2)}" }
- assert o1.__send__(op, o2), msg
- end
-
- ##
- # Fails if stdout or stderr do not output the expected results.
- # Pass in nil if you don't care about that streams output. Pass in
- # "" if you require it to be silent.
- #
- # See also: #assert_silent
-
- def assert_output stdout = nil, stderr = nil
- out, err = capture_io do
- yield
- end
-
- x = assert_equal stdout, out, "In stdout" if stdout
- y = assert_equal stderr, err, "In stderr" if stderr
-
- (!stdout || x) && (!stderr || y)
- end
-
- ##
- # Fails unless the block raises one of +exp+
-
- def assert_raises *exp
- msg = "#{exp.pop}\n" if String === exp.last
-
- should_raise = false
- begin
- yield
- should_raise = true
- rescue MiniTest::Skip => e
- details = "#{msg}#{mu_pp(exp)} exception expected, not"
-
- if exp.include? MiniTest::Skip then
- return e
- else
- raise e
- end
- rescue Exception => e
- details = "#{msg}#{mu_pp(exp)} exception expected, not"
- assert(exp.any? { |ex|
- ex.instance_of?(Module) ? e.kind_of?(ex) : ex == e.class
- }, exception_details(e, details))
-
- return e
- end
-
- exp = exp.first if exp.size == 1
- flunk "#{msg}#{mu_pp(exp)} expected but nothing was raised." if
- should_raise
- end
-
- ##
- # Fails unless +obj+ responds to +meth+.
-
- def assert_respond_to obj, meth, msg = nil
- msg = message(msg) {
- "Expected #{mu_pp(obj)} (#{obj.class}) to respond to ##{meth}"
- }
- assert obj.respond_to?(meth), msg
- end
-
- ##
- # Fails unless +exp+ and +act+ are #equal?
-
- def assert_same exp, act, msg = nil
- msg = message(msg) {
- data = [mu_pp(act), act.object_id, mu_pp(exp), exp.object_id]
- "Expected %s (oid=%d) to be the same as %s (oid=%d)" % data
- }
- assert exp.equal?(act), msg
- end
-
- ##
- # +send_ary+ is a receiver, message and arguments.
- #
- # Fails unless the call returns a true value
- # TODO: I should prolly remove this from specs
-
- def assert_send send_ary, m = nil
- recv, msg, *args = send_ary
- m = message(m) {
- "Expected #{mu_pp(recv)}.#{msg}(*#{mu_pp(args)}) to return true" }
- assert recv.__send__(msg, *args), m
- end
-
- ##
- # Fails if the block outputs anything to stderr or stdout.
- #
- # See also: #assert_output
-
- def assert_silent
- assert_output "", "" do
- yield
- end
- end
-
- ##
- # Fails unless the block throws +sym+
-
- def assert_throws sym, msg = nil
- default = "Expected #{mu_pp(sym)} to have been thrown"
- caught = true
- catch(sym) do
- begin
- yield
- rescue ArgumentError => e # 1.9 exception
- default += ", not #{e.message.split(/ /).last}"
- rescue NameError => e # 1.8 exception
- default += ", not #{e.name.inspect}"
- end
- caught = false
- end
-
- assert caught, message(msg) { default }
- end
-
- ##
- # Captures $stdout and $stderr into strings:
- #
- # out, err = capture_io do
- # warn "You did a bad thing"
- # end
- #
- # assert_match %r%bad%, err
-
- def capture_io
- require 'stringio'
-
- orig_stdout, orig_stderr = $stdout, $stderr
- captured_stdout, captured_stderr = StringIO.new, StringIO.new
- $stdout, $stderr = captured_stdout, captured_stderr
-
- yield
-
- return captured_stdout.string, captured_stderr.string
- ensure
- $stdout = orig_stdout
- $stderr = orig_stderr
- end
-
- ##
- # Returns details for exception +e+
-
- def exception_details e, msg
- [
- "#{msg}",
- "Class: <#{e.class}>",
- "Message: <#{e.message.inspect}>",
- "---Backtrace---",
- "#{MiniTest::filter_backtrace(e.backtrace).join("\n")}",
- "---------------",
- ].join "\n"
- end
-
- ##
- # Fails with +msg+
-
- def flunk msg = nil
- msg ||= "Epic Fail!"
- assert false, msg
- end
-
- ##
- # Returns a proc that will output +msg+ along with the default message.
-
- def message msg = nil, ending = ".", &default
- proc {
- custom_message = "#{msg}.\n" unless msg.nil? or msg.to_s.empty?
- "#{custom_message}#{default.call}#{ending}"
- }
- end
-
- ##
- # used for counting assertions
-
- def pass msg = nil
- assert true
- end
-
- ##
- # Fails if +test+ is a true value
-
- def refute test, msg = nil
- msg ||= "Failed refutation, no message given"
- not assert(! test, msg)
- end
-
- ##
- # Fails if +obj+ is empty.
-
- def refute_empty obj, msg = nil
- msg = message(msg) { "Expected #{mu_pp(obj)} to not be empty" }
- assert_respond_to obj, :empty?
- refute obj.empty?, msg
- end
-
- ##
- # Fails if <tt>exp == act</tt>.
- #
- # For floats use refute_in_delta.
-
- def refute_equal exp, act, msg = nil
- msg = message(msg) {
- "Expected #{mu_pp(act)} to not be equal to #{mu_pp(exp)}"
- }
- refute exp == act, msg
- end
-
- ##
- # For comparing Floats. Fails if +exp+ is within +delta+ of +act+
- #
- # refute_in_delta Math::PI, (22.0 / 7.0)
-
- def refute_in_delta exp, act, delta = 0.001, msg = nil
- n = (exp - act).abs
- msg = message(msg) {
- "Expected #{exp} - #{act} (#{n}) to not be < #{delta}"
- }
- refute delta > n, msg
- end
-
- ##
- # For comparing Floats. Fails if +exp+ and +act+ have a relative error
- # less than +epsilon+.
-
- def refute_in_epsilon a, b, epsilon = 0.001, msg = nil
- refute_in_delta a, b, a * epsilon, msg
- end
-
- ##
- # Fails if +collection+ includes +obj+
-
- def refute_includes collection, obj, msg = nil
- msg = message(msg) {
- "Expected #{mu_pp(collection)} to not include #{mu_pp(obj)}"
- }
- assert_respond_to collection, :include?
- refute collection.include?(obj), msg
- end
-
- ##
- # Fails if +obj+ is an instance of +cls+
-
- def refute_instance_of cls, obj, msg = nil
- msg = message(msg) {
- "Expected #{mu_pp(obj)} to not be an instance of #{cls}"
- }
- refute obj.instance_of?(cls), msg
- end
-
- ##
- # Fails if +obj+ is a kind of +cls+
-
- def refute_kind_of cls, obj, msg = nil # TODO: merge with instance_of
- msg = message(msg) { "Expected #{mu_pp(obj)} to not be a kind of #{cls}" }
- refute obj.kind_of?(cls), msg
- end
-
- ##
- # Fails if +exp+ <tt>=~</tt> +act+
-
- def refute_match exp, act, msg = nil
- msg = message(msg) { "Expected #{mu_pp(exp)} to not match #{mu_pp(act)}" }
- assert_respond_to act, :"=~"
- exp = (/#{Regexp.escape exp}/) if String === exp and String === act
- refute exp =~ act, msg
- end
-
- ##
- # Fails if +obj+ is nil.
-
- def refute_nil obj, msg = nil
- msg = message(msg) { "Expected #{mu_pp(obj)} to not be nil" }
- refute obj.nil?, msg
- end
-
- ##
- # Fails if +o1+ is not +op+ +o2+. Eg:
- #
- # refute_operator 1, :>, 2 #=> pass
- # refute_operator 1, :<, 2 #=> fail
-
- def refute_operator o1, op, o2, msg = nil
- msg = message(msg) {
- "Expected #{mu_pp(o1)} to not be #{op} #{mu_pp(o2)}"
- }
- refute o1.__send__(op, o2), msg
- end
-
- ##
- # Fails if +obj+ responds to the message +meth+.
-
- def refute_respond_to obj, meth, msg = nil
- msg = message(msg) { "Expected #{mu_pp(obj)} to not respond to #{meth}" }
-
- refute obj.respond_to?(meth), msg
- end
-
- ##
- # Fails if +exp+ is the same (by object identity) as +act+.
-
- def refute_same exp, act, msg = nil
- msg = message(msg) {
- data = [mu_pp(act), act.object_id, mu_pp(exp), exp.object_id]
- "Expected %s (oid=%d) to not be the same as %s (oid=%d)" % data
- }
- refute exp.equal?(act), msg
- end
-
- ##
- # Skips the current test. Gets listed at the end of the run but
- # doesn't cause a failure exit code.
-
- def skip msg = nil, bt = caller
- msg ||= "Skipped, no message given"
- raise MiniTest::Skip, msg, bt
- end
- end
-
- class Unit
- VERSION = "2.5.1" # :nodoc:
-
- attr_accessor :report, :failures, :errors, :skips # :nodoc:
- attr_accessor :test_count, :assertion_count # :nodoc:
- attr_accessor :start_time # :nodoc:
- attr_accessor :help # :nodoc:
- attr_accessor :verbose # :nodoc:
- attr_writer :options # :nodoc:
-
- def options
- @options ||= {}
- end
-
- @@installed_at_exit ||= false
- @@out = $stdout
-
- ##
- # A simple hook allowing you to run a block of code after the
- # tests are done. Eg:
- #
- # MiniTest::Unit.after_tests { p $debugging_info }
-
- def self.after_tests
- at_exit { at_exit { yield } }
- end
-
- ##
- # Registers MiniTest::Unit to run tests at process exit
-
- def self.autorun
- at_exit {
- next if $! # don't run if there was an exception
-
- # the order here is important. The at_exit handler must be
- # installed before anyone else gets a chance to install their
- # own, that way we can be assured that our exit will be last
- # to run (at_exit stacks).
- exit_code = nil
-
- at_exit { exit false if exit_code && exit_code != 0 }
-
- exit_code = MiniTest::Unit.new.run ARGV
- } unless @@installed_at_exit
- @@installed_at_exit = true
- end
-
- ##
- # Returns the stream to use for output.
-
- def self.output
- @@out
- end
-
- ##
- # Returns the stream to use for output.
- #
- # DEPRECATED: use ::output instead.
-
- def self.out
- warn "::out deprecated, use ::output instead." if $VERBOSE
- output
- end
-
- ##
- # Sets MiniTest::Unit to write output to +stream+. $stdout is the default
- # output
-
- def self.output= stream
- @@out = stream
- end
-
- ##
- # Tells MiniTest::Unit to delegate to +runner+, an instance of a
- # MiniTest::Unit subclass, when MiniTest::Unit#run is called.
-
- def self.runner= runner
- @@runner = runner
- end
-
- ##
- # Returns the MiniTest::Unit subclass instance that will be used
- # to run the tests. A MiniTest::Unit instance is the default
- # runner.
-
- def self.runner
- @@runner ||= self.new
- end
-
- ##
- # Return all plugins' run methods (methods that start with "run_").
-
- def self.plugins
- @@plugins ||= (["run_tests"] +
- public_instance_methods(false).
- grep(/^run_/).map { |s| s.to_s }).uniq
- end
-
- def output
- self.class.output
- end
-
- def puts *a # :nodoc:
- output.puts(*a)
- end
-
- def print *a # :nodoc:
- output.print(*a)
- end
-
- def _run_anything type
- suites = TestCase.send "#{type}_suites"
- return if suites.empty?
-
- start = Time.now
-
- puts
- puts "# Running #{type}s:"
- puts
-
- @test_count, @assertion_count = 0, 0
- sync = output.respond_to? :"sync=" # stupid emacs
- old_sync, output.sync = output.sync, true if sync
-
- results = _run_suites suites, type
-
- @test_count = results.inject(0) { |sum, (tc, _)| sum + tc }
- @assertion_count = results.inject(0) { |sum, (_, ac)| sum + ac }
-
- output.sync = old_sync if sync
-
- t = Time.now - start
-
- puts
- puts
- puts "Finished #{type}s in %.6fs, %.4f tests/s, %.4f assertions/s." %
- [t, test_count / t, assertion_count / t]
-
- report.each_with_index do |msg, i|
- puts "\n%3d) %s" % [i + 1, msg]
- end
-
- puts
-
- status
- end
-
- def _run_suites suites, type
- suites.map { |suite| _run_suite suite, type }
- end
-
- def _run_suite suite, type
- header = "#{type}_suite_header"
- puts send(header, suite) if respond_to? header
-
- filter = options[:filter] || '/./'
- filter = Regexp.new $1 if filter =~ /\/(.*)\//
-
- assertions = suite.send("#{type}_methods").grep(filter).map { |method|
- inst = suite.new method
- inst._assertions = 0
-
- print "#{suite}##{method} = " if @verbose
-
- @start_time = Time.now
- result = inst.run self
- time = Time.now - @start_time
-
- print "%.2f s = " % time if @verbose
- print result
- puts if @verbose
-
- inst._assertions
- }
-
- return assertions.size, assertions.inject(0) { |sum, n| sum + n }
- end
-
- def location e # :nodoc:
- last_before_assertion = ""
- e.backtrace.reverse_each do |s|
- break if s =~ /in .(assert|refute|flunk|pass|fail|raise|must|wont)/
- last_before_assertion = s
- end
- last_before_assertion.sub(/:in .*$/, '')
- end
-
- ##
- # Writes status for failed test +meth+ in +klass+ which finished with
- # exception +e+
-
- def puke klass, meth, e
- e = case e
- when MiniTest::Skip then
- @skips += 1
- return "S" unless @verbose
- "Skipped:\n#{meth}(#{klass}) [#{location e}]:\n#{e.message}\n"
- when MiniTest::Assertion then
- @failures += 1
- "Failure:\n#{meth}(#{klass}) [#{location e}]:\n#{e.message}\n"
- else
- @errors += 1
- bt = MiniTest::filter_backtrace(e.backtrace).join "\n "
- "Error:\n#{meth}(#{klass}):\n#{e.class}: #{e.message}\n #{bt}\n"
- end
- @report << e
- e[0, 1]
- end
-
- def initialize # :nodoc:
- @report = []
- @errors = @failures = @skips = 0
- @verbose = false
- end
-
- def process_args args = []
- options = {}
- orig_args = args.dup
-
- OptionParser.new do |opts|
- opts.banner = 'minitest options:'
- opts.version = MiniTest::Unit::VERSION
-
- opts.on '-h', '--help', 'Display this help.' do
- puts opts
- exit
- end
-
- opts.on '-s', '--seed SEED', Integer, "Sets random seed" do |m|
- options[:seed] = m.to_i
- end
-
- opts.on '-v', '--verbose', "Verbose. Show progress processing files." do
- options[:verbose] = true
- end
-
- opts.on '-n', '--name PATTERN', "Filter test names on pattern." do |a|
- options[:filter] = a
- end
-
- opts.parse! args
- orig_args -= args
- end
-
- unless options[:seed] then
- srand
- options[:seed] = srand % 0xFFFF
- orig_args << "--seed" << options[:seed].to_s
- end
-
- srand options[:seed]
-
- self.verbose = options[:verbose]
- @help = orig_args.map { |s| s =~ /[\s|&<>$()]/ ? s.inspect : s }.join " "
-
- options
- end
-
- ##
- # Begins the full test run. Delegates to +runner+'s #_run method.
-
- def run args = []
- self.class.runner._run(args)
- end
-
- ##
- # Top level driver, controls all output and filtering.
-
- def _run args = []
- self.options = process_args args
-
- puts "Run options: #{help}"
-
- self.class.plugins.each do |plugin|
- send plugin
- break unless report.empty?
- end
-
- return failures + errors if @test_count > 0 # or return nil...
- rescue Interrupt
- abort 'Interrupted'
- end
-
- ##
- # Runs test suites matching +filter+.
-
- def run_tests
- _run_anything :test
- end
-
- ##
- # Writes status to +io+
-
- def status io = self.output
- format = "%d tests, %d assertions, %d failures, %d errors, %d skips"
- io.puts format % [test_count, assertion_count, failures, errors, skips]
- end
-
- ##
- # Subclass TestCase to create your own tests. Typically you'll want a
- # TestCase subclass per implementation class.
- #
- # See MiniTest::Assertions
-
- class TestCase
- attr_reader :__name__ # :nodoc:
-
- PASSTHROUGH_EXCEPTIONS = [NoMemoryError, SignalException,
- Interrupt, SystemExit] # :nodoc:
-
- SUPPORTS_INFO_SIGNAL = Signal.list['INFO'] # :nodoc:
-
- ##
- # Runs the tests reporting the status to +runner+
-
- def run runner
- trap "INFO" do
- time = runner.start_time ? Time.now - runner.start_time : 0
- warn "%s#%s %.2fs" % [self.class, self.__name__, time]
- runner.status $stderr
- end if SUPPORTS_INFO_SIGNAL
-
- result = ""
- begin
- @passed = nil
- self.setup
- self.run_setup_hooks
- self.__send__ self.__name__
- result = "." unless io?
- @passed = true
- rescue *PASSTHROUGH_EXCEPTIONS
- raise
- rescue Exception => e
- @passed = false
- result = runner.puke self.class, self.__name__, e
- ensure
- begin
- self.run_teardown_hooks
- self.teardown
- rescue *PASSTHROUGH_EXCEPTIONS
- raise
- rescue Exception => e
- result = runner.puke self.class, self.__name__, e
- end
- trap 'INFO', 'DEFAULT' if SUPPORTS_INFO_SIGNAL
- end
- result
- end
-
- def initialize name # :nodoc:
- @__name__ = name
- @__io__ = nil
- @passed = nil
- end
-
- def io
- @__io__ = true
- MiniTest::Unit.output
- end
-
- def io?
- @__io__
- end
-
- def self.reset # :nodoc:
- @@test_suites = {}
- end
-
- reset
-
- ##
- # Call this at the top of your tests when you absolutely
- # positively need to have ordered tests. In doing so, you're
- # admitting that you suck and your tests are weak.
-
- def self.i_suck_and_my_tests_are_order_dependent!
- class << self
- define_method :test_order do :alpha end
- end
- end
-
- def self.inherited klass # :nodoc:
- @@test_suites[klass] = true
- klass.reset_setup_teardown_hooks
- super
- end
-
- def self.test_order # :nodoc:
- :random
- end
-
- def self.test_suites # :nodoc:
- @@test_suites.keys.sort_by { |ts| ts.name.to_s }
- end
-
- def self.test_methods # :nodoc:
- methods = public_instance_methods(true).grep(/^test/).map { |m| m.to_s }
-
- case self.test_order
- when :random then
- max = methods.size
- methods.sort.sort_by { rand max }
- when :alpha, :sorted then
- methods.sort
- else
- raise "Unknown test_order: #{self.test_order.inspect}"
- end
- end
-
- ##
- # Returns true if the test passed.
-
- def passed?
- @passed
- end
-
- ##
- # Runs before every test. Use this to refactor test initialization.
-
- def setup; end
-
- ##
- # Runs after every test. Use this to refactor test cleanup.
-
- def teardown; end
-
- def self.reset_setup_teardown_hooks # :nodoc:
- @setup_hooks = []
- @teardown_hooks = []
- end
-
- reset_setup_teardown_hooks
-
- ##
- # Adds a block of code that will be executed before every TestCase is
- # run. Equivalent to +setup+, but usable multiple times and without
- # re-opening any classes.
- #
- # All of the setup hooks will run in order after the +setup+ method, if
- # one is defined.
- #
- # The argument can be any object that responds to #call or a block.
- # That means that this call,
- #
- # MiniTest::TestCase.add_setup_hook { puts "foo" }
- #
- # ... is equivalent to:
- #
- # module MyTestSetup
- # def call
- # puts "foo"
- # end
- # end
- #
- # MiniTest::TestCase.add_setup_hook MyTestSetup
- #
- # The blocks passed to +add_setup_hook+ take an optional parameter that
- # will be the TestCase instance that is executing the block.
-
- def self.add_setup_hook arg=nil, &block
- hook = arg || block
- @setup_hooks << hook
- end
-
- def self.setup_hooks # :nodoc:
- if superclass.respond_to? :setup_hooks then
- superclass.setup_hooks
- else
- []
- end + @setup_hooks
- end
-
- def run_setup_hooks # :nodoc:
- self.class.setup_hooks.each do |hook|
- if hook.respond_to?(:arity) && hook.arity == 1
- hook.call(self)
- else
- hook.call
- end
- end
- end
-
- ##
- # Adds a block of code that will be executed after every TestCase is
- # run. Equivalent to +teardown+, but usable multiple times and without
- # re-opening any classes.
- #
- # All of the teardown hooks will run in reverse order after the
- # +teardown+ method, if one is defined.
- #
- # The argument can be any object that responds to #call or a block.
- # That means that this call,
- #
- # MiniTest::TestCase.add_teardown_hook { puts "foo" }
- #
- # ... is equivalent to:
- #
- # module MyTestTeardown
- # def call
- # puts "foo"
- # end
- # end
- #
- # MiniTest::TestCase.add_teardown_hook MyTestTeardown
- #
- # The blocks passed to +add_teardown_hook+ take an optional parameter
- # that will be the TestCase instance that is executing the block.
-
- def self.add_teardown_hook arg=nil, &block
- hook = arg || block
- @teardown_hooks << hook
- end
-
- def self.teardown_hooks # :nodoc:
- if superclass.respond_to? :teardown_hooks then
- superclass.teardown_hooks
- else
- []
- end + @teardown_hooks
- end
-
- def run_teardown_hooks # :nodoc:
- self.class.teardown_hooks.reverse.each do |hook|
- if hook.respond_to?(:arity) && hook.arity == 1
- hook.call(self)
- else
- hook.call
- end
- end
- end
-
- include MiniTest::Assertions
- end # class TestCase
- end # class Unit
-end # module MiniTest
-
-if $DEBUG then
- module Test # :nodoc:
- module Unit # :nodoc:
- class TestCase # :nodoc:
- def self.inherited x # :nodoc:
- # this helps me ferret out porting issues
- raise "Using minitest and test/unit in the same process: #{x}"
- end
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/mkmf.rb b/ruby_1_9_3/lib/mkmf.rb
deleted file mode 100644
index 8f4e69e429..0000000000
--- a/ruby_1_9_3/lib/mkmf.rb
+++ /dev/null
@@ -1,2334 +0,0 @@
-# -*- indent-tabs-mode: t -*-
-# module to create Makefile for extension modules
-# invoke like: ruby -r mkmf extconf.rb
-
-require 'rbconfig'
-require 'fileutils'
-require 'shellwords'
-
-CONFIG = RbConfig::MAKEFILE_CONFIG
-ORIG_LIBPATH = ENV['LIB']
-
-C_EXT = %w[c m]
-CXX_EXT = %w[cc mm cxx cpp]
-if File::FNM_SYSCASE.zero?
- CXX_EXT.concat(%w[C])
-end
-SRC_EXT = C_EXT + CXX_EXT
-$static = nil
-$config_h = '$(arch_hdrdir)/ruby/config.h'
-$default_static = $static
-
-unless defined? $configure_args
- $configure_args = {}
- args = CONFIG["configure_args"]
- if ENV["CONFIGURE_ARGS"]
- args << " " << ENV["CONFIGURE_ARGS"]
- end
- for arg in Shellwords::shellwords(args)
- arg, val = arg.split('=', 2)
- next unless arg
- arg.tr!('_', '-')
- if arg.sub!(/^(?!--)/, '--')
- val or next
- arg.downcase!
- end
- next if /^--(?:top|topsrc|src|cur)dir$/ =~ arg
- $configure_args[arg] = val || true
- end
- for arg in ARGV
- arg, val = arg.split('=', 2)
- next unless arg
- arg.tr!('_', '-')
- if arg.sub!(/^(?!--)/, '--')
- val or next
- arg.downcase!
- end
- $configure_args[arg] = val || true
- end
-end
-
-$libdir = CONFIG["libdir"]
-$rubylibdir = CONFIG["rubylibdir"]
-$archdir = CONFIG["archdir"]
-$sitedir = CONFIG["sitedir"]
-$sitelibdir = CONFIG["sitelibdir"]
-$sitearchdir = CONFIG["sitearchdir"]
-$vendordir = CONFIG["vendordir"]
-$vendorlibdir = CONFIG["vendorlibdir"]
-$vendorarchdir = CONFIG["vendorarchdir"]
-
-$mswin = /mswin/ =~ RUBY_PLATFORM
-$bccwin = /bccwin/ =~ RUBY_PLATFORM
-$mingw = /mingw/ =~ RUBY_PLATFORM
-$cygwin = /cygwin/ =~ RUBY_PLATFORM
-$netbsd = /netbsd/ =~ RUBY_PLATFORM
-$os2 = /os2/ =~ RUBY_PLATFORM
-$beos = /beos/ =~ RUBY_PLATFORM
-$haiku = /haiku/ =~ RUBY_PLATFORM
-$solaris = /solaris/ =~ RUBY_PLATFORM
-$universal = /universal/ =~ RUBY_PLATFORM
-$dest_prefix_pattern = (File::PATH_SEPARATOR == ';' ? /\A([[:alpha:]]:)?/ : /\A/)
-
-# :stopdoc:
-
-def config_string(key, config = CONFIG)
- s = config[key] and !s.empty? and block_given? ? yield(s) : s
-end
-
-def dir_re(dir)
- Regexp.new('\$(?:\('+dir+'\)|\{'+dir+'\})(?:\$(?:\(target_prefix\)|\{target_prefix\}))?')
-end
-
-def relative_from(path, base)
- dir = File.join(path, "")
- if File.expand_path(dir) == File.expand_path(dir, base)
- path
- else
- File.join(base, path)
- end
-end
-
-INSTALL_DIRS = [
- [dir_re('commondir'), "$(RUBYCOMMONDIR)"],
- [dir_re('sitedir'), "$(RUBYCOMMONDIR)"],
- [dir_re('vendordir'), "$(RUBYCOMMONDIR)"],
- [dir_re('rubylibdir'), "$(RUBYLIBDIR)"],
- [dir_re('archdir'), "$(RUBYARCHDIR)"],
- [dir_re('sitelibdir'), "$(RUBYLIBDIR)"],
- [dir_re('vendorlibdir'), "$(RUBYLIBDIR)"],
- [dir_re('sitearchdir'), "$(RUBYARCHDIR)"],
- [dir_re('vendorarchdir'), "$(RUBYARCHDIR)"],
- [dir_re('rubyhdrdir'), "$(RUBYHDRDIR)"],
- [dir_re('sitehdrdir'), "$(SITEHDRDIR)"],
- [dir_re('vendorhdrdir'), "$(VENDORHDRDIR)"],
- [dir_re('bindir'), "$(BINDIR)"],
-]
-
-def install_dirs(target_prefix = nil)
- if $extout
- dirs = [
- ['BINDIR', '$(extout)/bin'],
- ['RUBYCOMMONDIR', '$(extout)/common'],
- ['RUBYLIBDIR', '$(RUBYCOMMONDIR)$(target_prefix)'],
- ['RUBYARCHDIR', '$(extout)/$(arch)$(target_prefix)'],
- ['HDRDIR', '$(extout)/include/ruby$(target_prefix)'],
- ['ARCHHDRDIR', '$(extout)/include/$(arch)/ruby$(target_prefix)'],
- ['extout', "#$extout"],
- ['extout_prefix', "#$extout_prefix"],
- ]
- elsif $extmk
- dirs = [
- ['BINDIR', '$(bindir)'],
- ['RUBYCOMMONDIR', '$(rubylibdir)'],
- ['RUBYLIBDIR', '$(rubylibdir)$(target_prefix)'],
- ['RUBYARCHDIR', '$(archdir)$(target_prefix)'],
- ['HDRDIR', '$(rubyhdrdir)/ruby$(target_prefix)'],
- ['ARCHHDRDIR', '$(rubyhdrdir)/$(arch)/ruby$(target_prefix)'],
- ]
- elsif $configure_args.has_key?('--vendor')
- dirs = [
- ['BINDIR', '$(bindir)'],
- ['RUBYCOMMONDIR', '$(vendordir)$(target_prefix)'],
- ['RUBYLIBDIR', '$(vendorlibdir)$(target_prefix)'],
- ['RUBYARCHDIR', '$(vendorarchdir)$(target_prefix)'],
- ['HDRDIR', '$(rubyhdrdir)/ruby$(target_prefix)'],
- ['ARCHHDRDIR', '$(rubyhdrdir)/$(arch)/ruby$(target_prefix)'],
- ]
- else
- dirs = [
- ['BINDIR', '$(bindir)'],
- ['RUBYCOMMONDIR', '$(sitedir)$(target_prefix)'],
- ['RUBYLIBDIR', '$(sitelibdir)$(target_prefix)'],
- ['RUBYARCHDIR', '$(sitearchdir)$(target_prefix)'],
- ['HDRDIR', '$(rubyhdrdir)/ruby$(target_prefix)'],
- ['ARCHHDRDIR', '$(rubyhdrdir)/$(arch)/ruby$(target_prefix)'],
- ]
- end
- dirs << ['target_prefix', (target_prefix ? "/#{target_prefix}" : "")]
- dirs
-end
-
-def map_dir(dir, map = nil)
- map ||= INSTALL_DIRS
- map.inject(dir) {|d, (orig, new)| d.gsub(orig, new)}
-end
-
-topdir = File.dirname(File.dirname(__FILE__))
-path = File.expand_path($0)
-$extmk = path[0, topdir.size+1] == topdir+"/"
-$extmk &&= %r"\A(?:ext|enc|tool|test(?:/.+)?)\z" =~ File.dirname(path[topdir.size+1..-1])
-$extmk &&= true
-if not $extmk and File.exist?(($hdrdir = RbConfig::CONFIG["rubyhdrdir"]) + "/ruby/ruby.h")
- $topdir = $hdrdir
- $top_srcdir = $hdrdir
- $arch_hdrdir = $hdrdir + "/$(arch)"
-elsif File.exist?(($hdrdir = ($top_srcdir ||= topdir) + "/include") + "/ruby.h")
- $topdir ||= RbConfig::CONFIG["topdir"]
- $arch_hdrdir = "$(extout)/include/$(arch)"
-else
- abort "mkmf.rb can't find header files for ruby at #{$hdrdir}/ruby.h"
-end
-
-OUTFLAG = CONFIG['OUTFLAG']
-COUTFLAG = CONFIG['COUTFLAG']
-CPPOUTFILE = CONFIG['CPPOUTFILE']
-
-CONFTEST_C = "conftest.c".freeze
-
-class String
- # Wraps a string in escaped quotes if it contains whitespace.
- def quote
- /\s/ =~ self ? "\"#{self}\"" : "#{self}"
- end
-
- # Generates a string used as cpp macro name.
- def tr_cpp
- strip.upcase.tr_s("^A-Z0-9_*", "_").tr_s("*", "P")
- end
-end
-class Array
- # Wraps all strings in escaped quotes if they contain whitespace.
- def quote
- map {|s| s.quote}
- end
-end
-
-def rm_f(*files)
- opt = (Hash === files.last ? [files.pop] : [])
- FileUtils.rm_f(Dir[*files.flatten], *opt)
-end
-
-def rm_rf(*files)
- opt = (Hash === files.last ? [files.pop] : [])
- FileUtils.rm_rf(Dir[*files.flatten], *opt)
-end
-
-# Returns time stamp of the +target+ file if it exists and is newer
-# than or equal to all of +times+.
-def modified?(target, times)
- (t = File.mtime(target)) rescue return nil
- Array === times or times = [times]
- t if times.all? {|n| n <= t}
-end
-
-def merge_libs(*libs)
- libs.inject([]) do |x, y|
- xy = x & y
- xn = yn = 0
- y = y.inject([]) {|ary, e| ary.last == e ? ary : ary << e}
- y.each_with_index do |v, yi|
- if xy.include?(v)
- xi = [x.index(v), xn].max()
- x[xi, 1] = y[yn..yi]
- xn, yn = xi + (yi - yn + 1), yi + 1
- end
- end
- x.concat(y[yn..-1] || [])
- end
-end
-
-# This is a custom logging module. It generates an mkmf.log file when you
-# run your extconf.rb script. This can be useful for debugging unexpected
-# failures.
-#
-# This module and its associated methods are meant for internal use only.
-#
-module Logging
- @log = nil
- @logfile = 'mkmf.log'
- @orgerr = $stderr.dup
- @orgout = $stdout.dup
- @postpone = 0
- @quiet = $extmk
-
- def self::log_open
- @log ||= File::open(@logfile, 'wb')
- @log.sync = true
- end
-
- def self::open
- log_open
- $stderr.reopen(@log)
- $stdout.reopen(@log)
- yield
- ensure
- $stderr.reopen(@orgerr)
- $stdout.reopen(@orgout)
- end
-
- def self::message(*s)
- log_open
- @log.printf(*s)
- end
-
- def self::logfile file
- @logfile = file
- log_close
- end
-
- def self::log_close
- if @log and not @log.closed?
- @log.flush
- @log.close
- @log = nil
- end
- end
-
- def self::postpone
- tmplog = "mkmftmp#{@postpone += 1}.log"
- open do
- log, *save = @log, @logfile, @orgout, @orgerr
- @log, @logfile, @orgout, @orgerr = nil, tmplog, log, log
- begin
- log.print(open {yield @log})
- ensure
- @log.close if @log and not @log.closed?
- File::open(tmplog) {|t| FileUtils.copy_stream(t, log)} if File.exist?(tmplog)
- @log, @logfile, @orgout, @orgerr = log, *save
- @postpone -= 1
- rm_f tmplog
- end
- end
- end
-
- class << self
- attr_accessor :quiet
- end
-end
-
-def xsystem command, opts = nil
- varpat = /\$\((\w+)\)|\$\{(\w+)\}/
- if varpat =~ command
- vars = Hash.new {|h, k| h[k] = ''; ENV[k]}
- command = command.dup
- nil while command.gsub!(varpat) {vars[$1||$2]}
- end
- Logging::open do
- puts command.quote
- if opts and opts[:werror]
- result = nil
- Logging.postpone do |log|
- result = (system(command) and File.zero?(log.path))
- ""
- end
- result
- else
- system(command)
- end
- end
-end
-
-def xpopen command, *mode, &block
- Logging::open do
- case mode[0]
- when nil, /^r/
- puts "#{command} |"
- else
- puts "| #{command}"
- end
- IO.popen(command, *mode, &block)
- end
-end
-
-def log_src(src, heading="checked program was")
- src = src.split(/^/)
- fmt = "%#{src.size.to_s.size}d: %s"
- Logging::message <<"EOM"
-#{heading}:
-/* begin */
-EOM
- src.each_with_index {|line, no| Logging::message fmt, no+1, line}
- Logging::message <<"EOM"
-/* end */
-
-EOM
-end
-
-def create_tmpsrc(src)
- src = "#{COMMON_HEADERS}\n#{src}"
- src = yield(src) if block_given?
- src.gsub!(/[ \t]+$/, '')
- src.gsub!(/\A\n+|^\n+$/, '')
- src.sub!(/[^\n]\z/, "\\&\n")
- count = 0
- begin
- open(CONFTEST_C, "wb") do |cfile|
- cfile.print src
- end
- rescue Errno::EACCES
- if (count += 1) < 5
- sleep 0.2
- retry
- end
- end
- src
-end
-
-def have_devel?
- unless defined? $have_devel
- $have_devel = true
- $have_devel = try_link(MAIN_DOES_NOTHING)
- end
- $have_devel
-end
-
-def try_do(src, command, *opts, &b)
- unless have_devel?
- raise <<MSG
-The compiler failed to generate an executable file.
-You have to install development tools first.
-MSG
- end
- begin
- src = create_tmpsrc(src, &b)
- xsystem(command, *opts)
- ensure
- log_src(src)
- rm_rf 'conftest.dSYM'
- end
-end
-
-def link_command(ldflags, opt="", libpath=$DEFLIBPATH|$LIBPATH)
- librubyarg = $extmk ? $LIBRUBYARG_STATIC : "$(LIBRUBYARG)"
- conf = RbConfig::CONFIG.merge('hdrdir' => $hdrdir.quote,
- 'src' => "#{CONFTEST_C}",
- 'arch_hdrdir' => $arch_hdrdir.quote,
- 'top_srcdir' => $top_srcdir.quote,
- 'INCFLAGS' => "#$INCFLAGS",
- 'CPPFLAGS' => "#$CPPFLAGS",
- 'CFLAGS' => "#$CFLAGS",
- 'ARCH_FLAG' => "#$ARCH_FLAG",
- 'LDFLAGS' => "#$LDFLAGS #{ldflags}",
- 'LOCAL_LIBS' => "#$LOCAL_LIBS #$libs",
- 'LIBS' => "#{librubyarg} #{opt} #$LIBS")
- conf['LIBPATH'] = libpathflag(libpath.map {|s| RbConfig::expand(s.dup, conf)})
- RbConfig::expand(TRY_LINK.dup, conf)
-end
-
-def cc_command(opt="")
- conf = RbConfig::CONFIG.merge('hdrdir' => $hdrdir.quote, 'srcdir' => $srcdir.quote,
- 'arch_hdrdir' => $arch_hdrdir.quote,
- 'top_srcdir' => $top_srcdir.quote)
- RbConfig::expand("$(CC) #$INCFLAGS #$CPPFLAGS #$CFLAGS #$ARCH_FLAG #{opt} -c #{CONFTEST_C}",
- conf)
-end
-
-def cpp_command(outfile, opt="")
- conf = RbConfig::CONFIG.merge('hdrdir' => $hdrdir.quote, 'srcdir' => $srcdir.quote,
- 'arch_hdrdir' => $arch_hdrdir.quote,
- 'top_srcdir' => $top_srcdir.quote)
- RbConfig::expand("$(CPP) #$INCFLAGS #$CPPFLAGS #$CFLAGS #{opt} #{CONFTEST_C} #{outfile}",
- conf)
-end
-
-def libpathflag(libpath=$DEFLIBPATH|$LIBPATH)
- libpath.map{|x|
- case x
- when "$(topdir)", /\A\./
- LIBPATHFLAG
- else
- LIBPATHFLAG+RPATHFLAG
- end % x.quote
- }.join
-end
-
-def with_werror(opt, opts = nil)
- if opts
- if opts[:werror] and config_string("WERRORFLAG") {|flag| opt = opt ? "#{opt} #{flag}" : flag}
- (opts = opts.dup).delete(:werror)
- end
- yield(opt, opts)
- else
- yield(opt)
- end
-end
-
-# :nodoc:
-def try_link0(src, opt="", *opts, &b)
- cmd = link_command("", opt)
- if $universal
- require 'tmpdir'
- Dir.mktmpdir("mkmf_", oldtmpdir = ENV["TMPDIR"]) do |tmpdir|
- begin
- ENV["TMPDIR"] = tmpdir
- try_do(src, cmd, *opts, &b)
- ensure
- ENV["TMPDIR"] = oldtmpdir
- end
- end
- else
- try_do(src, cmd, *opts, &b)
- end
-end
-
-# Returns whether or not the +src+ can be compiled as a C source and
-# linked with its depending libraries successfully.
-# +opt+ is passed to the linker as options. Note that +$CFLAGS+ and +$LDFLAGS+
-# are also passed to the linker.
-#
-# If a block given, it is called with the source before compilation. You can
-# modify the source in the block.
-#
-# [+src+] a String which contains a C source
-# [+opt+] a String which contains linker options
-def try_link(src, opt="", *opts, &b)
- try_link0(src, opt, *opts, &b)
-ensure
- rm_f "conftest*", "c0x32*"
-end
-
-# Returns whether or not the +src+ can be compiled as a C source.
-# +opt+ is passed to the C compiler as options. Note that +$CFLAGS+ is
-# also passed to the compiler.
-#
-# If a block given, it is called with the source before compilation. You can
-# modify the source in the block.
-#
-# [+src+] a String which contains a C source
-# [+opt+] a String which contains compiler options
-def try_compile(src, opt="", *opts, &b)
- with_werror(opt, *opts) {|_opt, *_opts| try_do(src, cc_command(_opt), *_opts, &b)}
-ensure
- rm_f "conftest*"
-end
-
-# Returns whether or not the +src+ can be preprocessed with the C preprocessor.
-# +opt+ is passed to the preprocessor as options. Note that +$CFLAGS+ is
-# also passed to the preprocessor.
-#
-# If a block given, it is called with the source before preprocessing. You can
-# modify the source in the block.
-#
-# [+src+] a String which contains a C source
-# [+opt+] a String which contains preprocessor options
-def try_cpp(src, opt="", *opts, &b)
- try_do(src, cpp_command(CPPOUTFILE, opt), *opts, &b)
-ensure
- rm_f "conftest*"
-end
-
-class Object
- alias_method :try_header, (config_string('try_header') || :try_cpp)
-end
-
-def cpp_include(header)
- if header
- header = [header] unless header.kind_of? Array
- header.map {|h| String === h ? "#include <#{h}>\n" : h}.join
- else
- ""
- end
-end
-
-def with_cppflags(flags)
- cppflags = $CPPFLAGS
- $CPPFLAGS = flags
- ret = yield
-ensure
- $CPPFLAGS = cppflags unless ret
-end
-
-def with_cflags(flags)
- cflags = $CFLAGS
- $CFLAGS = flags
- ret = yield
-ensure
- $CFLAGS = cflags unless ret
-end
-
-def with_ldflags(flags)
- ldflags = $LDFLAGS
- $LDFLAGS = flags
- ret = yield
-ensure
- $LDFLAGS = ldflags unless ret
-end
-
-def try_static_assert(expr, headers = nil, opt = "", &b)
- headers = cpp_include(headers)
- try_compile(<<SRC, opt, &b)
-#{headers}
-/*top*/
-int conftest_const[(#{expr}) ? 1 : -1];
-SRC
-end
-
-def try_constant(const, headers = nil, opt = "", &b)
- includes = cpp_include(headers)
- if CROSS_COMPILING
- if try_static_assert("#{const} > 0", headers, opt)
- # positive constant
- elsif try_static_assert("#{const} < 0", headers, opt)
- neg = true
- const = "-(#{const})"
- elsif try_static_assert("#{const} == 0", headers, opt)
- return 0
- else
- # not a constant
- return nil
- end
- upper = 1
- lower = 0
- until try_static_assert("#{const} <= #{upper}", headers, opt)
- lower = upper
- upper <<= 1
- end
- return nil unless lower
- while upper > lower + 1
- mid = (upper + lower) / 2
- if try_static_assert("#{const} > #{mid}", headers, opt)
- lower = mid
- else
- upper = mid
- end
- end
- upper = -upper if neg
- return upper
- else
- src = %{#{includes}
-#include <stdio.h>
-/*top*/
-int conftest_const = (int)(#{const});
-int main() {printf("%d\\n", conftest_const); return 0;}
-}
- if try_link0(src, opt, &b)
- xpopen("./conftest") do |f|
- return Integer(f.gets)
- end
- end
- end
- nil
-end
-
-# You should use +have_func+ rather than +try_func+.
-#
-# [+func+] a String which contains a symbol name
-# [+libs+] a String which contains library names.
-# [+headers+] a String or an Array of strings which contains
-# names of header files.
-def try_func(func, libs, headers = nil, &b)
- headers = cpp_include(headers)
- case func
- when /^&/
- decltype = proc {|x|"const volatile void *#{x}"}
- else
- call = true
- decltype = proc {|x| "void ((*#{x})())"}
- end
- try_link(<<"SRC", libs, &b) or
-#{headers}
-/*top*/
-int t() { #{decltype["volatile p"]}; p = (#{decltype[]})#{func}; return 0; }
-#{MAIN_DOES_NOTHING "t"}
-SRC
- call && try_link(<<"SRC", libs, &b)
-#{headers}
-/*top*/
-int t() { #{func}(); return 0; }
-#{MAIN_DOES_NOTHING "t"}
-SRC
-end
-
-# You should use +have_var+ rather than +try_var+.
-def try_var(var, headers = nil, &b)
- headers = cpp_include(headers)
- try_compile(<<"SRC", &b)
-#{headers}
-/*top*/
-int t() { const volatile void *volatile p; p = &(&#{var})[0]; return 0; }
-#{MAIN_DOES_NOTHING "t"}
-SRC
-end
-
-# Returns whether or not the +src+ can be preprocessed with the C preprocessor and
-# matches with +pat+.
-#
-# If a block given, it is called with the source before compilation. You can
-# modify the source in the block.
-#
-# [+pat+] a Regexp or a String
-# [+src+] a String which contains a C source
-# [+opt+] a String which contains preprocessor options
-#
-# Note:
-# When pat is a Regexp the matching will be checked in process,
-# otherwise egrep(1) will be invoked to check it.
-def egrep_cpp(pat, src, opt = "", &b)
- src = create_tmpsrc(src, &b)
- xpopen(cpp_command('', opt)) do |f|
- if Regexp === pat
- puts(" ruby -ne 'print if #{pat.inspect}'")
- f.grep(pat) {|l|
- puts "#{f.lineno}: #{l}"
- return true
- }
- false
- else
- puts(" egrep '#{pat}'")
- begin
- stdin = $stdin.dup
- $stdin.reopen(f)
- system("egrep", pat)
- ensure
- $stdin.reopen(stdin)
- end
- end
- end
-ensure
- rm_f "conftest*"
- log_src(src)
-end
-
-# This is used internally by the have_macro? method.
-def macro_defined?(macro, src, opt = "", &b)
- src = src.sub(/[^\n]\z/, "\\&\n")
- try_compile(src + <<"SRC", opt, &b)
-/*top*/
-#ifndef #{macro}
-# error
->>>>>> #{macro} undefined <<<<<<
-#endif
-SRC
-end
-
-# Returns whether or not
-# * the +src+ can be compiled as a C source,
-# * the result object can be linked with its depending libraries successfully,
-# * the linked file can be invoked as an executable
-# * and the executable exits successfully
-# +opt+ is passed to the linker as options. Note that +$CFLAGS+ and +$LDFLAGS+
-# are also passed to the linker.
-#
-# If a block given, it is called with the source before compilation. You can
-# modify the source in the block.
-#
-# [+src+] a String which contains a C source
-# [+opt+] a String which contains linker options
-#
-# @return true when the executable exits successfully, false when it fails, or
-# nil when preprocessing, compilation or link fails.
-def try_run(src, opt = "", &b)
- if try_link0(src, opt, &b)
- xsystem("./conftest")
- else
- nil
- end
-ensure
- rm_f "conftest*"
-end
-
-def install_files(mfile, ifiles, map = nil, srcprefix = nil)
- ifiles or return
- ifiles.empty? and return
- srcprefix ||= "$(srcdir)/#{srcprefix}".chomp('/')
- RbConfig::expand(srcdir = srcprefix.dup)
- dirs = []
- path = Hash.new {|h, i| h[i] = dirs.push([i])[-1]}
- ifiles.each do |files, dir, prefix|
- dir = map_dir(dir, map)
- prefix &&= %r|\A#{Regexp.quote(prefix)}/?|
- if /\A\.\// =~ files
- # install files which are in current working directory.
- files = files[2..-1]
- len = nil
- else
- # install files which are under the $(srcdir).
- files = File.join(srcdir, files)
- len = srcdir.size
- end
- f = nil
- Dir.glob(files) do |fx|
- f = fx
- f[0..len] = "" if len
- case File.basename(f)
- when *$NONINSTALLFILES
- next
- end
- d = File.dirname(f)
- d.sub!(prefix, "") if prefix
- d = (d.empty? || d == ".") ? dir : File.join(dir, d)
- f = File.join(srcprefix, f) if len
- path[d] << f
- end
- unless len or f
- d = File.dirname(files)
- d.sub!(prefix, "") if prefix
- d = (d.empty? || d == ".") ? dir : File.join(dir, d)
- path[d] << files
- end
- end
- dirs
-end
-
-def install_rb(mfile, dest, srcdir = nil)
- install_files(mfile, [["lib/**/*.rb", dest, "lib"]], nil, srcdir)
-end
-
-def append_library(libs, lib) # :no-doc:
- format(LIBARG, lib) + " " + libs
-end
-
-def message(*s)
- unless Logging.quiet and not $VERBOSE
- printf(*s)
- $stdout.flush
- end
-end
-
-# This emits a string to stdout that allows users to see the results of the
-# various have* and find* methods as they are tested.
-#
-# Internal use only.
-#
-def checking_for(m, fmt = nil)
- f = caller[0][/in `([^<].*)'$/, 1] and f << ": " #` for vim #'
- m = "checking #{/\Acheck/ =~ f ? '' : 'for '}#{m}... "
- message "%s", m
- a = r = nil
- Logging::postpone do
- r = yield
- a = (fmt ? fmt % r : r ? "yes" : "no") << "\n"
- "#{f}#{m}-------------------- #{a}\n"
- end
- message(a)
- Logging::message "--------------------\n\n"
- r
-end
-
-def checking_message(target, place = nil, opt = nil)
- [["in", place], ["with", opt]].inject("#{target}") do |msg, (pre, noun)|
- if noun
- [[:to_str], [:join, ","], [:to_s]].each do |meth, *args|
- if noun.respond_to?(meth)
- break noun = noun.send(meth, *args)
- end
- end
- msg << " #{pre} #{noun}" unless noun.empty?
- end
- msg
- end
-end
-
-# :startdoc:
-
-# Returns whether or not +macro+ is defined either in the common header
-# files or within any +headers+ you provide.
-#
-# Any options you pass to +opt+ are passed along to the compiler.
-#
-def have_macro(macro, headers = nil, opt = "", &b)
- checking_for checking_message(macro, headers, opt) do
- macro_defined?(macro, cpp_include(headers), opt, &b)
- end
-end
-
-# Returns whether or not the given entry point +func+ can be found within
-# +lib+. If +func+ is nil, the 'main()' entry point is used by default.
-# If found, it adds the library to list of libraries to be used when linking
-# your extension.
-#
-# If +headers+ are provided, it will include those header files as the
-# header files it looks in when searching for +func+.
-#
-# The real name of the library to be linked can be altered by
-# '--with-FOOlib' configuration option.
-#
-def have_library(lib, func = nil, headers = nil, &b)
- func = "main" if !func or func.empty?
- lib = with_config(lib+'lib', lib)
- checking_for checking_message("#{func}()", LIBARG%lib) do
- if COMMON_LIBS.include?(lib)
- true
- else
- libs = append_library($libs, lib)
- if try_func(func, libs, headers, &b)
- $libs = libs
- true
- else
- false
- end
- end
- end
-end
-
-# Returns whether or not the entry point +func+ can be found within the library
-# +lib+ in one of the +paths+ specified, where +paths+ is an array of strings.
-# If +func+ is nil , then the main() function is used as the entry point.
-#
-# If +lib+ is found, then the path it was found on is added to the list of
-# library paths searched and linked against.
-#
-def find_library(lib, func, *paths, &b)
- func = "main" if !func or func.empty?
- lib = with_config(lib+'lib', lib)
- paths = paths.collect {|path| path.split(File::PATH_SEPARATOR)}.flatten
- checking_for "#{func}() in #{LIBARG%lib}" do
- libpath = $LIBPATH
- libs = append_library($libs, lib)
- begin
- until r = try_func(func, libs, &b) or paths.empty?
- $LIBPATH = libpath | [paths.shift]
- end
- if r
- $libs = libs
- libpath = nil
- end
- ensure
- $LIBPATH = libpath if libpath
- end
- r
- end
-end
-
-# Returns whether or not the function +func+ can be found in the common
-# header files, or within any +headers+ that you provide. If found, a
-# macro is passed as a preprocessor constant to the compiler using the
-# function name, in uppercase, prepended with 'HAVE_'.
-#
-# For example, if have_func('foo') returned true, then the HAVE_FOO
-# preprocessor macro would be passed to the compiler.
-#
-def have_func(func, headers = nil, &b)
- checking_for checking_message("#{func}()", headers) do
- if try_func(func, $libs, headers, &b)
- $defs.push(format("-DHAVE_%s", func.tr_cpp))
- true
- else
- false
- end
- end
-end
-
-# Returns whether or not the variable +var+ can be found in the common
-# header files, or within any +headers+ that you provide. If found, a
-# macro is passed as a preprocessor constant to the compiler using the
-# variable name, in uppercase, prepended with 'HAVE_'.
-#
-# For example, if have_var('foo') returned true, then the HAVE_FOO
-# preprocessor macro would be passed to the compiler.
-#
-def have_var(var, headers = nil, &b)
- checking_for checking_message(var, headers) do
- if try_var(var, headers, &b)
- $defs.push(format("-DHAVE_%s", var.tr_cpp))
- true
- else
- false
- end
- end
-end
-
-# Returns whether or not the given +header+ file can be found on your system.
-# If found, a macro is passed as a preprocessor constant to the compiler using
-# the header file name, in uppercase, prepended with 'HAVE_'.
-#
-# For example, if have_header('foo.h') returned true, then the HAVE_FOO_H
-# preprocessor macro would be passed to the compiler.
-#
-def have_header(header, preheaders = nil, &b)
- checking_for header do
- if try_header(cpp_include(preheaders)+cpp_include(header), &b)
- $defs.push(format("-DHAVE_%s", header.tr_cpp))
- true
- else
- false
- end
- end
-end
-
-# Returns whether or not the given +framework+ can be found on your system.
-# If found, a macro is passed as a preprocessor constant to the compiler using
-# the framework name, in uppercase, prepended with 'HAVE_FRAMEWORK_'.
-#
-# For example, if have_framework('Ruby') returned true, then the HAVE_FRAMEWORK_RUBY
-# preprocessor macro would be passed to the compiler.
-#
-def have_framework(fw, &b)
- checking_for fw do
- src = cpp_include("#{fw}/#{fw}.h") << "\n" "int main(void){return 0;}"
- if try_link(src, opt = "-framework #{fw}", &b)
- $defs.push(format("-DHAVE_FRAMEWORK_%s", fw.tr_cpp))
- $LDFLAGS << " " << opt
- true
- else
- false
- end
- end
-end
-
-# Instructs mkmf to search for the given +header+ in any of the +paths+
-# provided, and returns whether or not it was found in those paths.
-#
-# If the header is found then the path it was found on is added to the list
-# of included directories that are sent to the compiler (via the -I switch).
-#
-def find_header(header, *paths)
- message = checking_message(header, paths)
- header = cpp_include(header)
- checking_for message do
- if try_header(header)
- true
- else
- found = false
- paths.each do |dir|
- opt = "-I#{dir}".quote
- if try_header(header, opt)
- $INCFLAGS << " " << opt
- found = true
- break
- end
- end
- found
- end
- end
-end
-
-# Returns whether or not the struct of type +type+ contains +member+. If
-# it does not, or the struct type can't be found, then false is returned. You
-# may optionally specify additional +headers+ in which to look for the struct
-# (in addition to the common header files).
-#
-# If found, a macro is passed as a preprocessor constant to the compiler using
-# the type name and the member name, in uppercase, prepended with 'HAVE_'.
-#
-# For example, if have_struct_member('struct foo', 'bar') returned true, then the
-# HAVE_STRUCT_FOO_BAR preprocessor macro would be passed to the compiler.
-#
-# HAVE_ST_BAR is also defined for backward compatibility.
-#
-def have_struct_member(type, member, headers = nil, &b)
- checking_for checking_message("#{type}.#{member}", headers) do
- if try_compile(<<"SRC", &b)
-#{cpp_include(headers)}
-/*top*/
-int s = (char *)&((#{type}*)0)->#{member} - (char *)0;
-#{MAIN_DOES_NOTHING "s"}
-SRC
- $defs.push(format("-DHAVE_%s_%s", type.tr_cpp, member.tr_cpp))
- $defs.push(format("-DHAVE_ST_%s", member.tr_cpp)) # backward compatibility
- true
- else
- false
- end
- end
-end
-
-# Returns whether or not the static type +type+ is defined.
-#
-# See also +have_type+
-#
-def try_type(type, headers = nil, opt = "", &b)
- if try_compile(<<"SRC", opt, &b)
-#{cpp_include(headers)}
-/*top*/
-typedef #{type} conftest_type;
-int conftestval[sizeof(conftest_type)?1:-1];
-SRC
- $defs.push(format("-DHAVE_TYPE_%s", type.tr_cpp))
- true
- else
- false
- end
-end
-
-# Returns whether or not the static type +type+ is defined. You may
-# optionally pass additional +headers+ to check against in addition to the
-# common header files.
-#
-# You may also pass additional flags to +opt+ which are then passed along to
-# the compiler.
-#
-# If found, a macro is passed as a preprocessor constant to the compiler using
-# the type name, in uppercase, prepended with 'HAVE_TYPE_'.
-#
-# For example, if have_type('foo') returned true, then the HAVE_TYPE_FOO
-# preprocessor macro would be passed to the compiler.
-#
-def have_type(type, headers = nil, opt = "", &b)
- checking_for checking_message(type, headers, opt) do
- try_type(type, headers, opt, &b)
- end
-end
-
-# Returns where the static type +type+ is defined.
-#
-# You may also pass additional flags to +opt+ which are then passed along to
-# the compiler.
-#
-# See also +have_type+.
-#
-def find_type(type, opt, *headers, &b)
- opt ||= ""
- fmt = "not found"
- def fmt.%(x)
- x ? x.respond_to?(:join) ? x.join(",") : x : self
- end
- checking_for checking_message(type, nil, opt), fmt do
- headers.find do |h|
- try_type(type, h, opt, &b)
- end
- end
-end
-
-# Returns whether or not the Constant +const+ is defined.
-#
-# See also +have_const+
-#
-def try_const(const, headers = nil, opt = "", &b)
- const, type = *const
- if try_compile(<<"SRC", opt, &b)
-#{cpp_include(headers)}
-/*top*/
-typedef #{type || 'int'} conftest_type;
-conftest_type conftestval = #{type ? '' : '(int)'}#{const};
-SRC
- $defs.push(format("-DHAVE_CONST_%s", const.tr_cpp))
- true
- else
- false
- end
-end
-
-# Returns whether or not the constant +const+ is defined. You may
-# optionally pass the +type+ of +const+ as <code>[const, type]</code>,
-# like as:
-#
-# have_const(%w[PTHREAD_MUTEX_INITIALIZER pthread_mutex_t], "pthread.h")
-#
-# You may also pass additional +headers+ to check against in addition
-# to the common header files, and additional flags to +opt+ which are
-# then passed along to the compiler.
-#
-# If found, a macro is passed as a preprocessor constant to the compiler using
-# the type name, in uppercase, prepended with 'HAVE_CONST_'.
-#
-# For example, if have_const('foo') returned true, then the HAVE_CONST_FOO
-# preprocessor macro would be passed to the compiler.
-#
-def have_const(const, headers = nil, opt = "", &b)
- checking_for checking_message([*const].compact.join(' '), headers, opt) do
- try_const(const, headers, opt, &b)
- end
-end
-
-STRING_OR_FAILED_FORMAT = "%s"
-# :stopdoc:
-def STRING_OR_FAILED_FORMAT.%(x)
- x ? super : "failed"
-end
-
-def typedef_expr(type, headers)
- typename, member = type.split('.', 2)
- prelude = cpp_include(headers).split(/$/)
- prelude << "typedef #{typename} rbcv_typedef_;\n"
- return "rbcv_typedef_", member, prelude
-end
-
-def try_signedness(type, member, headers = nil, opts = nil, &b)
- raise ArgumentError, "don't know how to tell signedness of members" if member
- if try_static_assert("(#{type})-1 < 0", headers, opts)
- return -1
- elsif try_static_assert("(#{type})-1 > 0", headers, opts)
- return +1
- end
-end
-
-# :startdoc:
-
-# Returns the size of the given +type+. You may optionally specify additional
-# +headers+ to search in for the +type+.
-#
-# If found, a macro is passed as a preprocessor constant to the compiler using
-# the type name, in uppercase, prepended with 'SIZEOF_', followed by the type
-# name, followed by '=X' where 'X' is the actual size.
-#
-# For example, if check_sizeof('mystruct') returned 12, then the
-# SIZEOF_MYSTRUCT=12 preprocessor macro would be passed to the compiler.
-#
-def check_sizeof(type, headers = nil, opts = "", &b)
- typedef, member, prelude = typedef_expr(type, headers)
- prelude << "static #{typedef} *rbcv_ptr_;\n"
- prelude = [prelude]
- expr = "sizeof((*rbcv_ptr_)#{"." << member if member})"
- fmt = STRING_OR_FAILED_FORMAT
- checking_for checking_message("size of #{type}", headers), fmt do
- if size = try_constant(expr, prelude, opts, &b)
- $defs.push(format("-DSIZEOF_%s=%s", type.tr_cpp, size))
- size
- end
- end
-end
-
-# Returns the signedness of the given +type+. You may optionally
-# specify additional +headers+ to search in for the +type+.
-#
-# If the +type+ is found and is a numeric type, a macro is passed as a
-# preprocessor constant to the compiler using the +type+ name, in
-# uppercase, prepended with 'SIGNEDNESS_OF_', followed by the +type+
-# name, followed by '=X' where 'X' is positive integer if the +type+ is
-# unsigned, or negative integer if the +type+ is signed.
-#
-# For example, if size_t is defined as unsigned, then
-# check_signedness('size_t') would returned +1 and the
-# SIGNEDNESS_OF_SIZE_T=+1 preprocessor macro would be passed to the
-# compiler, and SIGNEDNESS_OF_INT=-1 if check_signedness('int') is
-# done.
-#
-def check_signedness(type, headers = nil, opts = nil, &b)
- typedef, member, prelude = typedef_expr(type, headers)
- signed = nil
- checking_for("signedness of #{type}", STRING_OR_FAILED_FORMAT) do
- signed = try_signedness(typedef, member, [prelude], opts, &b) or next nil
- $defs.push("-DSIGNEDNESS_OF_%s=%+d" % [type.tr_cpp, signed])
- signed < 0 ? "signed" : "unsigned"
- end
- signed
-end
-
-# Returns the convertible integer type of the given +type+. You may
-# optionally specify additional +headers+ to search in for the +type+.
-# _Convertible_ means actually same type, or typedefed from same type.
-#
-# If the +type+ is a integer type and _convertible_ type is found,
-# following macros are passed as preprocessor constants to the
-# compiler using the +type+ name, in uppercase.
-#
-# * 'TYPEOF_', followed by the +type+ name, followed by '=X' where 'X'
-# is the found _convertible_ type name. * 'TYP2NUM' and 'NUM2TYP,
-# where 'TYP' is the +type+ name in uppercase with replacing '_t'
-# suffix with 'T', followed by '=X' where 'X' is the macro name to
-# convert +type+ to +Integer+ object, and vice versa.
-#
-# For example, if foobar_t is defined as unsigned long, then
-# convertible_int("foobar_t") would return "unsigned long", and define
-# macros:
-#
-# #define TYPEOF_FOOBAR_T unsigned long
-# #define FOOBART2NUM ULONG2NUM
-# #define NUM2FOOBART NUM2ULONG
-def convertible_int(type, headers = nil, opts = nil, &b)
- type, macname = *type
- checking_for("convertible type of #{type}", STRING_OR_FAILED_FORMAT) do
- if UNIVERSAL_INTS.include?(type)
- type
- else
- typedef, member, prelude = typedef_expr(type, headers, &b)
- next unless signed = try_signedness(typedef, member, [prelude])
- u = "unsigned " if signed > 0
- prelude << "extern rbcv_typedef_ foo();"
- compat = UNIVERSAL_INTS.find {|t|
- try_compile([prelude, "extern #{u}#{t} foo();"].join("\n"), opts, :werror=>true, &b)
- }
- if compat
- macname ||= type.sub(/_(?=t\z)/, '').tr_cpp
- conv = (compat == "long long" ? "LL" : compat.upcase)
- compat = "#{u}#{compat}"
- $defs.push(format("-DTYPEOF_%s=%s", type.tr_cpp, compat.quote))
- $defs.push(format("-DPRI_%s_PREFIX=PRI_%s_PREFIX", macname, conv))
- conv = (u ? "U" : "") + conv
- $defs.push(format("-D%s2NUM=%s2NUM", macname, conv))
- $defs.push(format("-DNUM2%s=NUM2%s", macname, conv))
- compat
- end
- end
- end
-end
-# :stopdoc:
-
-# Used internally by the what_type? method to determine if +type+ is a scalar
-# pointer.
-def scalar_ptr_type?(type, member = nil, headers = nil, &b)
- try_compile(<<"SRC", &b) # pointer
-#{cpp_include(headers)}
-/*top*/
-volatile #{type} conftestval;
-int t() {return (int)(1-*(conftestval#{member ? ".#{member}" : ""}));}
-#{MAIN_DOES_NOTHING "t"}
-SRC
-end
-
-# Used internally by the what_type? method to determine if +type+ is a scalar
-# pointer.
-def scalar_type?(type, member = nil, headers = nil, &b)
- try_compile(<<"SRC", &b) # pointer
-#{cpp_include(headers)}
-/*top*/
-volatile #{type} conftestval;
-int t() {return (int)(1-(conftestval#{member ? ".#{member}" : ""}));}
-#{MAIN_DOES_NOTHING "t"}
-SRC
-end
-
-# Used internally by the what_type? method to check if _typeof_ GCC
-# extension is available.
-def have_typeof?
- return $typeof if defined?($typeof)
- $typeof = %w[__typeof__ typeof].find do |t|
- try_compile(<<SRC)
-int rbcv_foo;
-#{t}(rbcv_foo) rbcv_bar;
-SRC
- end
-end
-
-def what_type?(type, member = nil, headers = nil, &b)
- m = "#{type}"
- var = val = "*rbcv_var_"
- func = "rbcv_func_(void)"
- if member
- m << "." << member
- else
- type, member = type.split('.', 2)
- end
- if member
- val = "(#{var}).#{member}"
- end
- prelude = [cpp_include(headers).split(/^/)]
- prelude << ["typedef #{type} rbcv_typedef_;\n",
- "extern rbcv_typedef_ *#{func};\n",
- "static rbcv_typedef_ #{var};\n",
- ]
- type = "rbcv_typedef_"
- fmt = member && !(typeof = have_typeof?) ? "seems %s" : "%s"
- if typeof
- var = "*rbcv_member_"
- func = "rbcv_mem_func_(void)"
- member = nil
- type = "rbcv_mem_typedef_"
- prelude[-1] << "typedef #{typeof}(#{val}) #{type};\n"
- prelude[-1] << "extern #{type} *#{func};\n"
- prelude[-1] << "static #{type} #{var};\n"
- val = var
- end
- def fmt.%(x)
- x ? super : "unknown"
- end
- checking_for checking_message(m, headers), fmt do
- if scalar_ptr_type?(type, member, prelude, &b)
- if try_static_assert("sizeof(*#{var}) == 1", prelude)
- return "string"
- end
- ptr = "*"
- elsif scalar_type?(type, member, prelude, &b)
- unless member and !typeof or try_static_assert("(#{type})-1 < 0", prelude)
- unsigned = "unsigned"
- end
- ptr = ""
- else
- next
- end
- type = UNIVERSAL_INTS.find do |t|
- pre = prelude
- unless member
- pre += [["static #{unsigned} #{t} #{ptr}#{var};\n",
- "extern #{unsigned} #{t} #{ptr}*#{func};\n"]]
- end
- try_static_assert("sizeof(#{ptr}#{val}) == sizeof(#{unsigned} #{t})", pre)
- end
- type or next
- [unsigned, type, ptr].join(" ").strip
- end
-end
-
-# This method is used internally by the find_executable method.
-#
-# Internal use only.
-#
-def find_executable0(bin, path = nil)
- executable_file = proc do |name|
- begin
- stat = File.stat(name)
- rescue SystemCallError
- else
- next name if stat.file? and stat.executable?
- end
- end
-
- exts = config_string('EXECUTABLE_EXTS') {|s| s.split} || config_string('EXEEXT') {|s| [s]}
- if File.expand_path(bin) == bin
- return bin if executable_file.call(bin)
- if exts
- exts.each {|ext| executable_file.call(file = bin + ext) and return file}
- end
- return nil
- end
- if path ||= ENV['PATH']
- path = path.split(File::PATH_SEPARATOR)
- else
- path = %w[/usr/local/bin /usr/ucb /usr/bin /bin]
- end
- file = nil
- path.each do |dir|
- return file if executable_file.call(file = File.join(dir, bin))
- if exts
- exts.each {|ext| executable_file.call(ext = file + ext) and return ext}
- end
- end
- nil
-end
-
-# :startdoc:
-
-# Searches for the executable +bin+ on +path+. The default path is your
-# PATH environment variable. If that isn't defined, it will resort to
-# searching /usr/local/bin, /usr/ucb, /usr/bin and /bin.
-#
-# If found, it will return the full path, including the executable name,
-# of where it was found.
-#
-# Note that this method does not actually affect the generated Makefile.
-#
-def find_executable(bin, path = nil)
- checking_for checking_message(bin, path) do
- find_executable0(bin, path)
- end
-end
-
-# :stopdoc:
-
-def arg_config(config, default=nil, &block)
- $arg_config << [config, default]
- defaults = []
- if default
- defaults << default
- elsif !block
- defaults << nil
- end
- $configure_args.fetch(config.tr('_', '-'), *defaults, &block)
-end
-
-# :startdoc:
-
-# Tests for the presence of a --with-<tt>config</tt> or --without-<tt>config</tt>
-# option. Returns true if the with option is given, false if the without
-# option is given, and the default value otherwise.
-#
-# This can be useful for adding custom definitions, such as debug information.
-#
-# Example:
-#
-# if with_config("debug")
-# $defs.push("-DOSSL_DEBUG") unless $defs.include? "-DOSSL_DEBUG"
-# end
-#
-def with_config(config, default=nil)
- config = config.sub(/^--with[-_]/, '')
- val = arg_config("--with-"+config) do
- if arg_config("--without-"+config)
- false
- elsif block_given?
- yield(config, default)
- else
- break default
- end
- end
- case val
- when "yes"
- true
- when "no"
- false
- else
- val
- end
-end
-
-# Tests for the presence of an --enable-<tt>config</tt> or
-# --disable-<tt>config</tt> option. Returns true if the enable option is given,
-# false if the disable option is given, and the default value otherwise.
-#
-# This can be useful for adding custom definitions, such as debug information.
-#
-# Example:
-#
-# if enable_config("debug")
-# $defs.push("-DOSSL_DEBUG") unless $defs.include? "-DOSSL_DEBUG"
-# end
-#
-def enable_config(config, default=nil)
- if arg_config("--enable-"+config)
- true
- elsif arg_config("--disable-"+config)
- false
- elsif block_given?
- yield(config, default)
- else
- return default
- end
-end
-
-# Generates a header file consisting of the various macro definitions generated
-# by other methods such as have_func and have_header. These are then wrapped in
-# a custom #ifndef based on the +header+ file name, which defaults to
-# 'extconf.h'.
-#
-# For example:
-#
-# # extconf.rb
-# require 'mkmf'
-# have_func('realpath')
-# have_header('sys/utime.h')
-# create_header
-# create_makefile('foo')
-#
-# The above script would generate the following extconf.h file:
-#
-# #ifndef EXTCONF_H
-# #define EXTCONF_H
-# #define HAVE_REALPATH 1
-# #define HAVE_SYS_UTIME_H 1
-# #endif
-#
-# Given that the create_header method generates a file based on definitions
-# set earlier in your extconf.rb file, you will probably want to make this
-# one of the last methods you call in your script.
-#
-def create_header(header = "extconf.h")
- message "creating %s\n", header
- sym = header.tr_cpp
- hdr = ["#ifndef #{sym}\n#define #{sym}\n"]
- for line in $defs
- case line
- when /^-D([^=]+)(?:=(.*))?/
- hdr << "#define #$1 #{$2 ? Shellwords.shellwords($2)[0].gsub(/(?=\t+)/, "\\\n") : 1}\n"
- when /^-U(.*)/
- hdr << "#undef #$1\n"
- end
- end
- hdr << "#endif\n"
- hdr = hdr.join
- log_src(hdr, "#{header} is")
- unless (IO.read(header) == hdr rescue false)
- open(header, "wb") do |hfile|
- hfile.write(hdr)
- end
- end
- $extconf_h = header
-end
-
-# Sets a +target+ name that the user can then use to configure various 'with'
-# options with on the command line by using that name. For example, if the
-# target is set to "foo", then the user could use the --with-foo-dir command
-# line option.
-#
-# You may pass along additional 'include' or 'lib' defaults via the +idefault+
-# and +ldefault+ parameters, respectively.
-#
-# Note that dir_config only adds to the list of places to search for libraries
-# and include files. It does not link the libraries into your application.
-#
-def dir_config(target, idefault=nil, ldefault=nil)
- if dir = with_config(target + "-dir", (idefault unless ldefault))
- defaults = Array === dir ? dir : dir.split(File::PATH_SEPARATOR)
- idefault = ldefault = nil
- end
-
- idir = with_config(target + "-include", idefault)
- $arg_config.last[1] ||= "${#{target}-dir}/include"
- ldir = with_config(target + "-lib", ldefault)
- $arg_config.last[1] ||= "${#{target}-dir}/#{@libdir_basename}"
-
- idirs = idir ? Array === idir ? idir.dup : idir.split(File::PATH_SEPARATOR) : []
- if defaults
- idirs.concat(defaults.collect {|d| d + "/include"})
- idir = ([idir] + idirs).compact.join(File::PATH_SEPARATOR)
- end
- unless idirs.empty?
- idirs.collect! {|d| "-I" + d}
- idirs -= Shellwords.shellwords($CPPFLAGS)
- unless idirs.empty?
- $CPPFLAGS = (idirs.quote << $CPPFLAGS).join(" ")
- end
- end
-
- ldirs = ldir ? Array === ldir ? ldir.dup : ldir.split(File::PATH_SEPARATOR) : []
- if defaults
- ldirs.concat(defaults.collect {|d| "#{d}/#{@libdir_basename}"})
- ldir = ([ldir] + ldirs).compact.join(File::PATH_SEPARATOR)
- end
- $LIBPATH = ldirs | $LIBPATH
-
- [idir, ldir]
-end
-
-# :stopdoc:
-
-# Handles meta information about installed libraries. Uses your platform's
-# pkg-config program if it has one.
-def pkg_config(pkg)
- if pkgconfig = with_config("#{pkg}-config") and find_executable0(pkgconfig)
- # iff package specific config command is given
- get = proc {|opt| `#{pkgconfig} --#{opt}`.chomp}
- elsif ($PKGCONFIG ||=
- (pkgconfig = with_config("pkg-config", ("pkg-config" unless CROSS_COMPILING))) &&
- find_executable0(pkgconfig) && pkgconfig) and
- system("#{$PKGCONFIG} --exists #{pkg}")
- # default to pkg-config command
- get = proc {|opt| `#{$PKGCONFIG} --#{opt} #{pkg}`.chomp}
- elsif find_executable0(pkgconfig = "#{pkg}-config")
- # default to package specific config command, as a last resort.
- get = proc {|opt| `#{pkgconfig} --#{opt}`.chomp}
- end
- if get
- cflags = get['cflags']
- ldflags = get['libs']
- libs = get['libs-only-l']
- ldflags = (Shellwords.shellwords(ldflags) - Shellwords.shellwords(libs)).quote.join(" ")
- $CFLAGS += " " << cflags
- $LDFLAGS += " " << ldflags
- $libs += " " << libs
- Logging::message "package configuration for %s\n", pkg
- Logging::message "cflags: %s\nldflags: %s\nlibs: %s\n\n",
- cflags, ldflags, libs
- [cflags, ldflags, libs]
- else
- Logging::message "package configuration for %s is not found\n", pkg
- nil
- end
-end
-
-def with_destdir(dir)
- dir = dir.sub($dest_prefix_pattern, '')
- /\A\$[\(\{]/ =~ dir ? dir : "$(DESTDIR)"+dir
-end
-
-# Converts forward slashes to backslashes. Aimed at MS Windows.
-#
-# Internal use only.
-#
-def winsep(s)
- s.tr('/', '\\')
-end
-
-# Converts native path to format acceptable in Makefile
-#
-# Internal use only.
-#
-if !CROSS_COMPILING
- case CONFIG['build_os']
- when 'mingw32'
- def mkintpath(path)
- # mingw uses make from msys and it needs special care
- # converts from C:\some\path to /C/some/path
- path = path.dup
- path.tr!('\\', '/')
- path.sub!(/\A([A-Za-z]):(?=\/)/, '/\1')
- path
- end
- end
-end
-unless defined?(mkintpath)
- def mkintpath(path)
- path
- end
-end
-
-def configuration(srcdir)
- mk = []
- vpath = $VPATH.dup
- if !CROSS_COMPILING
- case CONFIG['build_os']
- when 'cygwin'
- if CONFIG['target_os'] != 'cygwin'
- vpath = vpath.map {|p| p.sub(/.*/, '$(shell cygpath -u \&)')}
- end
- end
- end
- CONFIG["hdrdir"] ||= $hdrdir
- mk << %{
-SHELL = /bin/sh
-
-# V=0 quiet, V=1 verbose. other values don't work.
-V = 0
-Q1 = $(V:1=)
-Q = $(Q1:0=@)
-n=$(NULLCMD)
-ECHO1 = $(V:1=@$n)
-ECHO = $(ECHO1:0=@echo)
-
-#### Start of system configuration section. ####
-#{"top_srcdir = " + $top_srcdir.sub(%r"\A#{Regexp.quote($topdir)}/", "$(topdir)/") if $extmk}
-srcdir = #{srcdir.gsub(/\$\((srcdir)\)|\$\{(srcdir)\}/) {mkintpath(CONFIG[$1||$2])}.quote}
-topdir = #{mkintpath($extmk ? CONFIG["topdir"] : $topdir).quote}
-hdrdir = #{mkintpath(CONFIG["hdrdir"]).quote}
-arch_hdrdir = #{$arch_hdrdir.quote}
-VPATH = #{vpath.join(CONFIG['PATH_SEPARATOR'])}
-}
- if $extmk
- mk << "RUBYLIB =\n""RUBYOPT = -\n"
- end
- if destdir = CONFIG["prefix"][$dest_prefix_pattern, 1]
- mk << "\nDESTDIR = #{destdir}\n"
- end
- CONFIG.each do |key, var|
- next unless /prefix$/ =~ key
- mk << "#{key} = #{with_destdir(var)}\n"
- end
- CONFIG.each do |key, var|
- next if /^abs_/ =~ key
- next if /^(?:src|top|hdr)dir$/ =~ key
- next unless /dir$/ =~ key
- mk << "#{key} = #{with_destdir(var)}\n"
- end
- if !$extmk and !$configure_args.has_key?('--ruby') and
- sep = config_string('BUILD_FILE_SEPARATOR')
- sep = ":/=#{sep}"
- else
- sep = ""
- end
- possible_command = (proc {|s| s if /top_srcdir/ !~ s} unless $extmk)
- extconf_h = $extconf_h ? "-DRUBY_EXTCONF_H=\\\"$(RUBY_EXTCONF_H)\\\" " : $defs.join(" ") << " "
- mk << %{
-NULLCMD = #{CONFIG['NULLCMD']}
-
-CC = #{CONFIG['CC']}
-CXX = #{CONFIG['CXX']}
-LIBRUBY = #{CONFIG['LIBRUBY']}
-LIBRUBY_A = #{CONFIG['LIBRUBY_A']}
-LIBRUBYARG_SHARED = #$LIBRUBYARG_SHARED
-LIBRUBYARG_STATIC = #$LIBRUBYARG_STATIC
-empty =
-OUTFLAG = #{OUTFLAG}$(empty)
-COUTFLAG = #{COUTFLAG}$(empty)
-
-RUBY_EXTCONF_H = #{$extconf_h}
-cflags = #{CONFIG['cflags']}
-optflags = #{CONFIG['optflags']}
-debugflags = #{CONFIG['debugflags']}
-warnflags = #{$warnflags}
-CFLAGS = #{$static ? '' : CONFIG['CCDLFLAGS']} #$CFLAGS $(ARCH_FLAG)
-INCFLAGS = -I. #$INCFLAGS
-DEFS = #{CONFIG['DEFS']}
-CPPFLAGS = #{extconf_h}#{$CPPFLAGS}
-CXXFLAGS = $(CFLAGS) #{CONFIG['CXXFLAGS']}
-ldflags = #{$LDFLAGS}
-dldflags = #{$DLDFLAGS} #{CONFIG['EXTDLDFLAGS']}
-ARCH_FLAG = #{$ARCH_FLAG}
-DLDFLAGS = $(ldflags) $(dldflags) $(ARCH_FLAG)
-LDSHARED = #{CONFIG['LDSHARED']}
-LDSHAREDXX = #{config_string('LDSHAREDXX') || '$(LDSHARED)'}
-AR = #{CONFIG['AR']}
-EXEEXT = #{CONFIG['EXEEXT']}
-
-RUBY_BASE_NAME = #{CONFIG['RUBY_BASE_NAME']}
-RUBY_INSTALL_NAME = #{CONFIG['RUBY_INSTALL_NAME']}
-RUBY_SO_NAME = #{CONFIG['RUBY_SO_NAME']}
-arch = #{CONFIG['arch']}
-sitearch = #{CONFIG['sitearch']}
-ruby_version = #{RbConfig::CONFIG['ruby_version']}
-ruby = #{$ruby}
-RUBY = $(ruby#{sep})
-RM = #{config_string('RM', &possible_command) || '$(RUBY) -run -e rm -- -f'}
-RM_RF = #{'$(RUBY) -run -e rm -- -rf'}
-RMDIRS = #{config_string('RMDIRS', &possible_command) || '$(RUBY) -run -e rmdir -- -p'}
-MAKEDIRS = #{config_string('MAKEDIRS', &possible_command) || '@$(RUBY) -run -e mkdir -- -p'}
-INSTALL = #{config_string('INSTALL', &possible_command) || '@$(RUBY) -run -e install -- -vp'}
-INSTALL_PROG = #{config_string('INSTALL_PROG') || '$(INSTALL) -m 0755'}
-INSTALL_DATA = #{config_string('INSTALL_DATA') || '$(INSTALL) -m 0644'}
-COPY = #{config_string('CP', &possible_command) || '@$(RUBY) -run -e cp -- -v'}
-TOUCH = exit >
-
-#### End of system configuration section. ####
-
-preload = #{defined?($preload) && $preload ? $preload.join(' ') : ''}
-}
- if $nmake == ?b
- mk.each do |x|
- x.gsub!(/^(MAKEDIRS|INSTALL_(?:PROG|DATA))+\s*=.*\n/) do
- "!ifndef " + $1 + "\n" +
- $& +
- "!endif\n"
- end
- end
- end
- mk
-end
-
-def timestamp_file(name)
- name = name.gsub(/(\$[({]|[})])|(\/+)|[^-.\w]+/) {$1 ? "" : $2 ? ".-." : "_"}
- "./.#{name}.time"
-end
-# :startdoc:
-
-# creates a stub Makefile.
-#
-def dummy_makefile(srcdir)
- configuration(srcdir) << <<RULES << CLEANINGS
-CLEANFILES = #{$cleanfiles.join(' ')}
-DISTCLEANFILES = #{$distcleanfiles.join(' ')}
-
-all install static install-so install-rb: Makefile
-.PHONY: all install static install-so install-rb
-.PHONY: clean clean-so clean-rb
-
-RULES
-end
-
-# Processes the data contents of the "depend" file.
-# Each line of this file is expected to be a file name.
-#
-# Returns the output of findings, in Makefile format.
-#
-def depend_rules(depend)
- suffixes = []
- depout = []
- cont = implicit = nil
- impconv = proc do
- COMPILE_RULES.each {|rule| depout << (rule % implicit[0]) << implicit[1]}
- implicit = nil
- end
- ruleconv = proc do |line|
- if implicit
- if /\A\t/ =~ line
- implicit[1] << line
- next
- else
- impconv[]
- end
- end
- if m = /\A\.(\w+)\.(\w+)(?:\s*:)/.match(line)
- suffixes << m[1] << m[2]
- implicit = [[m[1], m[2]], [m.post_match]]
- next
- elsif RULE_SUBST and /\A(?!\s*\w+\s*=)[$\w][^#]*:/ =~ line
- line.gsub!(%r"(\s)(?!\.)([^$(){}+=:\s\/\\,]+)(?=\s|\z)") {$1 + RULE_SUBST % $2}
- end
- depout << line
- end
- depend.each_line do |line|
- line.gsub!(/\.o\b/, ".#{$OBJEXT}")
- line.gsub!(/\$\((?:hdr|top)dir\)\/config.h/, $config_h)
- line.gsub!(%r"\$\(hdrdir\)/(?!ruby(?![^:;/\s]))(?=[-\w]+\.h)", '\&ruby/')
- if $nmake && /\A\s*\$\(RM|COPY\)/ =~ line
- line.gsub!(%r"[-\w\./]{2,}"){$&.tr("/", "\\")}
- line.gsub!(/(\$\((?!RM|COPY)[^:)]+)(?=\))/, '\1:/=\\')
- end
- if /(?:^|[^\\])(?:\\\\)*\\$/ =~ line
- (cont ||= []) << line
- next
- elsif cont
- line = (cont << line).join
- cont = nil
- end
- ruleconv.call(line)
- end
- if cont
- ruleconv.call(cont.join)
- elsif implicit
- impconv.call
- end
- unless suffixes.empty?
- depout.unshift(".SUFFIXES: ." + suffixes.uniq.join(" .") + "\n\n")
- end
- depout.unshift("$(OBJS): $(RUBY_EXTCONF_H)\n\n") if $extconf_h
- depout.flatten!
- depout
-end
-
-# Generates the Makefile for your extension, passing along any options and
-# preprocessor constants that you may have generated through other methods.
-#
-# The +target+ name should correspond the name of the global function name
-# defined within your C extension, minus the 'Init_'. For example, if your
-# C extension is defined as 'Init_foo', then your target would simply be 'foo'.
-#
-# If any '/' characters are present in the target name, only the last name
-# is interpreted as the target name, and the rest are considered toplevel
-# directory names, and the generated Makefile will be altered accordingly to
-# follow that directory structure.
-#
-# For example, if you pass 'test/foo' as a target name, your extension will
-# be installed under the 'test' directory. This means that in order to
-# load the file within a Ruby program later, that directory structure will
-# have to be followed, e.g. "require 'test/foo'".
-#
-# The +srcprefix+ should be used when your source files are not in the same
-# directory as your build script. This will not only eliminate the need for
-# you to manually copy the source files into the same directory as your build
-# script, but it also sets the proper +target_prefix+ in the generated
-# Makefile.
-#
-# Setting the +target_prefix+ will, in turn, install the generated binary in
-# a directory under your RbConfig::CONFIG['sitearchdir'] that mimics your local
-# filesystem when you run 'make install'.
-#
-# For example, given the following file tree:
-#
-# ext/
-# extconf.rb
-# test/
-# foo.c
-#
-# And given the following code:
-#
-# create_makefile('test/foo', 'test')
-#
-# That will set the +target_prefix+ in the generated Makefile to 'test'. That,
-# in turn, will create the following file tree when installed via the
-# 'make install' command:
-#
-# /path/to/ruby/sitearchdir/test/foo.so
-#
-# It is recommended that you use this approach to generate your makefiles,
-# instead of copying files around manually, because some third party
-# libraries may depend on the +target_prefix+ being set properly.
-#
-# The +srcprefix+ argument can be used to override the default source
-# directory, i.e. the current directory . It is included as part of the VPATH
-# and added to the list of INCFLAGS.
-#
-def create_makefile(target, srcprefix = nil)
- $target = target
- libpath = $DEFLIBPATH|$LIBPATH
- message "creating Makefile\n"
- rm_f "conftest*"
- if CONFIG["DLEXT"] == $OBJEXT
- for lib in libs = $libs.split
- lib.sub!(/-l(.*)/, %%"lib\\1.#{$LIBEXT}"%)
- end
- $defs.push(format("-DEXTLIB='%s'", libs.join(",")))
- end
-
- if target.include?('/')
- target_prefix, target = File.split(target)
- target_prefix[0,0] = '/'
- else
- target_prefix = ""
- end
-
- srcprefix ||= "$(srcdir)/#{srcprefix}".chomp('/')
- RbConfig.expand(srcdir = srcprefix.dup)
-
- ext = ".#{$OBJEXT}"
- if not $objs
- srcs = $srcs || Dir[File.join(srcdir, "*.{#{SRC_EXT.join(%q{,})}}")]
- objs = srcs.inject(Hash.new {[]}) {|h, f| h[File.basename(f, ".*") << ext] <<= f; h}
- $objs = objs.keys
- unless objs.delete_if {|b, f| f.size == 1}.empty?
- dups = objs.sort.map {|b, f|
- "#{b[/.*\./]}{#{f.collect {|n| n[/([^.]+)\z/]}.join(',')}}"
- }
- abort "source files duplication - #{dups.join(", ")}"
- end
- else
- $objs.collect! {|o| File.basename(o, ".*") << ext} unless $OBJEXT == "o"
- srcs = $srcs || $objs.collect {|o| o.chomp(ext) << ".c"}
- end
- $srcs = srcs
-
- target = nil if $objs.empty?
-
- if target and EXPORT_PREFIX
- if File.exist?(File.join(srcdir, target + '.def'))
- deffile = "$(srcdir)/$(TARGET).def"
- unless EXPORT_PREFIX.empty?
- makedef = %{-pe "$_.sub!(/^(?=\\w)/,'#{EXPORT_PREFIX}') unless 1../^EXPORTS$/i"}
- end
- else
- makedef = %{-e "puts 'EXPORTS', '$(TARGET_ENTRY)'"}
- end
- if makedef
- $cleanfiles << '$(DEFFILE)'
- origdef = deffile
- deffile = "$(TARGET)-$(arch).def"
- end
- end
- origdef ||= ''
-
- if $extout and $INSTALLFILES
- $cleanfiles.concat($INSTALLFILES.collect {|files, dir|File.join(dir, files.sub(/\A\.\//, ''))})
- $distcleandirs.concat($INSTALLFILES.collect {|files, dir| dir})
- end
-
- if $extmk and not $extconf_h
- create_header
- end
-
- libpath = libpathflag(libpath)
-
- dllib = target ? "$(TARGET).#{CONFIG['DLEXT']}" : ""
- staticlib = target ? "$(TARGET).#$LIBEXT" : ""
- mfile = open("Makefile", "wb")
- conf = configuration(srcprefix)
- conf = yield(conf) if block_given?
- mfile.puts(conf)
- mfile.print "
-libpath = #{($DEFLIBPATH|$LIBPATH).join(" ")}
-LIBPATH = #{libpath}
-DEFFILE = #{deffile}
-
-CLEANFILES = #{$cleanfiles.join(' ')}
-DISTCLEANFILES = #{$distcleanfiles.join(' ')}
-DISTCLEANDIRS = #{$distcleandirs.join(' ')}
-
-extout = #{$extout && $extout.quote}
-extout_prefix = #{$extout_prefix}
-target_prefix = #{target_prefix}
-LOCAL_LIBS = #{$LOCAL_LIBS}
-LIBS = #{$LIBRUBYARG} #{$libs} #{$LIBS}
-SRCS = #{srcs.collect(&File.method(:basename)).join(' ')}
-OBJS = #{$objs.join(" ")}
-TARGET = #{target}
-TARGET_NAME = #{target && target[/\A\w+/]}
-TARGET_ENTRY = #{EXPORT_PREFIX || ''}Init_$(TARGET_NAME)
-DLLIB = #{dllib}
-EXTSTATIC = #{$static || ""}
-STATIC_LIB = #{staticlib unless $static.nil?}
-#{!$extout && defined?($installed_list) ? "INSTALLED_LIST = #{$installed_list}\n" : ""}
-" #"
- # TODO: fixme
- install_dirs.each {|d| mfile.print("%-14s= %s\n" % d) if /^[[:upper:]]/ =~ d[0]}
- n = ($extout ? '$(RUBYARCHDIR)/' : '') + '$(TARGET)'
- mfile.print "
-TARGET_SO = #{($extout ? '$(RUBYARCHDIR)/' : '')}$(DLLIB)
-CLEANLIBS = #{n}.#{CONFIG['DLEXT']} #{config_string('cleanlibs') {|t| t.gsub(/\$\*/) {n}}}
-CLEANOBJS = *.#{$OBJEXT} #{config_string('cleanobjs') {|t| t.gsub(/\$\*/, "$(TARGET)#{deffile ? '-$(arch)': ''}")} if target} *.bak
-
-all: #{$extout ? "install" : target ? "$(DLLIB)" : "Makefile"}
-static: $(STATIC_LIB)#{$extout ? " install-rb" : ""}
-.PHONY: all install static install-so install-rb
-.PHONY: clean clean-so clean-rb
-"
- mfile.print CLEANINGS
- fsep = config_string('BUILD_FILE_SEPARATOR') {|s| s unless s == "/"}
- if fsep
- sep = ":/=#{fsep}"
- fseprepl = proc {|s|
- s = s.gsub("/", fsep)
- s = s.gsub(/(\$\(\w+)(\))/) {$1+sep+$2}
- s = s.gsub(/(\$\{\w+)(\})/) {$1+sep+$2}
- }
- rsep = ":#{fsep}=/"
- else
- fseprepl = proc {|s| s}
- sep = ""
- rsep = ""
- end
- dirs = []
- mfile.print "install: install-so install-rb\n\n"
- sodir = (dir = "$(RUBYARCHDIR)").dup
- mfile.print("install-so: ")
- if target
- f = "$(DLLIB)"
- dest = "#{dir}/#{f}"
- mfile.puts dest
- if $extout
- mfile.print "clean-so::\n"
- mfile.print "\t-$(Q)$(RM) #{fseprepl[dest]}\n"
- mfile.print "\t-$(Q)$(RMDIRS) #{fseprepl[dir]}#{$ignore_error}\n"
- else
- mfile.print "#{dest}: #{f}\n\t-$(Q)$(MAKEDIRS) $(@D#{sep})\n"
- mfile.print "\t$(INSTALL_PROG) #{fseprepl[f]} $(@D#{sep})\n"
- if defined?($installed_list)
- mfile.print "\t@echo #{dir}/#{File.basename(f)}>>$(INSTALLED_LIST)\n"
- end
- end
- mfile.print "clean-static::\n"
- mfile.print "\t-$(Q)$(RM) $(STATIC_LIB)\n"
- else
- mfile.puts "Makefile"
- end
- mfile.print("install-rb: pre-install-rb install-rb-default\n")
- mfile.print("install-rb-default: pre-install-rb-default\n")
- mfile.print("pre-install-rb: Makefile\n")
- mfile.print("pre-install-rb-default: Makefile\n")
- for sfx, i in [["-default", [["lib/**/*.rb", "$(RUBYLIBDIR)", "lib"]]], ["", $INSTALLFILES]]
- files = install_files(mfile, i, nil, srcprefix) or next
- for dir, *files in files
- unless dirs.include?(dir)
- dirs << dir
- mfile.print "pre-install-rb#{sfx}: #{timestamp_file(dir)}\n"
- end
- for f in files
- dest = "#{dir}/#{File.basename(f)}"
- mfile.print("install-rb#{sfx}: #{dest} #{dir}\n")
- mfile.print("#{dest}: #{f}\n")
- mfile.print("\t$(Q) $(#{$extout ? 'COPY' : 'INSTALL_DATA'}) #{f} $(@D#{sep})\n")
- if defined?($installed_list) and !$extout
- mfile.print("\t@echo #{dest}>>$(INSTALLED_LIST)\n")
- end
- if $extout
- mfile.print("clean-rb#{sfx}::\n")
- mfile.print("\t@-$(RM) #{fseprepl[dest]}\n")
- end
- end
- end
- mfile.print "pre-install-rb#{sfx}:\n"
- mfile.print("\t$(ECHO) installing#{sfx.sub(/^-/, " ")} #{target} libraries\n")
- if $extout
- dirs.uniq!
- unless dirs.empty?
- mfile.print("clean-rb#{sfx}::\n")
- for dir in dirs.sort_by {|d| -d.count('/')}
- mfile.print("\t@-$(RMDIRS) #{fseprepl[dir]}#{$ignore_error}\n")
- end
- end
- end
- end
- dirs.unshift(sodir) if target and !dirs.include?(sodir)
- dirs.each do |d|
- t = timestamp_file(d)
- mfile.print "#{t}:\n\t$(Q) $(MAKEDIRS) #{d}\n\t$(Q) $(TOUCH) $@\n"
- end
-
- mfile.print <<-SITEINSTALL
-
-site-install: site-install-so site-install-rb
-site-install-so: install-so
-site-install-rb: install-rb
-
- SITEINSTALL
-
- return unless target
-
- mfile.puts SRC_EXT.collect {|e| ".path.#{e} = $(VPATH)"} if $nmake == ?b
- mfile.print ".SUFFIXES: .#{SRC_EXT.join(' .')} .#{$OBJEXT}\n"
- mfile.print "\n"
-
- compile_command = "\n\t$(ECHO) compiling $(<#{rsep})\n\t$(Q) %s\n\n"
- CXX_EXT.each do |e|
- COMPILE_RULES.each do |rule|
- mfile.printf(rule, e, $OBJEXT)
- mfile.printf(compile_command, COMPILE_CXX)
- end
- end
- C_EXT.each do |e|
- COMPILE_RULES.each do |rule|
- mfile.printf(rule, e, $OBJEXT)
- mfile.printf(compile_command, COMPILE_C)
- end
- end
-
- mfile.print "$(RUBYARCHDIR)/" if $extout
- mfile.print "$(DLLIB): "
- mfile.print "$(DEFFILE) " if makedef
- mfile.print "$(OBJS) Makefile"
- mfile.print " #{timestamp_file('$(RUBYARCHDIR)')}" if $extout
- mfile.print "\n"
- mfile.print "\t$(ECHO) linking shared-object #{target_prefix.sub(/\A\/(.*)/, '\1/')}$(DLLIB)\n"
- mfile.print "\t-$(Q)$(RM) $(@#{sep})\n"
- link_so = LINK_SO.gsub(/^/, "\t$(Q) ")
- if srcs.any?(&%r"\.(?:#{CXX_EXT.join('|')})\z".method(:===))
- link_so = link_so.sub(/\bLDSHARED\b/, '\&XX')
- end
- mfile.print link_so, "\n\n"
- unless $static.nil?
- mfile.print "$(STATIC_LIB): $(OBJS)\n\t@-$(RM) $(@#{sep})\n\t"
- mfile.print "$(ECHO) linking static-library $(@#{rsep})\n\t$(Q) "
- mfile.print "$(AR) #{config_string('ARFLAGS') || 'cru '}$@ $(OBJS)"
- config_string('RANLIB') do |ranlib|
- mfile.print "\n\t@-#{ranlib} $(DLLIB) 2> /dev/null || true"
- end
- end
- mfile.print "\n\n"
- if makedef
- mfile.print "$(DEFFILE): #{origdef}\n"
- mfile.print "\t$(ECHO) generating $(@#{rsep})\n"
- mfile.print "\t$(Q) $(RUBY) #{makedef} #{origdef} > $@\n\n"
- end
-
- depend = File.join(srcdir, "depend")
- if File.exist?(depend)
- mfile.print("###\n", *depend_rules(File.read(depend)))
- else
- headers = %w[$(hdrdir)/ruby.h $(hdrdir)/ruby/defines.h]
- if RULE_SUBST
- headers.each {|h| h.sub!(/.*/, &RULE_SUBST.method(:%))}
- end
- headers << $config_h
- headers << '$(RUBY_EXTCONF_H)' if $extconf_h
- mfile.print "$(OBJS): ", headers.join(' '), "\n"
- end
-
- $makefile_created = true
-ensure
- mfile.close if mfile
-end
-
-# :stopdoc:
-
-def init_mkmf(config = CONFIG, rbconfig = RbConfig::CONFIG)
- $makefile_created = false
- $arg_config = []
- $enable_shared = config['ENABLE_SHARED'] == 'yes'
- $defs = []
- $extconf_h = nil
- if $warnflags = CONFIG['warnflags'] and CONFIG['GCC'] == 'yes'
- # turn warnings into errors only for bundled extensions.
- config['warnflags'] = $warnflags.gsub(/(\A|\s)-Werror[-=]/, '\1-W')
- RbConfig.expand(rbconfig['warnflags'] = config['warnflags'].dup)
- config.each do |key, val|
- RbConfig.expand(rbconfig[key] = val.dup) if /warnflags/ =~ val
- end
- $warnflags = config['warnflags'] unless $extmk
- end
- $CFLAGS = with_config("cflags", arg_config("CFLAGS", config["CFLAGS"])).dup
- $ARCH_FLAG = with_config("arch_flag", arg_config("ARCH_FLAG", config["ARCH_FLAG"])).dup
- $CPPFLAGS = with_config("cppflags", arg_config("CPPFLAGS", config["CPPFLAGS"])).dup
- $LDFLAGS = with_config("ldflags", arg_config("LDFLAGS", config["LDFLAGS"])).dup
- $INCFLAGS = "-I$(arch_hdrdir)"
- $INCFLAGS << " -I$(hdrdir)/ruby/backward" unless $extmk
- $INCFLAGS << " -I$(hdrdir) -I$(srcdir)"
- $DLDFLAGS = with_config("dldflags", arg_config("DLDFLAGS", config["DLDFLAGS"])).dup
- $LIBEXT = config['LIBEXT'].dup
- $OBJEXT = config["OBJEXT"].dup
- $LIBS = "#{config['LIBS']} #{config['DLDLIBS']}"
- $LIBRUBYARG = ""
- $LIBRUBYARG_STATIC = config['LIBRUBYARG_STATIC']
- $LIBRUBYARG_SHARED = config['LIBRUBYARG_SHARED']
- $DEFLIBPATH = [$extmk ? "$(topdir)" : "$(libdir)"]
- $DEFLIBPATH.unshift(".")
- $LIBPATH = []
- $INSTALLFILES = []
- $NONINSTALLFILES = [/~\z/, /\A#.*#\z/, /\A\.#/, /\.bak\z/i, /\.orig\z/, /\.rej\z/, /\.l[ao]\z/, /\.o\z/]
- $VPATH = %w[$(srcdir) $(arch_hdrdir)/ruby $(hdrdir)/ruby]
-
- $objs = nil
- $srcs = nil
- $libs = ""
- if $enable_shared or RbConfig.expand(config["LIBRUBY"].dup) != RbConfig.expand(config["LIBRUBY_A"].dup)
- $LIBRUBYARG = config['LIBRUBYARG']
- end
-
- $LOCAL_LIBS = ""
-
- $cleanfiles = config_string('CLEANFILES') {|s| Shellwords.shellwords(s)} || []
- $cleanfiles << "mkmf.log"
- $distcleanfiles = config_string('DISTCLEANFILES') {|s| Shellwords.shellwords(s)} || []
- $distcleandirs = config_string('DISTCLEANDIRS') {|s| Shellwords.shellwords(s)} || []
-
- $extout ||= nil
- $extout_prefix ||= nil
-
- @libdir_basename = config["libdir"] && config["libdir"][/\A\$\(exec_prefix\)\/(.*)/, 1] or "lib"
-
- $arg_config.clear
- dir_config("opt")
-end
-
-FailedMessage = <<MESSAGE
-Could not create Makefile due to some reason, probably lack of
-necessary libraries and/or headers. Check the mkmf.log file for more
-details. You may need configuration options.
-
-Provided configuration options:
-MESSAGE
-
-# Returns whether or not the Makefile was successfully generated. If not,
-# the script will abort with an error message.
-#
-# Internal use only.
-#
-def mkmf_failed(path)
- unless $makefile_created or File.exist?("Makefile")
- opts = $arg_config.collect {|t, n| "\t#{t}#{n ? "=#{n}" : ""}\n"}
- abort "*** #{path} failed ***\n" + FailedMessage + opts.join
- end
-end
-
-def MAIN_DOES_NOTHING(*refs)
- src = MAIN_DOES_NOTHING
- unless refs.empty?
- src = src.sub(/\{/) do
- $& +
- "\n if (argc > 1000000) {\n" +
- refs.map {|n|" printf(\"%p\", &#{n});\n"}.join("") +
- " }\n"
- end
- end
- src
-end
-
-# :startdoc:
-
-init_mkmf
-
-$make = with_config("make-prog", ENV["MAKE"] || "make")
-make, = Shellwords.shellwords($make)
-$nmake = nil
-case
-when $mswin
- $nmake = ?m if /nmake/i =~ make
-when $bccwin
- $nmake = ?b if /Borland/i =~ `#{make} -h`
-end
-$ignore_error = $nmake ? '' : ' 2> /dev/null || true'
-
-RbConfig::CONFIG["srcdir"] = CONFIG["srcdir"] =
- $srcdir = arg_config("--srcdir", File.dirname($0))
-$configure_args["--topsrcdir"] ||= $srcdir
-if $curdir = arg_config("--curdir")
- RbConfig.expand(curdir = $curdir.dup)
-else
- curdir = $curdir = "."
-end
-unless File.expand_path(RbConfig::CONFIG["topdir"]) == File.expand_path(curdir)
- CONFIG["topdir"] = $curdir
- RbConfig::CONFIG["topdir"] = curdir
-end
-$configure_args["--topdir"] ||= $curdir
-$ruby = arg_config("--ruby", File.join(RbConfig::CONFIG["bindir"], CONFIG["ruby_install_name"]))
-
-split = Shellwords.method(:shellwords).to_proc
-
-EXPORT_PREFIX = config_string('EXPORT_PREFIX') {|s| s.strip}
-
-hdr = ['#include "ruby.h"' "\n"]
-config_string('COMMON_MACROS') do |s|
- Shellwords.shellwords(s).each do |w|
- w, v = w.split(/=/, 2)
- hdr << "#ifndef #{w}"
- hdr << "#define #{[w, v].compact.join(" ")}"
- hdr << "#endif /* #{w} */"
- end
-end
-config_string('COMMON_HEADERS') do |s|
- Shellwords.shellwords(s).each {|w| hdr << "#include <#{w}>"}
-end
-COMMON_HEADERS = hdr.join("\n")
-COMMON_LIBS = config_string('COMMON_LIBS', &split) || []
-
-COMPILE_RULES = config_string('COMPILE_RULES', &split) || %w[.%s.%s:]
-RULE_SUBST = config_string('RULE_SUBST')
-COMPILE_C = config_string('COMPILE_C') || '$(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -c $<'
-COMPILE_CXX = config_string('COMPILE_CXX') || '$(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $<'
-TRY_LINK = config_string('TRY_LINK') ||
- "$(CC) #{OUTFLAG}conftest $(INCFLAGS) $(CPPFLAGS) " \
- "$(CFLAGS) $(src) $(LIBPATH) $(LDFLAGS) $(ARCH_FLAG) $(LOCAL_LIBS) $(LIBS)"
-LINK_SO = config_string('LINK_SO') ||
- if CONFIG["DLEXT"] == $OBJEXT
- "ld $(DLDFLAGS) -r -o $@ $(OBJS)\n"
- else
- "$(LDSHARED) #{OUTFLAG}$@ $(OBJS) " \
- "$(LIBPATH) $(DLDFLAGS) $(LOCAL_LIBS) $(LIBS)"
- end
-LIBPATHFLAG = config_string('LIBPATHFLAG') || ' -L"%s"'
-RPATHFLAG = config_string('RPATHFLAG') || ''
-LIBARG = config_string('LIBARG') || '-l%s'
-MAIN_DOES_NOTHING = config_string('MAIN_DOES_NOTHING') || "int main(int argc, char **argv)\n{\n return 0;\n}"
-UNIVERSAL_INTS = config_string('UNIVERSAL_INTS') {|s| Shellwords.shellwords(s)} ||
- %w[int short long long\ long]
-
-sep = config_string('BUILD_FILE_SEPARATOR') {|s| ":/=#{s}" if s != "/"} || ""
-CLEANINGS = "
-clean-static::
-clean-rb-default::
-clean-rb::
-clean-so::
-clean: clean-so clean-static clean-rb-default clean-rb
-\t\t-$(Q)$(RM) $(CLEANLIBS#{sep}) $(CLEANOBJS#{sep}) $(CLEANFILES#{sep}) .*.time
-
-distclean-rb-default::
-distclean-rb::
-distclean-so::
-distclean: clean distclean-so distclean-rb-default distclean-rb
-\t\t@-$(RM) Makefile $(RUBY_EXTCONF_H) conftest.* mkmf.log
-\t\t@-$(RM) core ruby$(EXEEXT) *~ $(DISTCLEANFILES#{sep})
-\t\t@-$(RMDIRS) $(DISTCLEANDIRS#{sep})#{$ignore_error}
-
-realclean: distclean
-"
-
-if not $extmk and /\A(extconf|makefile).rb\z/ =~ File.basename($0)
- END {mkmf_failed($0)}
-end
diff --git a/ruby_1_9_3/lib/monitor.rb b/ruby_1_9_3/lib/monitor.rb
deleted file mode 100644
index 9e26ec1de1..0000000000
--- a/ruby_1_9_3/lib/monitor.rb
+++ /dev/null
@@ -1,300 +0,0 @@
-# = monitor.rb
-#
-# Copyright (C) 2001 Shugo Maeda <shugo@ruby-lang.org>
-#
-# This library is distributed under the terms of the Ruby license.
-# You can freely distribute/modify this library.
-#
-
-require 'thread'
-
-#
-# In concurrent programming, a monitor is an object or module intended to be
-# used safely by more than one thread. The defining characteristic of a
-# monitor is that its methods are executed with mutual exclusion. That is, at
-# each point in time, at most one thread may be executing any of its methods.
-# This mutual exclusion greatly simplifies reasoning about the implementation
-# of monitors compared to reasoning about parallel code that updates a data
-# structure.
-#
-# You can read more about the general principles on the Wikipedia page for
-# Monitors[http://en.wikipedia.org/wiki/Monitor_%28synchronization%29]
-#
-# == Examples
-#
-# === Simple object.extend
-#
-# require 'monitor.rb'
-#
-# buf = []
-# buf.extend(MonitorMixin)
-# empty_cond = buf.new_cond
-#
-# # consumer
-# Thread.start do
-# loop do
-# buf.synchronize do
-# empty_cond.wait_while { buf.empty? }
-# print buf.shift
-# end
-# end
-# end
-#
-# # producer
-# while line = ARGF.gets
-# buf.synchronize do
-# buf.push(line)
-# empty_cond.signal
-# end
-# end
-#
-# The consumer thread waits for the producer thread to push a line to buf
-# while <tt>buf.empty?</tt>. The producer thread (main thread) reads a
-# line from ARGF and pushes it into buf then calls <tt>empty_cond.signal</tt>
-# to notify the consumer thread of new data.
-#
-# === Simple Class include
-#
-# require 'monitor'
-#
-# class SynchronizedArray < Array
-#
-# include MonitorMixin
-#
-# def initialize(*args)
-# super(*args)
-# end
-#
-# alias :old_shift :shift
-# alias :old_unshift :unshift
-#
-# def shift(n=1)
-# self.synchronize do
-# self.old_shift(n)
-# end
-# end
-#
-# def unshift(item)
-# self.synchronize do
-# self.old_unshift(item)
-# end
-# end
-#
-# # other methods ...
-# end
-#
-# +SynchronizedArray+ implements an Array with synchronized access to items.
-# This Class is implemented as subclass of Array which includes the
-# MonitorMixin module.
-#
-module MonitorMixin
- #
- # FIXME: This isn't documented in Nutshell.
- #
- # Since MonitorMixin.new_cond returns a ConditionVariable, and the example
- # above calls while_wait and signal, this class should be documented.
- #
- class ConditionVariable
- class Timeout < Exception; end
-
- #
- # Releases the lock held in the associated monitor and waits; reacquires the lock on wakeup.
- #
- # If +timeout+ is given, this method returns after +timeout+ seconds passed,
- # even if no other thread doesn't signal.
- #
- def wait(timeout = nil)
- @monitor.__send__(:mon_check_owner)
- count = @monitor.__send__(:mon_exit_for_cond)
- begin
- @cond.wait(@monitor.instance_variable_get("@mon_mutex"), timeout)
- return true
- ensure
- @monitor.__send__(:mon_enter_for_cond, count)
- end
- end
-
- #
- # Calls wait repeatedly while the given block yields a truthy value.
- #
- def wait_while
- while yield
- wait
- end
- end
-
- #
- # Calls wait repeatedly until the given block yields a truthy value.
- #
- def wait_until
- until yield
- wait
- end
- end
-
- #
- # Wakes up the first thread in line waiting for this lock.
- #
- def signal
- @monitor.__send__(:mon_check_owner)
- @cond.signal
- end
-
- #
- # Wakes up all threads waiting for this lock.
- #
- def broadcast
- @monitor.__send__(:mon_check_owner)
- @cond.broadcast
- end
-
- private
-
- def initialize(monitor)
- @monitor = monitor
- @cond = ::ConditionVariable.new
- end
- end
-
- def self.extend_object(obj)
- super(obj)
- obj.__send__(:mon_initialize)
- end
-
- #
- # Attempts to enter exclusive section. Returns +false+ if lock fails.
- #
- def mon_try_enter
- if @mon_owner != Thread.current
- unless @mon_mutex.try_lock
- return false
- end
- @mon_owner = Thread.current
- end
- @mon_count += 1
- return true
- end
- # For backward compatibility
- alias try_mon_enter mon_try_enter
-
- #
- # Enters exclusive section.
- #
- def mon_enter
- if @mon_owner != Thread.current
- @mon_mutex.lock
- @mon_owner = Thread.current
- end
- @mon_count += 1
- end
-
- #
- # Leaves exclusive section.
- #
- def mon_exit
- mon_check_owner
- @mon_count -=1
- if @mon_count == 0
- @mon_owner = nil
- @mon_mutex.unlock
- end
- end
-
- #
- # Enters exclusive section and executes the block. Leaves the exclusive
- # section automatically when the block exits. See example under
- # +MonitorMixin+.
- #
- def mon_synchronize
- mon_enter
- begin
- yield
- ensure
- mon_exit
- end
- end
- alias synchronize mon_synchronize
-
- #
- # Creates a new MonitorMixin::ConditionVariable associated with the
- # receiver.
- #
- def new_cond
- return ConditionVariable.new(self)
- end
-
- private
-
- # Use <tt>extend MonitorMixin</tt> or <tt>include MonitorMixin</tt> instead
- # of this constructor. Have look at the examples above to understand how to
- # use this module.
- def initialize(*args)
- super
- mon_initialize
- end
-
- # Initializes the MonitorMixin after being included in a class or when an
- # object has been extended with the MonitorMixin
- def mon_initialize
- @mon_owner = nil
- @mon_count = 0
- @mon_mutex = Mutex.new
- end
-
- def mon_check_owner
- if @mon_owner != Thread.current
- raise ThreadError, "current thread not owner"
- end
- end
-
- def mon_enter_for_cond(count)
- @mon_owner = Thread.current
- @mon_count = count
- end
-
- def mon_exit_for_cond
- count = @mon_count
- @mon_owner = nil
- @mon_count = 0
- return count
- end
-end
-
-# Use the Monitor class when you want to have a lock object for blocks with
-# mutual exclusion.
-#
-# require 'monitor'
-#
-# lock = Monitor.new
-# lock.synchronize do
-# # exclusive access
-# end
-#
-class Monitor
- include MonitorMixin
- alias try_enter try_mon_enter
- alias enter mon_enter
- alias exit mon_exit
-end
-
-
-# Documentation comments:
-# - All documentation comes from Nutshell.
-# - MonitorMixin.new_cond appears in the example, but is not documented in
-# Nutshell.
-# - All the internals (internal modules Accessible and Initializable, class
-# ConditionVariable) appear in RDoc. It might be good to hide them, by
-# making them private, or marking them :nodoc:, etc.
-# - RDoc doesn't recognise aliases, so we have mon_synchronize documented, but
-# not synchronize.
-# - mon_owner is in Nutshell, but appears as an accessor in a separate module
-# here, so is hard/impossible to RDoc. Some other useful accessors
-# (mon_count and some queue stuff) are also in this module, and don't appear
-# directly in the RDoc output.
-# - in short, it may be worth changing the code layout in this file to make the
-# documentation easier
-
-# Local variables:
-# mode: Ruby
-# tab-width: 8
-# End:
diff --git a/ruby_1_9_3/lib/mutex_m.rb b/ruby_1_9_3/lib/mutex_m.rb
deleted file mode 100644
index 722754b8d5..0000000000
--- a/ruby_1_9_3/lib/mutex_m.rb
+++ /dev/null
@@ -1,95 +0,0 @@
-#
-# mutex_m.rb -
-# $Release Version: 3.0$
-# $Revision: 1.7 $
-# Original from mutex.rb
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-# modified by matz
-# patched by akira yamada
-#
-# --
-# Usage:
-# require "mutex_m.rb"
-# obj = Object.new
-# obj.extend Mutex_m
-# ...
-# extended object can be handled like Mutex
-# or
-# class Foo
-# include Mutex_m
-# ...
-# end
-# obj = Foo.new
-# this obj can be handled like Mutex
-#
-
-require 'thread'
-
-module Mutex_m
- def Mutex_m.define_aliases(cl)
- cl.module_eval %q{
- alias locked? mu_locked?
- alias lock mu_lock
- alias unlock mu_unlock
- alias try_lock mu_try_lock
- alias synchronize mu_synchronize
- }
- end
-
- def Mutex_m.append_features(cl)
- super
- define_aliases(cl) unless cl.instance_of?(Module)
- end
-
- def Mutex_m.extend_object(obj)
- super
- obj.mu_extended
- end
-
- def mu_extended
- unless (defined? locked? and
- defined? lock and
- defined? unlock and
- defined? try_lock and
- defined? synchronize)
- Mutex_m.define_aliases(singleton_class)
- end
- mu_initialize
- end
-
- # locking
- def mu_synchronize(&block)
- @_mutex.synchronize(&block)
- end
-
- def mu_locked?
- @_mutex.locked?
- end
-
- def mu_try_lock
- @_mutex.try_lock
- end
-
- def mu_lock
- @_mutex.lock
- end
-
- def mu_unlock
- @_mutex.unlock
- end
-
- def sleep(timeout = nil)
- @_mutex.sleep(timeout)
- end
-
- private
-
- def mu_initialize
- @_mutex = Mutex.new
- end
-
- def initialize(*args)
- mu_initialize
- super
- end
-end
diff --git a/ruby_1_9_3/lib/net/.document b/ruby_1_9_3/lib/net/.document
deleted file mode 100644
index 6332bb9e7e..0000000000
--- a/ruby_1_9_3/lib/net/.document
+++ /dev/null
@@ -1,8 +0,0 @@
-ftp.rb
-http.rb
-https.rb
-imap.rb
-pop.rb
-smtp.rb
-smtps.rb
-telnet.rb
diff --git a/ruby_1_9_3/lib/net/ftp.rb b/ruby_1_9_3/lib/net/ftp.rb
deleted file mode 100644
index 149fc6adc1..0000000000
--- a/ruby_1_9_3/lib/net/ftp.rb
+++ /dev/null
@@ -1,1043 +0,0 @@
-#
-# = 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
- class FTPConnectionError < 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_reader :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
- @sock = NullSocket.new
- @logged_in = false
- if host
- connect(host)
- if user
- login(user, passwd, acct)
- end
- end
- end
-
- # A setter to toggle transfers in binary mode.
- # +newmode+ is either +true+ or +false+
- def binary=(newmode)
- if newmode != @binary
- @binary = newmode
- send_type_command if @logged_in
- end
- end
-
- # Sends a command to destination host, with the current binary sendmode
- # type.
- #
- # If binary mode is +true+, then "TYPE I" (image) is sent, otherwise "TYPE
- # A" (ascii) is sent.
- def send_type_command # :nodoc:
- if @binary
- voidcmd("TYPE I")
- else
- voidcmd("TYPE A")
- end
- end
- private :send_type_command
-
- # Toggles transfers in binary mode and yields to a block.
- # This preserves your current binary send mode, but allows a temporary
- # transaction with binary sendmode of +newmode+.
- #
- # +newmode+ is either +true+ or +false+
- def with_binary(newmode) # :nodoc:
- oldmode = binary
- self.binary = newmode
- begin
- yield
- ensure
- self.binary = oldmode
- end
- end
- private :with_binary
-
- # Obsolete
- def return_code # :nodoc:
- $stderr.puts("warning: Net::FTP#return_code is obsolete and do nothing")
- return "\n"
- end
-
- # Obsolete
- def return_code=(s) # :nodoc:
- $stderr.puts("warning: Net::FTP#return_code= is obsolete and do nothing")
- end
-
- # Contructs a socket with +host+ and +port+.
- #
- # If SOCKSSocket is defined and the environment (ENV) defines
- # SOCKS_SERVER, then a SOCKSSocket is returned, else a TCPSocket is
- # returned.
- def open_socket(host, port) # :nodoc:
- 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
-
- # If string +s+ includes the PASS command (password), then the contents of
- # the password are cleaned from the string using "*"
- def sanitize(s) # :nodoc:
- if s =~ /^PASS /i
- return s[0, 5] + "*" * (s.length - 5)
- else
- return s
- end
- end
- private :sanitize
-
- # Ensures that +line+ has a control return / line feed (CRLF) and writes
- # it to the socket.
- def putline(line) # :nodoc:
- if @debug_mode
- print "put: ", sanitize(line), "\n"
- end
- line = line + CRLF
- @sock.write(line)
- end
- private :putline
-
- # Reads a line from the sock. If EOF, then it will raise EOFError
- def getline # :nodoc:
- 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
-
- # Receive a section of lines until the response code's match.
- def getmultiline # :nodoc:
- 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
-
- # Recieves a response from the destination host.
- #
- # Returns the response code or raises FTPTempError, FTPPermError, or
- # FTPProtoError
- def getresp # :nodoc:
- @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
-
- # Recieves a response.
- #
- # Raises FTPReplyError if the first position of the response code is not
- # equal 2.
- def voidresp # :nodoc:
- 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
-
- # Constructs and send the appropriate PORT (or EPRT) command
- def sendport(host, port) # :nodoc:
- 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
-
- # Constructs a TCPServer socket, and sends it the PORT command
- #
- # Returns the constructed TCPServer socket
- def makeport # :nodoc:
- sock = TCPServer.open(@sock.addr[3], 0)
- port = sock.addr[1]
- host = sock.addr[3]
- sendport(host, port)
- return sock
- end
- private :makeport
-
- # sends the appropriate command to enable a passive connection
- def makepasv # :nodoc:
- 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
-
- # Constructs a connection for transferring data
- def transfercmd(cmd, rest_offset = nil) # :nodoc:
- 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
-
- #
- # 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 = "anonymous@"
- 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
- send_type_command
- @logged_in = true
- 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
- with_binary(true) do
- conn = transfercmd(cmd, rest_offset)
- loop do
- data = conn.read(blocksize)
- break if data == nil
- yield(data)
- end
- conn.close
- voidresp
- end
- 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
- with_binary(false) do
- conn = transfercmd(cmd)
- loop do
- line = conn.gets
- break if line == nil
- yield(line.sub(/\r?\n\z/, ""), !line.match(/\n\z/).nil?)
- end
- conn.close
- voidresp
- end
- 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
- with_binary(true) do
- conn = transfercmd(cmd)
- loop do
- buf = file.read(blocksize)
- break if buf == nil
- conn.write(buf)
- yield(buf) if block
- end
- conn.close
- voidresp
- end
- end
- rescue Errno::EPIPE
- # EPIPE, in this case, means that the data connection was unexpectedly
- # terminated. Rather than just raising EPIPE to the caller, check the
- # response on the control connection. If getresp doesn't raise a more
- # appropriate exception, re-raise the original exception.
- getresp
- raise
- 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
- with_binary(false) do
- 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
- rescue Errno::EPIPE
- # EPIPE, in this case, means that the data connection was unexpectedly
- # terminated. Rather than just raising EPIPE to the caller, check the
- # response on the control connection. If getresp doesn't raise a more
- # appropriate exception, re-raise the original exception.
- getresp
- raise
- end
-
- #
- # Retrieves +remotefile+ in binary mode, storing the result in +localfile+.
- # If +localfile+ is nil, returns retrieved data.
- # If a block is supplied, it is passed the retrieved data in +blocksize+
- # chunks.
- #
- def getbinaryfile(remotefile, localfile = File.basename(remotefile),
- blocksize = DEFAULT_BLOCKSIZE) # :yield: data
- result = nil
- if localfile
- if @resume
- rest_offset = File.size?(localfile)
- f = open(localfile, "a")
- else
- rest_offset = nil
- f = open(localfile, "w")
- end
- elsif !block_given?
- result = ""
- end
- begin
- f.binmode if localfile
- retrbinary("RETR " + remotefile.to_s, blocksize, rest_offset) do |data|
- f.write(data) if localfile
- yield(data) if block_given?
- result.concat(data) if result
- end
- return result
- ensure
- f.close if localfile
- end
- end
-
- #
- # Retrieves +remotefile+ in ASCII (text) mode, storing the result in
- # +localfile+.
- # If +localfile+ is nil, returns retrieved data.
- # If a block is supplied, it is passed the retrieved data one
- # line at a time.
- #
- def gettextfile(remotefile, localfile = File.basename(remotefile)) # :yield: line
- result = nil
- if localfile
- f = open(localfile, "w")
- elsif !block_given?
- result = ""
- end
- begin
- retrlines("RETR " + remotefile) do |line, newline|
- l = newline ? line + "\n" : line
- f.print(l) if localfile
- yield(line, newline) if block_given?
- result.concat(l) if result
- end
- return result
- ensure
- f.close if localfile
- 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
- if @binary
- getbinaryfile(remotefile, localfile, blocksize, &block)
- else
- gettextfile(remotefile, localfile, &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
- if rest_offset
- storbinary("APPE " + remotefile, f, blocksize, rest_offset, &block)
- else
- storbinary("STOR " + remotefile, f, blocksize, rest_offset, &block)
- end
- 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)
- if @binary
- putbinaryfile(localfile, remotefile, blocksize, &block)
- else
- puttextfile(localfile, remotefile, &block)
- end
- end
-
- #
- # Sends the ACCT command.
- #
- # This is a less common FTP command, to send account
- # information if the destination host requires it.
- #
- 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.to_s
- 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)
- with_binary(true) do
- resp = sendcmd("SIZE " + filename)
- if resp[0, 3] != "213"
- raise FTPReplyError, resp
- end
- return resp[3..-1].strip.to_i
- end
- 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.
- #
- # Does nothing except return a response.
- #
- 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
-
- # handler for response code 227
- # (Entering Passive Mode (h1,h2,h3,h4,p1,p2))
- #
- # Returns host and port.
- def parse227(resp) # :nodoc:
- 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
-
- # handler for response code 228
- # (Entering Long Passive Mode)
- #
- # Returns host and port.
- def parse228(resp) # :nodoc:
- 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
-
- # handler for response code 229
- # (Extended Passive Mode Entered)
- #
- # Returns host and port.
- def parse229(resp) # :nodoc:
- 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
-
- # handler for response code 257
- # ("PATHNAME" created)
- #
- # Returns host and port.
- def parse257(resp) # :nodoc:
- 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
-
- # :stopdoc:
- class NullSocket
- def method_missing(mid, *args)
- raise FTPConnectionError, "not connected"
- end
- end
- # :startdoc:
- 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)
diff --git a/ruby_1_9_3/lib/net/http.rb b/ruby_1_9_3/lib/net/http.rb
deleted file mode 100644
index 9e4fe6a120..0000000000
--- a/ruby_1_9_3/lib/net/http.rb
+++ /dev/null
@@ -1,2825 +0,0 @@
-#
-# = net/http.rb
-#
-# Copyright (c) 1999-2007 Yukihiro Matsumoto
-# Copyright (c) 1999-2007 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.
-#
-
-require 'net/protocol'
-require 'uri'
-autoload :OpenSSL, 'openssl'
-
-module Net #:nodoc:
-
- # :stopdoc:
- class HTTPBadResponse < StandardError; end
- class HTTPHeaderSyntaxError < StandardError; end
- # :startdoc:
-
- # == An HTTP client API for Ruby.
- #
- # Net::HTTP provides a rich library which can be used to build HTTP
- # user-agents. For more details about HTTP see
- # [RFC2616](http://www.ietf.org/rfc/rfc2616.txt)
- #
- # Net::HTTP is designed to work closely with URI. URI::HTTP#host,
- # URI::HTTP#port and URI::HTTP#request_uri are designed to work with
- # Net::HTTP.
- #
- # If you are only performing a few GET requests you should try OpenURI.
- #
- # == Simple Examples
- #
- # All examples assume you have loaded Net::HTTP with:
- #
- # require 'net/http'
- #
- # This will also require 'uri' so you don't need to require it separately.
- #
- # The Net::HTTP methods in the following section do not persist
- # connections. They are not recommended if you are performing many HTTP
- # requests.
- #
- # === GET
- #
- # Net::HTTP.get('example.com', '/index.html') # => String
- #
- # === GET by URI
- #
- # uri = URI('http://example.com/index.html?count=10')
- # Net::HTTP.get(uri) # => String
- #
- # === GET with Dynamic Parameters
- #
- # uri = URI('http://example.com/index.html')
- # params = { :limit => 10, :page => 3 }
- # uri.query = URI.encode_www_form(params)
- #
- # res = Net::HTTP.get_response(uri)
- # puts res.body if res.is_a?(Net::HTTPSuccess)
- #
- # === POST
- #
- # uri = URI('http://www.example.com/search.cgi')
- # res = Net::HTTP.post_form(uri, 'q' => 'ruby', 'max' => '50')
- # puts res.body
- #
- # === POST with Multiple Values
- #
- # uri = URI('http://www.example.com/search.cgi')
- # res = Net::HTTP.post_form(uri, 'q' => ['ruby', 'perl'], 'max' => '50')
- # puts res.body
- #
- # == How to use Net::HTTP
- #
- # The following example code can be used as the basis of a HTTP user-agent
- # which can perform a variety of request types using persistent
- # connections.
- #
- # uri = URI('http://example.com/some_path?query=string')
- #
- # Net::HTTP.start(uri.host, uri.port) do |http|
- # request = Net::HTTP::Get.new uri.request_uri
- #
- # response = http.request request # Net::HTTPResponse object
- # end
- #
- # Net::HTTP::start immediately creates a connection to an HTTP server which
- # is kept open for the duration of the block. The connection will remain
- # open for multiple requests in the block if the server indicates it
- # supports persistent connections.
- #
- # The request types Net::HTTP supports are listed below in the section "HTTP
- # Request Classes".
- #
- # If you wish to re-use a connection across multiple HTTP requests without
- # automatically closing it you can use ::new instead of ::start. #request
- # will automatically open a connection to the server if one is not currently
- # open. You can manually close the connection with #finish.
- #
- # === Response Data
- #
- # uri = URI('http://example.com/index.html')
- # res = Net::HTTP.get_response(uri)
- #
- # # Headers
- # res['Set-Cookie'] # => String
- # res.get_fields('set-cookie') # => Array
- # res.to_hash['set-cookie'] # => Array
- # puts "Headers: #{res.to_hash.inspect}"
- #
- # # Status
- # puts res.code # => '200'
- # puts res.message # => 'OK'
- # puts res.class.name # => 'HTTPOK'
- #
- # # Body
- # puts res.body if res.response_body_permitted?
- #
- # === Following Redirection
- #
- # Each Net::HTTPResponse object belongs to a class for its response code.
- #
- # For example, all 2XX responses are instances of a Net::HTTPSuccess
- # subclass, a 3XX response is an instance of a Net::HTTPRedirection
- # subclass and a 200 response is an instance of the Net::HTTPOK class. For
- # details of response classes, see the section "HTTP Response Classes"
- # below.
- #
- # Using a case statement you can handle various types of responses properly:
- #
- # def fetch(uri_str, limit = 10)
- # # You should choose a better exception.
- # raise ArgumentError, 'too many HTTP redirects' if limit == 0
- #
- # response = Net::HTTP.get_response(URI(uri_str))
- #
- # case response
- # when Net::HTTPSuccess then
- # response
- # when Net::HTTPRedirection then
- # location = response['location']
- # warn "redirected to #{location}"
- # fetch(location, limit - 1)
- # else
- # response.value
- # end
- # end
- #
- # print fetch('http://www.ruby-lang.org')
- #
- # === POST
- #
- # A POST can be made using the Net::HTTP::Post request class. This example
- # creates a urlencoded POST body:
- #
- # uri = URI('http://www.example.com/todo.cgi')
- # req = Net::HTTP::Post.new(uri.path)
- # req.set_form_data('from' => '2005-01-01', 'to' => '2005-03-31')
- #
- # res = Net::HTTP.start(uri.hostname, uri.port) do |http|
- # http.request(req)
- # end
- #
- # case res
- # when Net::HTTPSuccess, Net::HTTPRedirection
- # # OK
- # else
- # res.value
- # end
- #
- # At this time Net::HTTP does not support multipart/form-data. To send
- # multipart/form-data use Net::HTTPRequest#body= and
- # Net::HTTPRequest#content_type=:
- #
- # req = Net::HTTP::Post.new(uri.path)
- # req.body = multipart_data
- # req.content_type = 'multipart/form-data'
- #
- # Other requests that can contain a body such as PUT can be created in the
- # same way using the corresponding request class (Net::HTTP::Put).
- #
- # === Setting Headers
- #
- # The following example performs a conditional GET using the
- # If-Modified-Since header. If the files has not been modified since the
- # time in the header a Not Modified response will be returned. See RFC 2616
- # section 9.3 for further details.
- #
- # uri = URI('http://example.com/cached_response')
- # file = File.stat 'cached_response'
- #
- # req = Net::HTTP::Get.new(uri.request_uri)
- # req['If-Modified-Since'] = file.mtime.rfc2822
- #
- # res = Net::HTTP.start(uri.hostname, uri.port) {|http|
- # http.request(req)
- # }
- #
- # open 'cached_response', 'w' do |io|
- # io.write res.body
- # end if res.is_a?(Net::HTTPSuccess)
- #
- # === Basic Authentication
- #
- # Basic authentication is performed according to
- # [RFC2617](http://www.ietf.org/rfc/rfc2617.txt)
- #
- # uri = URI('http://example.com/index.html?key=value')
- #
- # req = Net::HTTP::Get.new(uri.request_uri)
- # req.basic_auth 'user', 'pass'
- #
- # res = Net::HTTP.start(uri.hostname, uri.port) {|http|
- # http.request(req)
- # }
- # puts res.body
- #
- # === Streaming Response Bodies
- #
- # By default Net::HTTP reads an entire response into memory. If you are
- # handling large files or wish to implement a progress bar you can instead
- # stream the body directly to an IO.
- #
- # uri = URI('http://example.com/large_file')
- #
- # Net::HTTP.start(uri.host, uri.port) do |http|
- # request = Net::HTTP::Get.new uri.request_uri
- #
- # http.request request do |response|
- # open 'large_file', 'w' do |io|
- # response.read_body do |chunk|
- # io.write chunk
- # end
- # end
- # end
- # end
- #
- # === HTTPS
- #
- # HTTPS is enabled for an HTTP connection by Net::HTTP#use_ssl=.
- #
- # uri = URI('https://secure.example.com/some_path?query=string')
- #
- # Net::HTTP.start(uri.host, uri.port,
- # :use_ssl => uri.scheme == 'https').start do |http|
- # request = Net::HTTP::Get.new uri.request_uri
- #
- # response = http.request request # Net::HTTPResponse object
- # end
- #
- # In previous versions of ruby you would need to require 'net/https' to use
- # HTTPS. This is no longer true.
- #
- # === Proxies
- #
- # Net::HTTP::Proxy has the same methods as Net::HTTP but its instances always
- # connect via the proxy instead of directly to the given host.
- #
- # 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
- # }
- #
- # Net::HTTP::Proxy returns a Net::HTTP instance when proxy_addr is nil so
- # there is no need for conditional code.
- #
- # See Net::HTTP::Proxy for further details and examples such as proxies that
- # require a username and password.
- #
- # == HTTP Request Classes
- #
- # Here is the 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 and are subclasses of Net::HTTPResponse.
- #
- # HTTPUnknownResponse:: For unhandled HTTP extensions
- # HTTPInformation:: 1xx
- # HTTPContinue:: 100
- # HTTPSwitchProtocol:: 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
- #
- # There is also the Net::HTTPBadResponse exception which is raised when
- # there is a protocol error.
- #
- class HTTP < Protocol
-
- # :stopdoc:
- Revision = %q$Revision$.split[1]
- HTTPVersion = '1.1'
- begin
- require 'zlib'
- require 'stringio' #for our purposes (unpacking gzip) lump these together
- HAVE_ZLIB=true
- rescue LoadError
- HAVE_ZLIB=false
- end
- # :startdoc:
-
- # Turns on net/http 1.2 (ruby 1.8) features.
- # Defaults to ON in ruby 1.8 or later.
- def HTTP.version_1_2
- true
- end
-
- # Returns true if net/http is in version 1.2 mode.
- # Defaults to true.
- def HTTP.version_1_2?
- true
- end
-
- def HTTP.version_1_1? #:nodoc:
- false
- 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
- #
-
- #
- # Gets the body text from the target and outputs it to $stdout. The
- # target can either be specified as
- # (+uri+), or as (+host+, +path+, +port+ = 80); so:
- #
- # Net::HTTP.get_print URI('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
-
- # Sends a GET request to the target and returns the HTTP response
- # as a string. The target can either be specified as
- # (+uri+), or as (+host+, +path+, +port+ = 80); so:
- #
- # print Net::HTTP.get(URI('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
-
- # Sends a GET request to the target and returns the HTTP 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('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.hostname, uri.port).start {|http|
- return http.request_get(uri.request_uri, &block)
- }
- end
- end
-
- # Posts HTML form data to the specified URI object.
- # The form data must be provided as a Hash mapping from String to String.
- # Example:
- #
- # { "cmd" => "search", "q" => "ruby", "max" => "50" }
- #
- # This method also does Basic Authentication iff +url+.user exists.
- # But userinfo for authentication is deprecated (RFC3986).
- # So this feature will be removed.
- #
- # Example:
- #
- # require 'net/http'
- # require 'uri'
- #
- # HTTP.post_form URI('http://www.example.com/search.cgi'),
- # { "q" => "ruby", "max" => "50" }
- #
- def HTTP.post_form(url, params)
- req = Post.new(url.request_uri)
- req.form_data = params
- req.basic_auth url.user, url.password if url.user
- new(url.hostname, 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
-
- # call-seq:
- # HTTP.start(address, port, p_addr, p_port, p_user, p_pass, &block)
- # HTTP.start(address, port=nil, p_addr=nil, p_port=nil, p_user=nil, p_pass=nil, opt, &block)
- #
- # Creates a new Net::HTTP object, then additionally opens the TCP
- # connection and HTTP session.
- #
- # Arguments are the following:
- # _address_ :: hostname or IP address of the server
- # _port_ :: port of the server
- # _p_addr_ :: address of proxy
- # _p_port_ :: port of proxy
- # _p_user_ :: user of proxy
- # _p_pass_ :: pass of proxy
- # _opt_ :: optional hash
- #
- # _opt_ sets following values by its accessor.
- # The keys are ca_file, ca_path, cert, cert_store, ciphers,
- # close_on_empty_response, key, open_timeout, read_timeout, ssl_timeout,
- # ssl_version, use_ssl, verify_callback, verify_depth and verify_mode.
- # If you set :use_ssl as true, you can use https and default value of
- # verify_mode is set as OpenSSL::SSL::VERIFY_PEER.
- #
- # 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
- # using the finish() method.
- def HTTP.start(address, *arg, &block) # :yield: +http+
- arg.pop if opt = Hash.try_convert(arg[-1])
- port, p_addr, p_port, p_user, p_pass = *arg
- port = https_default_port if !port && opt && opt[:use_ssl]
- http = new(address, port, p_addr, p_port, p_user, p_pass)
-
- if opt
- if opt[:use_ssl]
- opt = {verify_mode: OpenSSL::SSL::VERIFY_PEER}.update(opt)
- end
- http.methods.grep(/\A(\w+)=\z/) do |meth|
- key = $1.to_sym
- opt.key?(key) or next
- http.__send__(meth, opt[key])
- end
- end
-
- http.start(&block)
- end
-
- class << HTTP
- alias newobj new
- end
-
- # Creates a new Net::HTTP object without opening a TCP connection or
- # HTTP session.
- # The +address+ should be a DNS hostname or IP address.
- # If +p_addr+ is given, creates a Net::HTTP object with proxy support.
- def HTTP.new(address, port = nil, p_addr = nil, p_port = nil, p_user = nil, p_pass = nil)
- Proxy(p_addr, p_port, p_user, p_pass).newobj(address, port)
- end
-
- # Creates a new Net::HTTP object for the specified server address,
- # without opening the TCP connection or initializing the HTTP session.
- # The +address+ should be a DNS hostname or IP address.
- def initialize(address, port = nil)
- @address = address
- @port = (port || HTTP.default_port)
- @curr_http_version = HTTPVersion
- @no_keepalive_server = false
- @close_on_empty_response = false
- @socket = nil
- @started = false
- @open_timeout = nil
- @read_timeout = 60
- @continue_timeout = nil
- @debug_output = nil
- @use_ssl = false
- @ssl_context = nil
- @enable_post_connection_check = true
- @compression = nil
- @sspi_enabled = false
- if defined?(SSL_ATTRIBUTES)
- SSL_ATTRIBUTES.each do |name|
- instance_variable_set "@#{name}", nil
- end
- end
- end
-
- def inspect
- "#<#{self.class} #{@address}:#{@port} open=#{started?}>"
- end
-
- # *WARNING* This method opens a serious security hole.
- # Never use this method in production code.
- #
- # Sets 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 DNS host name or IP address to connect to.
- attr_reader :address
-
- # The port number to connect to.
- attr_reader :port
-
- # Number of seconds to wait for the connection to open. Any number
- # may be used, including Floats for fractional seconds. If the HTTP
- # object cannot open a connection in this many seconds, it raises a
- # TimeoutError exception. The default value is +nil+.
- attr_accessor :open_timeout
-
- # Number of seconds to wait for one block to be read (via one read(2)
- # call). Any number may be used, including Floats for fractional
- # seconds. If the HTTP object cannot read data in this many seconds,
- # it raises a TimeoutError exception. The default value is 60 seconds.
- attr_reader :read_timeout
-
- # Setter for the read_timeout attribute.
- def read_timeout=(sec)
- @socket.read_timeout = sec if @socket
- @read_timeout = sec
- end
-
- # Seconds to wait for 100 Continue response. If the HTTP object does not
- # receive a response in this many seconds it sends the request body. The
- # default value is +nil+.
- attr_reader :continue_timeout
-
- # Setter for the continue_timeout attribute.
- def continue_timeout=(sec)
- @socket.continue_timeout = sec if @socket
- @continue_timeout = sec
- end
-
- # Returns true if the HTTP session has been started.
- def started?
- @started
- end
-
- alias active? started? #:nodoc: obsolete
-
- attr_accessor :close_on_empty_response
-
- # Returns true if SSL/TLS is being used with HTTP.
- def use_ssl?
- @use_ssl
- end
-
- # 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
- if started? and @use_ssl != flag
- raise IOError, "use_ssl value changed, but session already started"
- end
- @use_ssl = flag
- end
-
- SSL_ATTRIBUTES = %w(
- ssl_version key cert ca_file ca_path cert_store ciphers
- verify_mode verify_callback verify_depth ssl_timeout
- )
-
- # Sets path of a CA certification file in PEM format.
- #
- # The file can contain several CA certificates.
- attr_accessor :ca_file
-
- # Sets path of a CA certification directory containing certifications in
- # PEM format.
- attr_accessor :ca_path
-
- # Sets an OpenSSL::X509::Certificate object as client certificate.
- # (This method is appeared in Michal Rokos's OpenSSL extension).
- attr_accessor :cert
-
- # Sets the X509::Store to verify peer certificate.
- attr_accessor :cert_store
-
- # Sets the available ciphers. See OpenSSL::SSL::SSLContext#ciphers=
- attr_accessor :ciphers
-
- # Sets an OpenSSL::PKey::RSA or OpenSSL::PKey::DSA object.
- # (This method is appeared in Michal Rokos's OpenSSL extension.)
- attr_accessor :key
-
- # Sets the SSL timeout seconds.
- attr_accessor :ssl_timeout
-
- # Sets the SSL version. See OpenSSL::SSL::SSLContext#ssl_version=
- attr_accessor :ssl_version
-
- # Sets the verify callback for the server certification verification.
- attr_accessor :verify_callback
-
- # Sets the maximum depth for the certificate chain verification.
- attr_accessor :verify_depth
-
- # Sets the flags for server the certification verification at beginning of
- # SSL/TLS session.
- #
- # OpenSSL::SSL::VERIFY_NONE or OpenSSL::SSL::VERIFY_PEER are acceptable.
- attr_accessor :verify_mode
-
- # Returns the X.509 certificates the server presented.
- def peer_cert
- if not use_ssl? or not @socket
- return nil
- end
- @socket.io.peer_cert
- end
-
- # Opens a TCP connection and HTTP session.
- #
- # When this method is called with a block, it passes the Net::HTTP
- # object to the block, and closes the TCP connection and HTTP session
- # after the block has been executed.
- #
- # When called with a block, it returns the return value of the
- # block; otherwise, it 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?
- ssl_parameters = Hash.new
- iv_list = instance_variables
- SSL_ATTRIBUTES.each do |name|
- ivname = "@#{name}".intern
- if iv_list.include?(ivname) and
- value = instance_variable_get(ivname)
- ssl_parameters[name] = value
- end
- end
- @ssl_context = OpenSSL::SSL::SSLContext.new
- @ssl_context.set_params(ssl_parameters)
- s = OpenSSL::SSL::SSLSocket.new(s, @ssl_context)
- s.sync_close = true
- end
- @socket = BufferedIO.new(s)
- @socket.read_timeout = @read_timeout
- @socket.continue_timeout = @continue_timeout
- @socket.debug_output = @debug_output
- if use_ssl?
- begin
- 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
- # Server Name Indication (SNI) RFC 3546
- s.hostname = @address if s.respond_to? :hostname=
- timeout(@open_timeout) { s.connect }
- if @ssl_context.verify_mode != OpenSSL::SSL::VERIFY_NONE
- s.post_connection_check(@address)
- end
- rescue => exception
- D "Conn close because of connect error #{exception}"
- @socket.close if @socket and not @socket.closed?
- raise exception
- end
- end
- on_connect
- end
- private :connect
-
- def on_connect
- end
- private :on_connect
-
- # Finishes the HTTP session and closes the TCP connection.
- # Raises IOError if the session has not been 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 which behaves like Net::HTTP, but
- # performs all access via the specified proxy.
- #
- # The arguments are the DNS name or IP address of the proxy host,
- # the port to use to access the proxy, and a username and password
- # if authorization is required to use the proxy.
- #
- # You can replace any use of the Net::HTTP class with use of the
- # proxy class created.
- #
- # If +p_addr+ is nil, this method returns self (a Net::HTTP object).
- #
- # # Example
- # proxy_class = Net::HTTP::Proxy('proxy.example.com', 8080)
- #
- # proxy_class.start('www.ruby-lang.org') {|http|
- # # connecting proxy.foo.org:8080
- # }
- #
- # You may use them to work with authorization-enabled proxies:
- #
- # proxy_host = 'your.proxy.example'
- # proxy_port = 8080
- # proxy_user = 'user'
- # proxy_pass = 'pass'
- #
- # proxy = Net::HTTP::Proxy(proxy_host, proxy_port, proxy_user, proxy_pass)
- # proxy.start('www.example.com') { |http|
- # # always connect to your.proxy.example:8080 using specified username
- # # and password
- # }
- #
- # Note that net/http does not use the HTTP_PROXY environment variable.
- # If you want to use a proxy, you must set it explicitly.
- #
- 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
-
- # Address of proxy host. If Net::HTTP does not use a proxy, nil.
- attr_reader :proxy_address
-
- # Port number of proxy host. If Net::HTTP does not use a proxy, nil.
- attr_reader :proxy_port
-
- # User name for accessing proxy. If Net::HTTP does not use a proxy, nil.
- attr_reader :proxy_user
-
- # User password for accessing proxy. If Net::HTTP does not use a proxy,
- # nil.
- attr_reader :proxy_pass
- end
-
- # True if self is a HTTP proxy class.
- def proxy?
- self.class.proxy_class?
- end
-
- # A convenience method for accessing value of proxy_address from Net::HTTP.
- def proxy_address
- self.class.proxy_address
- end
-
- # A convenience method for accessing value of proxy_port from Net::HTTP.
- def proxy_port
- self.class.proxy_port
- end
-
- # A convenience method for accessing value of proxy_user from Net::HTTP.
- def proxy_user
- self.class.proxy_user
- end
-
- # A convenience method for accessing value of proxy_pass from Net::HTTP.
- 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.
- # +initheader+ must be a Hash like { 'Accept' => '*/*', ... },
- # and it defaults to an empty hash.
- # If +initheader+ doesn't have the key 'accept-encoding', then
- # a value of "gzip;q=1.0,deflate;q=0.6,identity;q=0.3" is used,
- # so that gzip compression is used in preference to deflate
- # compression, which is used in preference to no compression.
- # Ruby doesn't have libraries to support the compress (Lempel-Ziv)
- # compression, so that is not supported. The intent of this is
- # to reduce bandwidth by default. If this routine sets up
- # compression, then it does the decompression also, removing
- # the header as well to prevent confusion. Otherwise
- # it leaves the body as it found it.
- #
- # 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.
- #
- # This method never raises an exception.
- #
- # 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 = {}, dest = nil, &block) # :yield: +body_segment+
- res = nil
- if HAVE_ZLIB
- unless initheader.keys.any?{|k| k.downcase == "accept-encoding"}
- initheader = initheader.merge({
- "accept-encoding" => "gzip;q=1.0,deflate;q=0.6,identity;q=0.3"
- })
- @compression = true
- end
- end
- request(Get.new(path, initheader)) {|r|
- if r.key?("content-encoding") and @compression
- @compression = nil # Clear it till next set.
- the_body = r.read_body dest, &block
- case r["content-encoding"]
- when "gzip"
- r.body= Zlib::GzipReader.new(StringIO.new(the_body), encoding: "ASCII-8BIT").read
- r.delete("content-encoding")
- when "deflate"
- r.body= Zlib::Inflate.inflate(the_body);
- r.delete("content-encoding")
- when "identity"
- ; # nothing needed
- else
- ; # Don't do anything dramatic, unless we need to later
- end
- else
- r.read_body dest, &block
- end
- res = r
- }
- 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.
- #
- # 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)
- request(Head.new(path, initheader))
- end
-
- # Posts +data+ (must be a String) to +path+. +header+ must be a Hash
- # like { 'Accept' => '*/*', ... }.
- #
- # 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.
- #
- # This method never raises exception.
- #
- # 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+
- send_entity(path, data, initheader, dest, Post, &block)
- end
-
- # Sends a PATCH request to the +path+ and gets a response,
- # as an HTTPResponse object.
- def patch(path, data, initheader = nil, dest = nil, &block) # :yield: +body_segment+
- send_entity(path, data, initheader, dest, Patch, &block)
- end
-
- def put(path, data, initheader = nil) #:nodoc:
- request(Put.new(path, initheader), data)
- 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+.
- # Returns the response as a Net::HTTPResponse object.
- #
- # When called with a block, passes an HTTPResponse object to the block.
- # The body of the response will not have been read yet;
- # the block 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 in this case.
- # p response['content-type']
- # puts response.body
- #
- # # Using a 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 returns the response
- # as a Net::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+.
- #
- # Returns the response as a Net::HTTPResponse object.
- #
- # When called with a block, the block is passed an HTTPResponse
- # object. The body of that response will not have been read yet;
- # the block 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 in this case
- #
- # # 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.
- # Also sends a DATA string if +data+ is given.
- #
- # Returns a Net::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 +req+ to the HTTP server.
- #
- # If +req+ is a Net::HTTP::Post or Net::HTTP::Put request containing
- # data, the data is also sent. Providing data for a Net::HTTP::Head or
- # Net::HTTP::Get request results in an ArgumentError.
- #
- # Returns an HTTPResponse object.
- #
- # When called with a block, passes an HTTPResponse object to the block.
- # The body of the response will not have been read yet;
- # the block can process it using HTTPResponse#read_body,
- # if desired.
- #
- # 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()
- req.proxy_basic_auth proxy_user(), proxy_pass() unless use_ssl?
- end
- req.set_body_internal body
- res = transport_request(req, &block)
- if sspi_auth?(res)
- sspi_auth(req)
- res = transport_request(req, &block)
- end
- res
- end
-
- private
-
- # Executes a request which uses a representation
- # and returns its body.
- def send_entity(path, data, initheader, dest, type, &block)
- res = nil
- request(type.new(path, initheader), data) {|r|
- r.read_body dest, &block
- res = r
- }
- res
- end
-
- def transport_request(req)
- begin_transport req
- res = catch(:response) {
- 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?
- }
- res
- }
- end_transport req, res
- res
- rescue => exception
- D "Conn close because of error #{exception}"
- @socket.close if @socket and not @socket.closed?
- raise exception
- end
-
- def begin_transport(req)
- connect if @socket.closed?
- if not req.response_body_permitted? and @close_on_empty_response
- req['connection'] ||= 'close'
- end
- req['host'] ||= addr_port()
- end
-
- def end_transport(req, res)
- @curr_http_version = res.http_version
- if @socket.closed?
- D 'Conn socket closed'
- elsif not res.body and @close_on_empty_response
- D 'Conn close'
- @socket.close
- elsif keep_alive?(req, res)
- D 'Conn keep-alive'
- else
- D 'Conn close'
- @socket.close
- end
- end
-
- def keep_alive?(req, res)
- return false if req.connection_close?
- if @curr_http_version <= '1.0'
- res.connection_keep_alive?
- else # HTTP/1.1 or later
- not res.connection_close?
- end
- end
-
- def sspi_auth?(res)
- return false unless @sspi_enabled
- if res.kind_of?(HTTPProxyAuthenticationRequired) and
- proxy? and res["Proxy-Authenticate"].include?("Negotiate")
- begin
- require 'win32/sspi'
- true
- rescue LoadError
- false
- end
- else
- false
- end
- end
-
- def sspi_auth(req)
- n = Win32::SSPI::NegotiateAuth.new
- req["Proxy-Authorization"] = "Negotiate #{n.get_initial_token}"
- # Some versions of ISA will close the connection if this isn't present.
- req["Connection"] = "Keep-Alive"
- req["Proxy-Connection"] = "Keep-Alive"
- res = transport_request(req)
- authphrase = res["Proxy-Authenticate"] or return res
- req["Proxy-Authorization"] = "Negotiate #{n.complete_authentication(authphrase)}"
- rescue => err
- raise HTTPAuthenticationError.new('HTTP authentication failed', err)
- end
-
- #
- # utils
- #
-
- private
-
- def addr_port
- if use_ssl?
- address() + (port == HTTP.https_default_port ? '' : ":#{port()}")
- else
- address() + (port == HTTP.http_default_port ? '' : ":#{port()}")
- end
- end
-
- def D(msg)
- return unless @debug_output
- @debug_output << msg
- @debug_output << "\n"
- end
-
- end
-
- HTTPSession = HTTP
-
-
- # The HTTPHeader module defines methods for reading and writing
- # HTTP headers.
- #
- # It is used as a mixin by other classes, to provide hash-like
- # access to HTTP header values. Unlike raw hash access, HTTPHeader
- # provides access via case-insensitive keys. It also provides
- # methods for accessing commonly-used HTTP header values in more
- # convenient formats.
- #
- module HTTPHeader
-
- def initialize_http_header(initheader)
- @header = {}
- return unless initheader
- initheader.each do |key, value|
- warn "net/http: warning: duplicated HTTP header: #{key}" if key?(key) and $VERBOSE
- @header[key.downcase] = [value.strip]
- end
- end
-
- def size #:nodoc: obsolete
- @header.size
- end
-
- alias length size #:nodoc: obsolete
-
- # Returns the header field corresponding to the case-insensitive key.
- # For example, a key of "Content-Type" might return "text/html"
- def [](key)
- a = @header[key.downcase] or return nil
- a.join(', ')
- end
-
- # Sets the header field corresponding to the case-insensitive key.
- def []=(key, val)
- unless val
- @header.delete key.downcase
- return val
- end
- @header[key.downcase] = [val]
- end
-
- # [Ruby 1.8.3]
- # Adds a value to a named header field, instead of replacing its value.
- # Second argument +val+ must be a String.
- # See also #[]=, #[] and #get_fields.
- #
- # request.add_field 'X-My-Header', 'a'
- # p request['X-My-Header'] #=> "a"
- # p request.get_fields('X-My-Header') #=> ["a"]
- # request.add_field 'X-My-Header', 'b'
- # p request['X-My-Header'] #=> "a, b"
- # p request.get_fields('X-My-Header') #=> ["a", "b"]
- # request.add_field 'X-My-Header', 'c'
- # p request['X-My-Header'] #=> "a, b, c"
- # p request.get_fields('X-My-Header') #=> ["a", "b", "c"]
- #
- def add_field(key, val)
- if @header.key?(key.downcase)
- @header[key.downcase].push val
- else
- @header[key.downcase] = [val]
- end
- end
-
- # [Ruby 1.8.3]
- # Returns an array of header field strings corresponding to the
- # case-insensitive +key+. This method allows you to get duplicated
- # header fields without any processing. See also #[].
- #
- # p response.get_fields('Set-Cookie')
- # #=> ["session=al98axx; expires=Fri, 31-Dec-1999 23:58:23",
- # "query=rubyscript; expires=Fri, 31-Dec-1999 23:58:23"]
- # p response['Set-Cookie']
- # #=> "session=al98axx; expires=Fri, 31-Dec-1999 23:58:23, query=rubyscript; expires=Fri, 31-Dec-1999 23:58:23"
- #
- def get_fields(key)
- return nil unless @header[key.downcase]
- @header[key.downcase].dup
- end
-
- # Returns the header field corresponding to the case-insensitive key.
- # Returns the default value +args+, or the result of the block, or
- # raises an IndexError if there's no header field named +key+
- # See Hash#fetch
- def fetch(key, *args, &block) #:yield: +key+
- a = @header.fetch(key.downcase, *args, &block)
- a.kind_of?(Array) ? a.join(', ') : a
- end
-
- # Iterates through the header names and values, passing in the name
- # and value to the code block supplied.
- #
- # Example:
- #
- # response.header.each_header {|key,value| puts "#{key} = #{value}" }
- #
- def each_header #:yield: +key+, +value+
- block_given? or return enum_for(__method__)
- @header.each do |k,va|
- yield k, va.join(', ')
- end
- end
-
- alias each each_header
-
- # Iterates through the header names in the header, passing
- # each header name to the code block.
- def each_name(&block) #:yield: +key+
- block_given? or return enum_for(__method__)
- @header.each_key(&block)
- end
-
- alias each_key each_name
-
- # Iterates through the header names in the header, passing
- # capitalized header names to the code block.
- #
- # Note that header names are capitalized systematically;
- # capitalization may not match that used by the remote HTTP
- # server in its response.
- def each_capitalized_name #:yield: +key+
- block_given? or return enum_for(__method__)
- @header.each_key do |k|
- yield capitalize(k)
- end
- end
-
- # Iterates through header values, passing each value to the
- # code block.
- def each_value #:yield: +value+
- block_given? or return enum_for(__method__)
- @header.each_value do |va|
- yield va.join(', ')
- end
- end
-
- # Removes a header field, specified by case-insensitive key.
- def delete(key)
- @header.delete(key.downcase)
- end
-
- # true if +key+ header exists.
- def key?(key)
- @header.key?(key.downcase)
- end
-
- # Returns a Hash consisting of header names and values.
- # e.g.
- # {"cache-control" => "private",
- # "content-type" => "text/html",
- # "date" => "Wed, 22 Jun 2005 22:11:50 GMT"}
- def to_hash
- @header.dup
- end
-
- # As for #each_header, except the keys are provided in capitalized form.
- #
- # Note that header names are capitalized systematically;
- # capitalization may not match that used by the remote HTTP
- # server in its response.
- def each_capitalized
- block_given? or return enum_for(__method__)
- @header.each do |k,v|
- yield capitalize(k), v.join(', ')
- end
- end
-
- alias canonical_each each_capitalized
-
- def capitalize(name)
- name.split(/-/).map {|s| s.capitalize }.join('-')
- end
- private :capitalize
-
- # Returns an Array of Range objects which represent the Range:
- # HTTP header field, or +nil+ if there is no such header.
- def range
- return nil unless @header['range']
- self['Range'].split(/,/).map {|spec|
- m = /bytes\s*=\s*(\d+)?\s*-\s*(\d+)?/i.match(spec) or
- raise HTTPHeaderSyntaxError, "wrong Range: #{spec}"
- d1 = m[1].to_i
- d2 = m[2].to_i
- if m[1] and m[2] then d1..d2
- elsif m[1] then d1..-1
- elsif m[2] then -d2..-1
- else
- raise HTTPHeaderSyntaxError, 'range is not specified'
- end
- }
- end
-
- # Sets the HTTP Range: header.
- # Accepts either a Range object as a single argument,
- # or a beginning index and a length from that index.
- # Example:
- #
- # req.range = (0..1023)
- # req.set_range 0, 1023
- #
- def set_range(r, e = nil)
- unless r
- @header.delete 'range'
- return r
- end
- r = (r...r+e) if e
- case r
- when Numeric
- n = r.to_i
- rangestr = (n > 0 ? "0-#{n-1}" : "-#{-n}")
- when Range
- first = r.first
- last = r.last
- last -= 1 if r.exclude_end?
- if last == -1
- rangestr = (first > 0 ? "#{first}-" : "-#{-first}")
- else
- raise HTTPHeaderSyntaxError, 'range.first is negative' if first < 0
- raise HTTPHeaderSyntaxError, 'range.last is negative' if last < 0
- raise HTTPHeaderSyntaxError, 'must be .first < .last' if first > last
- rangestr = "#{first}-#{last}"
- end
- else
- raise TypeError, 'Range/Integer is required'
- end
- @header['range'] = ["bytes=#{rangestr}"]
- r
- end
-
- alias range= set_range
-
- # Returns an Integer object which represents the HTTP Content-Length:
- # header field, or +nil+ if that field was not provided.
- def content_length
- return nil unless key?('Content-Length')
- len = self['Content-Length'].slice(/\d+/) or
- raise HTTPHeaderSyntaxError, 'wrong Content-Length format'
- len.to_i
- end
-
- def content_length=(len)
- unless len
- @header.delete 'content-length'
- return nil
- end
- @header['content-length'] = [len.to_i.to_s]
- end
-
- # Returns "true" if the "transfer-encoding" header is present and
- # set to "chunked". This is an HTTP/1.1 feature, allowing the
- # the content to be sent in "chunks" without at the outset
- # stating the entire content length.
- def chunked?
- return false unless @header['transfer-encoding']
- field = self['Transfer-Encoding']
- (/(?:\A|[^\-\w])chunked(?![\-\w])/i =~ field) ? true : false
- end
-
- # Returns a Range object which represents the value of the Content-Range:
- # header field.
- # For a partial entity body, this indicates where this fragment
- # fits inside the full entity body, as range of byte offsets.
- def content_range
- return nil unless @header['content-range']
- m = %r<bytes\s+(\d+)-(\d+)/(\d+|\*)>i.match(self['Content-Range']) or
- raise HTTPHeaderSyntaxError, 'wrong Content-Range format'
- m[1].to_i .. m[2].to_i
- end
-
- # The length of the range represented in Content-Range: header.
- def range_length
- r = content_range() or return nil
- r.end - r.begin + 1
- end
-
- # Returns a content type string such as "text/html".
- # This method returns nil if Content-Type: header field does not exist.
- def content_type
- return nil unless main_type()
- if sub_type()
- then "#{main_type()}/#{sub_type()}"
- else main_type()
- end
- end
-
- # Returns a content type string such as "text".
- # This method returns nil if Content-Type: header field does not exist.
- def main_type
- return nil unless @header['content-type']
- self['Content-Type'].split(';').first.to_s.split('/')[0].to_s.strip
- end
-
- # Returns a content type string such as "html".
- # This method returns nil if Content-Type: header field does not exist
- # or sub-type is not given (e.g. "Content-Type: text").
- def sub_type
- return nil unless @header['content-type']
- _, sub = *self['Content-Type'].split(';').first.to_s.split('/')
- return nil unless sub
- sub.strip
- end
-
- # Any parameters specified for the content type, returned as a Hash.
- # For example, a header of Content-Type: text/html; charset=EUC-JP
- # would result in type_params returning {'charset' => 'EUC-JP'}
- def type_params
- result = {}
- list = self['Content-Type'].to_s.split(';')
- list.shift
- list.each do |param|
- k, v = *param.split('=', 2)
- result[k.strip] = v.strip
- end
- result
- end
-
- # Sets the content type in an HTTP header.
- # The +type+ should be a full HTTP content type, e.g. "text/html".
- # The +params+ are an optional Hash of parameters to add after the
- # content type, e.g. {'charset' => 'iso-8859-1'}
- def set_content_type(type, params = {})
- @header['content-type'] = [type + params.map{|k,v|"; #{k}=#{v}"}.join('')]
- end
-
- alias content_type= set_content_type
-
- # Set header fields and a body from HTML form data.
- # +params+ should be an Array of Arrays or
- # a Hash containing HTML form data.
- # Optional argument +sep+ means data record separator.
- #
- # Values are URL encoded as necessary and the content-type is set to
- # application/x-www-form-urlencoded
- #
- # Example:
- # http.form_data = {"q" => "ruby", "lang" => "en"}
- # http.form_data = {"q" => ["ruby", "perl"], "lang" => "en"}
- # http.set_form_data({"q" => "ruby", "lang" => "en"}, ';')
- #
- def set_form_data(params, sep = '&')
- query = URI.encode_www_form(params)
- query.gsub!(/&/, sep) if sep != '&'
- self.body = query
- self.content_type = 'application/x-www-form-urlencoded'
- end
-
- alias form_data= set_form_data
-
- # Set a HTML form data set.
- # +params+ is the form data set; it is an Array of Arrays or a Hash
- # +enctype is the type to encode the form data set.
- # It is application/x-www-form-urlencoded or multipart/form-data.
- # +formpot+ is an optional hash to specify the detail.
- #
- # boundary:: the boundary of the multipart message
- # charset:: the charset of the message. All names and the values of
- # non-file fields are encoded as the charset.
- #
- # Each item of params is an array and contains following items:
- # +name+:: the name of the field
- # +value+:: the value of the field, it should be a String or a File
- # +opt+:: an optional hash to specify additional information
- #
- # Each item is a file field or a normal field.
- # If +value+ is a File object or the +opt+ have a filename key,
- # the item is treated as a file field.
- #
- # If Transfer-Encoding is set as chunked, this send the request in
- # chunked encoding. Because chunked encoding is HTTP/1.1 feature,
- # you must confirm the server to support HTTP/1.1 before sending it.
- #
- # Example:
- # http.set_form([["q", "ruby"], ["lang", "en"]])
- #
- # See also RFC 2388, RFC 2616, HTML 4.01, and HTML5
- #
- def set_form(params, enctype='application/x-www-form-urlencoded', formopt={})
- @body_data = params
- @body = nil
- @body_stream = nil
- @form_option = formopt
- case enctype
- when /\Aapplication\/x-www-form-urlencoded\z/i,
- /\Amultipart\/form-data\z/i
- self.content_type = enctype
- else
- raise ArgumentError, "invalid enctype: #{enctype}"
- end
- end
-
- # Set the Authorization: header for "Basic" authorization.
- def basic_auth(account, password)
- @header['authorization'] = [basic_encode(account, password)]
- end
-
- # Set Proxy-Authorization: header for "Basic" authorization.
- def proxy_basic_auth(account, password)
- @header['proxy-authorization'] = [basic_encode(account, password)]
- end
-
- def basic_encode(account, password)
- 'Basic ' + ["#{account}:#{password}"].pack('m').delete("\r\n")
- end
- private :basic_encode
-
- def connection_close?
- tokens(@header['connection']).include?('close') or
- tokens(@header['proxy-connection']).include?('close')
- end
-
- def connection_keep_alive?
- tokens(@header['connection']).include?('keep-alive') or
- tokens(@header['proxy-connection']).include?('keep-alive')
- end
-
- def tokens(vals)
- return [] unless vals
- vals.map {|v| v.split(',') }.flatten\
- .reject {|str| str.strip.empty? }\
- .map {|tok| tok.strip.downcase }
- end
- private :tokens
-
- end
-
-
- # HTTPGenericRequest is the parent of the HTTPRequest class.
- # Do not use this directly; use a subclass of HTTPRequest.
- #
- # Mixes in the HTTPHeader module to provide easier access to HTTP headers.
- #
- class HTTPGenericRequest
-
- include HTTPHeader
-
- def initialize(m, reqbody, resbody, path, initheader = nil)
- @method = m
- @request_has_body = reqbody
- @response_has_body = resbody
- raise ArgumentError, "no HTTP request path given" unless path
- raise ArgumentError, "HTTP request path is empty" if path.empty?
- @path = path
- initialize_http_header initheader
- self['Accept'] ||= '*/*'
- self['User-Agent'] ||= 'Ruby'
- @body = nil
- @body_stream = nil
- @body_data = nil
- end
-
- attr_reader :method
- attr_reader :path
-
- def inspect
- "\#<#{self.class} #{@method}>"
- end
-
- def request_body_permitted?
- @request_has_body
- end
-
- def response_body_permitted?
- @response_has_body
- end
-
- def body_exist?
- warn "Net::HTTPRequest#body_exist? is obsolete; use response_body_permitted?" if $VERBOSE
- response_body_permitted?
- end
-
- attr_reader :body
-
- def body=(str)
- @body = str
- @body_stream = nil
- @body_data = nil
- str
- end
-
- attr_reader :body_stream
-
- def body_stream=(input)
- @body = nil
- @body_stream = input
- @body_data = nil
- input
- end
-
- def set_body_internal(str) #:nodoc: internal use only
- raise ArgumentError, "both of body argument and HTTPRequest#body set" if str and (@body or @body_stream)
- self.body = str if str
- end
-
- #
- # write
- #
-
- def exec(sock, ver, path) #:nodoc: internal use only
- if @body
- send_request_with_body sock, ver, path, @body
- elsif @body_stream
- send_request_with_body_stream sock, ver, path, @body_stream
- elsif @body_data
- send_request_with_body_data sock, ver, path, @body_data
- else
- write_header sock, ver, path
- end
- end
-
- private
-
- def send_request_with_body(sock, ver, path, body)
- self.content_length = body.bytesize
- delete 'Transfer-Encoding'
- supply_default_content_type
- write_header sock, ver, path
- wait_for_continue sock, ver if sock.continue_timeout
- sock.write body
- end
-
- def send_request_with_body_stream(sock, ver, path, f)
- unless content_length() or chunked?
- raise ArgumentError,
- "Content-Length not given and Transfer-Encoding is not `chunked'"
- end
- supply_default_content_type
- write_header sock, ver, path
- wait_for_continue sock, ver if sock.continue_timeout
- if chunked?
- while s = f.read(1024)
- sock.write(sprintf("%x\r\n", s.length) << s << "\r\n")
- end
- sock.write "0\r\n\r\n"
- else
- while s = f.read(1024)
- sock.write s
- end
- end
- end
-
- def send_request_with_body_data(sock, ver, path, params)
- if /\Amultipart\/form-data\z/i !~ self.content_type
- self.content_type = 'application/x-www-form-urlencoded'
- return send_request_with_body(sock, ver, path, URI.encode_www_form(params))
- end
-
- opt = @form_option.dup
- require 'securerandom' unless defined?(SecureRandom)
- opt[:boundary] ||= SecureRandom.urlsafe_base64(40)
- self.set_content_type(self.content_type, boundary: opt[:boundary])
- if chunked?
- write_header sock, ver, path
- encode_multipart_form_data(sock, params, opt)
- else
- require 'tempfile'
- file = Tempfile.new('multipart')
- file.binmode
- encode_multipart_form_data(file, params, opt)
- file.rewind
- self.content_length = file.size
- write_header sock, ver, path
- IO.copy_stream(file, sock)
- end
- end
-
- def encode_multipart_form_data(out, params, opt)
- charset = opt[:charset]
- boundary = opt[:boundary]
- require 'securerandom' unless defined?(SecureRandom)
- boundary ||= SecureRandom.urlsafe_base64(40)
- chunked_p = chunked?
-
- buf = ''
- params.each do |key, value, h={}|
- key = quote_string(key, charset)
- filename =
- h.key?(:filename) ? h[:filename] :
- value.respond_to?(:to_path) ? File.basename(value.to_path) :
- nil
-
- buf << "--#{boundary}\r\n"
- if filename
- filename = quote_string(filename, charset)
- type = h[:content_type] || 'application/octet-stream'
- buf << "Content-Disposition: form-data; " \
- "name=\"#{key}\"; filename=\"#{filename}\"\r\n" \
- "Content-Type: #{type}\r\n\r\n"
- if !out.respond_to?(:write) || !value.respond_to?(:read)
- # if +out+ is not an IO or +value+ is not an IO
- buf << (value.respond_to?(:read) ? value.read : value)
- elsif value.respond_to?(:size) && chunked_p
- # if +out+ is an IO and +value+ is a File, use IO.copy_stream
- flush_buffer(out, buf, chunked_p)
- out << "%x\r\n" % value.size if chunked_p
- IO.copy_stream(value, out)
- out << "\r\n" if chunked_p
- else
- # +out+ is an IO, and +value+ is not a File but an IO
- flush_buffer(out, buf, chunked_p)
- 1 while flush_buffer(out, value.read(4096), chunked_p)
- end
- else
- # non-file field:
- # HTML5 says, "The parts of the generated multipart/form-data
- # resource that correspond to non-file fields must not have a
- # Content-Type header specified."
- buf << "Content-Disposition: form-data; name=\"#{key}\"\r\n\r\n"
- buf << (value.respond_to?(:read) ? value.read : value)
- end
- buf << "\r\n"
- end
- buf << "--#{boundary}--\r\n"
- flush_buffer(out, buf, chunked_p)
- out << "0\r\n\r\n" if chunked_p
- end
-
- def quote_string(str, charset)
- str = str.encode(charset, fallback:->(c){'&#%d;'%c.encode("UTF-8").ord}) if charset
- str = str.gsub(/[\\"]/, '\\\\\&')
- end
-
- def flush_buffer(out, buf, chunked_p)
- return unless buf
- out << "%x\r\n"%buf.bytesize if chunked_p
- out << buf
- out << "\r\n" if chunked_p
- buf.clear
- end
-
- def supply_default_content_type
- return if content_type()
- warn 'net/http: warning: Content-Type did not set; using application/x-www-form-urlencoded' if $VERBOSE
- set_content_type 'application/x-www-form-urlencoded'
- end
-
- ##
- # Waits up to the continue timeout for a response from the server provided
- # we're speaking HTTP 1.1 and are expecting a 100-continue response.
-
- def wait_for_continue(sock, ver)
- if ver >= '1.1' and @header['expect'] and
- @header['expect'].include?('100-continue')
- if IO.select([sock.io], nil, nil, sock.continue_timeout)
- res = HTTPResponse.read_new(sock)
- unless res.kind_of?(Net::HTTPContinue)
- throw :response, res
- end
- end
- end
- end
-
- def write_header(sock, ver, path)
- buf = "#{@method} #{path} HTTP/#{ver}\r\n"
- each_capitalized do |k,v|
- buf << "#{k}: #{v}\r\n"
- end
- buf << "\r\n"
- sock.write buf
- end
-
- end
-
-
- #
- # HTTP request class.
- # This class wraps together the request header and the request path.
- # You cannot use this class directly. Instead, you should use one of its
- # subclasses: Net::HTTP::Get, Net::HTTP::Post, Net::HTTP::Head.
- #
- class HTTPRequest < HTTPGenericRequest
-
- # Creates HTTP request object.
- def initialize(path, initheader = nil)
- super self.class::METHOD,
- self.class::REQUEST_HAS_BODY,
- self.class::RESPONSE_HAS_BODY,
- path, initheader
- end
- end
-
-
- class HTTP # reopen
- #
- # HTTP/1.1 methods --- RFC2616
- #
-
- # See Net::HTTPGenericRequest for attributes and methods.
- # See Net::HTTP for usage examples.
- class Get < HTTPRequest
- METHOD = 'GET'
- REQUEST_HAS_BODY = false
- RESPONSE_HAS_BODY = true
- end
-
- # See Net::HTTPGenericRequest for attributes and methods.
- # See Net::HTTP for usage examples.
- class Head < HTTPRequest
- METHOD = 'HEAD'
- REQUEST_HAS_BODY = false
- RESPONSE_HAS_BODY = false
- end
-
- # See Net::HTTPGenericRequest for attributes and methods.
- # See Net::HTTP for usage examples.
- class Post < HTTPRequest
- METHOD = 'POST'
- REQUEST_HAS_BODY = true
- RESPONSE_HAS_BODY = true
- end
-
- # See Net::HTTPGenericRequest for attributes and methods.
- # See Net::HTTP for usage examples.
- class Put < HTTPRequest
- METHOD = 'PUT'
- REQUEST_HAS_BODY = true
- RESPONSE_HAS_BODY = true
- end
-
- # See Net::HTTPGenericRequest for attributes and methods.
- # See Net::HTTP for usage examples.
- class Delete < HTTPRequest
- METHOD = 'DELETE'
- REQUEST_HAS_BODY = false
- RESPONSE_HAS_BODY = true
- end
-
- # See Net::HTTPGenericRequest for attributes and methods.
- class Options < HTTPRequest
- METHOD = 'OPTIONS'
- REQUEST_HAS_BODY = false
- RESPONSE_HAS_BODY = false
- end
-
- # See Net::HTTPGenericRequest for attributes and methods.
- class Trace < HTTPRequest
- METHOD = 'TRACE'
- REQUEST_HAS_BODY = false
- RESPONSE_HAS_BODY = true
- end
-
- #
- # PATCH method --- RFC5789
- #
-
- # See Net::HTTPGenericRequest for attributes and methods.
- class Patch < HTTPRequest
- METHOD = 'PATCH'
- REQUEST_HAS_BODY = true
- RESPONSE_HAS_BODY = true
- end
-
- #
- # WebDAV methods --- RFC2518
- #
-
- # See Net::HTTPGenericRequest for attributes and methods.
- class Propfind < HTTPRequest
- METHOD = 'PROPFIND'
- REQUEST_HAS_BODY = true
- RESPONSE_HAS_BODY = true
- end
-
- # See Net::HTTPGenericRequest for attributes and methods.
- class Proppatch < HTTPRequest
- METHOD = 'PROPPATCH'
- REQUEST_HAS_BODY = true
- RESPONSE_HAS_BODY = true
- end
-
- # See Net::HTTPGenericRequest for attributes and methods.
- class Mkcol < HTTPRequest
- METHOD = 'MKCOL'
- REQUEST_HAS_BODY = true
- RESPONSE_HAS_BODY = true
- end
-
- # See Net::HTTPGenericRequest for attributes and methods.
- class Copy < HTTPRequest
- METHOD = 'COPY'
- REQUEST_HAS_BODY = false
- RESPONSE_HAS_BODY = true
- end
-
- # See Net::HTTPGenericRequest for attributes and methods.
- class Move < HTTPRequest
- METHOD = 'MOVE'
- REQUEST_HAS_BODY = false
- RESPONSE_HAS_BODY = true
- end
-
- # See Net::HTTPGenericRequest for attributes and methods.
- class Lock < HTTPRequest
- METHOD = 'LOCK'
- REQUEST_HAS_BODY = true
- RESPONSE_HAS_BODY = true
- end
-
- # See Net::HTTPGenericRequest for attributes and methods.
- class Unlock < HTTPRequest
- METHOD = 'UNLOCK'
- REQUEST_HAS_BODY = true
- RESPONSE_HAS_BODY = true
- end
- end
-
-
- ###
- ### Response
- ###
-
- # HTTP exception class.
- # You cannot use HTTPExceptions directly; instead, you must use
- # its subclasses.
- module HTTPExceptions
- def initialize(msg, res) #:nodoc:
- super msg
- @response = res
- end
- attr_reader :response
- alias data response #:nodoc: obsolete
- end
- class HTTPError < ProtocolError
- include HTTPExceptions
- end
- class HTTPRetriableError < ProtoRetriableError
- include HTTPExceptions
- end
- class HTTPServerException < ProtoServerError
- # We cannot use the name "HTTPServerError", it is the name of the response.
- include HTTPExceptions
- end
- class HTTPFatalError < ProtoFatalError
- include HTTPExceptions
- end
-
-
- # HTTP response class.
- #
- # This class wraps together the response header and the response body (the
- # entity requested).
- #
- # It mixes in the HTTPHeader module, which provides access to response
- # header values both via hash-like methods and via individual readers.
- #
- # Note that each possible HTTP response code defines its own
- # HTTPResponse subclass. These are listed below.
- #
- # All classes are
- # defined under the Net module. Indentation indicates inheritance.
- #
- # xxx HTTPResponse
- #
- # 1xx HTTPInformation
- # 100 HTTPContinue
- # 101 HTTPSwitchProtocol
- #
- # 2xx HTTPSuccess
- # 200 HTTPOK
- # 201 HTTPCreated
- # 202 HTTPAccepted
- # 203 HTTPNonAuthoritativeInformation
- # 204 HTTPNoContent
- # 205 HTTPResetContent
- # 206 HTTPPartialContent
- #
- # 3xx HTTPRedirection
- # 300 HTTPMultipleChoice
- # 301 HTTPMovedPermanently
- # 302 HTTPFound
- # 303 HTTPSeeOther
- # 304 HTTPNotModified
- # 305 HTTPUseProxy
- # 307 HTTPTemporaryRedirect
- #
- # 4xx HTTPClientError
- # 400 HTTPBadRequest
- # 401 HTTPUnauthorized
- # 402 HTTPPaymentRequired
- # 403 HTTPForbidden
- # 404 HTTPNotFound
- # 405 HTTPMethodNotAllowed
- # 406 HTTPNotAcceptable
- # 407 HTTPProxyAuthenticationRequired
- # 408 HTTPRequestTimeOut
- # 409 HTTPConflict
- # 410 HTTPGone
- # 411 HTTPLengthRequired
- # 412 HTTPPreconditionFailed
- # 413 HTTPRequestEntityTooLarge
- # 414 HTTPRequestURITooLong
- # 415 HTTPUnsupportedMediaType
- # 416 HTTPRequestedRangeNotSatisfiable
- # 417 HTTPExpectationFailed
- #
- # 5xx HTTPServerError
- # 500 HTTPInternalServerError
- # 501 HTTPNotImplemented
- # 502 HTTPBadGateway
- # 503 HTTPServiceUnavailable
- # 504 HTTPGatewayTimeOut
- # 505 HTTPVersionNotSupported
- #
- # xxx HTTPUnknownResponse
- #
- class HTTPResponse
- # true if the response has a body.
- def HTTPResponse.body_permitted?
- self::HAS_BODY
- end
-
- def HTTPResponse.exception_type # :nodoc: internal use only
- self::EXCEPTION_TYPE
- end
- end # reopened after
-
- # :stopdoc:
-
- class HTTPUnknownResponse < HTTPResponse
- HAS_BODY = true
- EXCEPTION_TYPE = HTTPError
- end
- class HTTPInformation < HTTPResponse # 1xx
- HAS_BODY = false
- EXCEPTION_TYPE = HTTPError
- end
- class HTTPSuccess < HTTPResponse # 2xx
- HAS_BODY = true
- EXCEPTION_TYPE = HTTPError
- end
- class HTTPRedirection < HTTPResponse # 3xx
- HAS_BODY = true
- EXCEPTION_TYPE = HTTPRetriableError
- end
- class HTTPClientError < HTTPResponse # 4xx
- HAS_BODY = true
- EXCEPTION_TYPE = HTTPServerException # for backward compatibility
- end
- class HTTPServerError < HTTPResponse # 5xx
- HAS_BODY = true
- EXCEPTION_TYPE = HTTPFatalError # for backward compatibility
- end
-
- class HTTPContinue < HTTPInformation # 100
- HAS_BODY = false
- end
- class HTTPSwitchProtocol < HTTPInformation # 101
- HAS_BODY = false
- end
-
- class HTTPOK < HTTPSuccess # 200
- HAS_BODY = true
- end
- class HTTPCreated < HTTPSuccess # 201
- HAS_BODY = true
- end
- class HTTPAccepted < HTTPSuccess # 202
- HAS_BODY = true
- end
- class HTTPNonAuthoritativeInformation < HTTPSuccess # 203
- HAS_BODY = true
- end
- class HTTPNoContent < HTTPSuccess # 204
- HAS_BODY = false
- end
- class HTTPResetContent < HTTPSuccess # 205
- HAS_BODY = false
- end
- class HTTPPartialContent < HTTPSuccess # 206
- HAS_BODY = true
- end
-
- class HTTPMultipleChoice < HTTPRedirection # 300
- HAS_BODY = true
- end
- class HTTPMovedPermanently < HTTPRedirection # 301
- HAS_BODY = true
- end
- class HTTPFound < HTTPRedirection # 302
- HAS_BODY = true
- end
- HTTPMovedTemporarily = HTTPFound
- class HTTPSeeOther < HTTPRedirection # 303
- HAS_BODY = true
- end
- class HTTPNotModified < HTTPRedirection # 304
- HAS_BODY = false
- end
- class HTTPUseProxy < HTTPRedirection # 305
- HAS_BODY = false
- end
- # 306 unused
- class HTTPTemporaryRedirect < HTTPRedirection # 307
- HAS_BODY = true
- end
-
- class HTTPBadRequest < HTTPClientError # 400
- HAS_BODY = true
- end
- class HTTPUnauthorized < HTTPClientError # 401
- HAS_BODY = true
- end
- class HTTPPaymentRequired < HTTPClientError # 402
- HAS_BODY = true
- end
- class HTTPForbidden < HTTPClientError # 403
- HAS_BODY = true
- end
- class HTTPNotFound < HTTPClientError # 404
- HAS_BODY = true
- end
- class HTTPMethodNotAllowed < HTTPClientError # 405
- HAS_BODY = true
- end
- class HTTPNotAcceptable < HTTPClientError # 406
- HAS_BODY = true
- end
- class HTTPProxyAuthenticationRequired < HTTPClientError # 407
- HAS_BODY = true
- end
- class HTTPRequestTimeOut < HTTPClientError # 408
- HAS_BODY = true
- end
- class HTTPConflict < HTTPClientError # 409
- HAS_BODY = true
- end
- class HTTPGone < HTTPClientError # 410
- HAS_BODY = true
- end
- class HTTPLengthRequired < HTTPClientError # 411
- HAS_BODY = true
- end
- class HTTPPreconditionFailed < HTTPClientError # 412
- HAS_BODY = true
- end
- class HTTPRequestEntityTooLarge < HTTPClientError # 413
- HAS_BODY = true
- end
- class HTTPRequestURITooLong < HTTPClientError # 414
- HAS_BODY = true
- end
- HTTPRequestURITooLarge = HTTPRequestURITooLong
- class HTTPUnsupportedMediaType < HTTPClientError # 415
- HAS_BODY = true
- end
- class HTTPRequestedRangeNotSatisfiable < HTTPClientError # 416
- HAS_BODY = true
- end
- class HTTPExpectationFailed < HTTPClientError # 417
- HAS_BODY = true
- end
-
- class HTTPInternalServerError < HTTPServerError # 500
- HAS_BODY = true
- end
- class HTTPNotImplemented < HTTPServerError # 501
- HAS_BODY = true
- end
- class HTTPBadGateway < HTTPServerError # 502
- HAS_BODY = true
- end
- class HTTPServiceUnavailable < HTTPServerError # 503
- HAS_BODY = true
- end
- class HTTPGatewayTimeOut < HTTPServerError # 504
- HAS_BODY = true
- end
- class HTTPVersionNotSupported < HTTPServerError # 505
- HAS_BODY = true
- end
-
- # :startdoc:
-
-
- class HTTPResponse # reopen
-
- CODE_CLASS_TO_OBJ = {
- '1' => HTTPInformation,
- '2' => HTTPSuccess,
- '3' => HTTPRedirection,
- '4' => HTTPClientError,
- '5' => HTTPServerError
- }
- CODE_TO_OBJ = {
- '100' => HTTPContinue,
- '101' => HTTPSwitchProtocol,
-
- '200' => HTTPOK,
- '201' => HTTPCreated,
- '202' => HTTPAccepted,
- '203' => HTTPNonAuthoritativeInformation,
- '204' => HTTPNoContent,
- '205' => HTTPResetContent,
- '206' => HTTPPartialContent,
-
- '300' => HTTPMultipleChoice,
- '301' => HTTPMovedPermanently,
- '302' => HTTPFound,
- '303' => HTTPSeeOther,
- '304' => HTTPNotModified,
- '305' => HTTPUseProxy,
- '307' => HTTPTemporaryRedirect,
-
- '400' => HTTPBadRequest,
- '401' => HTTPUnauthorized,
- '402' => HTTPPaymentRequired,
- '403' => HTTPForbidden,
- '404' => HTTPNotFound,
- '405' => HTTPMethodNotAllowed,
- '406' => HTTPNotAcceptable,
- '407' => HTTPProxyAuthenticationRequired,
- '408' => HTTPRequestTimeOut,
- '409' => HTTPConflict,
- '410' => HTTPGone,
- '411' => HTTPLengthRequired,
- '412' => HTTPPreconditionFailed,
- '413' => HTTPRequestEntityTooLarge,
- '414' => HTTPRequestURITooLong,
- '415' => HTTPUnsupportedMediaType,
- '416' => HTTPRequestedRangeNotSatisfiable,
- '417' => HTTPExpectationFailed,
-
- '500' => HTTPInternalServerError,
- '501' => HTTPNotImplemented,
- '502' => HTTPBadGateway,
- '503' => HTTPServiceUnavailable,
- '504' => HTTPGatewayTimeOut,
- '505' => HTTPVersionNotSupported
- }
-
- class << HTTPResponse
- def read_new(sock) #:nodoc: internal use only
- httpv, code, msg = read_status_line(sock)
- res = response_class(code).new(httpv, code, msg)
- each_response_header(sock) do |k,v|
- res.add_field k, v
- end
- res
- end
-
- private
-
- def read_status_line(sock)
- str = sock.readline
- m = /\AHTTP(?:\/(\d+\.\d+))?\s+(\d\d\d)\s*(.*)\z/in.match(str) or
- raise HTTPBadResponse, "wrong status line: #{str.dump}"
- m.captures
- end
-
- def response_class(code)
- CODE_TO_OBJ[code] or
- CODE_CLASS_TO_OBJ[code[0,1]] or
- HTTPUnknownResponse
- end
-
- def each_response_header(sock)
- key = value = nil
- while true
- line = sock.readuntil("\n", true).sub(/\s+\z/, '')
- break if line.empty?
- if line[0] == ?\s or line[0] == ?\t and value
- value << ' ' unless value.empty?
- value << line.strip
- else
- yield key, value if key
- key, value = line.strip.split(/\s*:\s*/, 2)
- raise HTTPBadResponse, 'wrong header line format' if value.nil?
- end
- end
- yield key, value if key
- end
- end
-
- # next is to fix bug in RDoc, where the private inside class << self
- # spills out.
- public
-
- include HTTPHeader
-
- def initialize(httpv, code, msg) #:nodoc: internal use only
- @http_version = httpv
- @code = code
- @message = msg
- initialize_http_header nil
- @body = nil
- @read = false
- end
-
- # The HTTP version supported by the server.
- attr_reader :http_version
-
- # The HTTP result code string. For example, '302'. You can also
- # determine the response type by examining which response subclass
- # the response object is an instance of.
- attr_reader :code
-
- # The HTTP result message sent by the server. For example, 'Not Found'.
- attr_reader :message
- alias msg message # :nodoc: obsolete
-
- def inspect
- "#<#{self.class} #{@code} #{@message} readbody=#{@read}>"
- end
-
- #
- # response <-> exception relationship
- #
-
- def code_type #:nodoc:
- self.class
- end
-
- def error! #:nodoc:
- raise error_type().new(@code + ' ' + @message.dump, self)
- end
-
- def error_type #:nodoc:
- self.class::EXCEPTION_TYPE
- end
-
- # Raises an HTTP error if the response is not 2xx (success).
- def value
- error! unless self.kind_of?(HTTPSuccess)
- end
-
- #
- # header (for backward compatibility only; DO NOT USE)
- #
-
- def response #:nodoc:
- warn "#{caller(1)[0]}: warning: HTTPResponse#response is obsolete" if $VERBOSE
- self
- end
-
- def header #:nodoc:
- warn "#{caller(1)[0]}: warning: HTTPResponse#header is obsolete" if $VERBOSE
- self
- end
-
- def read_header #:nodoc:
- warn "#{caller(1)[0]}: warning: HTTPResponse#read_header is obsolete" if $VERBOSE
- self
- end
-
- #
- # body
- #
-
- def reading_body(sock, reqmethodallowbody) #:nodoc: internal use only
- @socket = sock
- @body_exist = reqmethodallowbody && self.class.body_permitted?
- begin
- yield
- self.body # ensure to read body
- ensure
- @socket = nil
- end
- end
-
- # Gets the entity body returned by the remote HTTP server.
- #
- # If a block is given, the body is passed to the block, and
- # the body is provided in fragments, as it is read in from the socket.
- #
- # Calling this method a second or subsequent time for the same
- # HTTPResponse object will return the value already read.
- #
- # http.request_get('/index.html') {|res|
- # puts res.read_body
- # }
- #
- # http.request_get('/index.html') {|res|
- # p res.read_body.object_id # 538149362
- # p res.read_body.object_id # 538149362
- # }
- #
- # # using iterator
- # http.request_get('/index.html') {|res|
- # res.read_body do |segment|
- # print segment
- # end
- # }
- #
- def read_body(dest = nil, &block)
- if @read
- raise IOError, "#{self.class}\#read_body called twice" if dest or block
- return @body
- end
- to = procdest(dest, block)
- stream_check
- if @body_exist
- read_body_0 to
- @body = to
- else
- @body = nil
- end
- @read = true
-
- @body
- end
-
- # Returns the full entity body.
- #
- # Calling this method a second or subsequent time will return the
- # string already read.
- #
- # http.request_get('/index.html') {|res|
- # puts res.body
- # }
- #
- # http.request_get('/index.html') {|res|
- # p res.body.object_id # 538149362
- # p res.body.object_id # 538149362
- # }
- #
- def body
- read_body()
- end
-
- # Because it may be necessary to modify the body, Eg, decompression
- # this method facilitates that.
- def body=(value)
- @body = value
- end
-
- alias entity body #:nodoc: obsolete
-
- private
-
- def read_body_0(dest)
- if chunked?
- read_chunked dest
- return
- end
- clen = content_length()
- if clen
- @socket.read clen, dest, true # ignore EOF
- return
- end
- clen = range_length()
- if clen
- @socket.read clen, dest
- return
- end
- @socket.read_all dest
- end
-
- def read_chunked(dest)
- len = nil
- total = 0
- while true
- line = @socket.readline
- hexlen = line.slice(/[0-9a-fA-F]+/) or
- raise HTTPBadResponse, "wrong chunk size line: #{line}"
- len = hexlen.hex
- break if len == 0
- begin
- @socket.read len, dest
- ensure
- total += len
- @socket.read 2 # \r\n
- end
- end
- until @socket.readline.empty?
- # none
- end
- end
-
- def stream_check
- raise IOError, 'attempt to read body out of block' if @socket.closed?
- end
-
- def procdest(dest, block)
- raise ArgumentError, 'both arg and block given for HTTP method' \
- if dest and block
- if block
- ReadAdapter.new(block)
- else
- dest || ''
- end
- end
-
- end
-
-
- # :enddoc:
-
- #--
- # for backward compatibility
- class HTTP
- ProxyMod = ProxyDelta
- end
- module NetPrivate
- HTTPRequest = ::Net::HTTPRequest
- end
-
- HTTPInformationCode = HTTPInformation
- HTTPSuccessCode = HTTPSuccess
- HTTPRedirectionCode = HTTPRedirection
- HTTPRetriableCode = HTTPRedirection
- HTTPClientErrorCode = HTTPClientError
- HTTPFatalErrorCode = HTTPClientError
- HTTPServerErrorCode = HTTPServerError
- HTTPResponceReceiver = HTTPResponse
-
-end # module Net
diff --git a/ruby_1_9_3/lib/net/https.rb b/ruby_1_9_3/lib/net/https.rb
deleted file mode 100644
index d36f82002d..0000000000
--- a/ruby_1_9_3/lib/net/https.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-=begin
-
-= net/https -- SSL/TLS enhancement for Net::HTTP.
-
- This file has been merged with net/http. There is no longer any need to
- require 'net/https' to use HTTPS.
-
- See Net::HTTP for details on how to make HTTPS connections.
-
-== 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'.)
-
-=end
-
-require 'net/http'
-require 'openssl'
diff --git a/ruby_1_9_3/lib/net/imap.rb b/ruby_1_9_3/lib/net/imap.rb
deleted file mode 100644
index 794e82328e..0000000000
--- a/ruby_1_9_3/lib/net/imap.rb
+++ /dev/null
@@ -1,3676 +0,0 @@
-#
-# = 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"
-require "strscan"
-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
-
- # Returns the max number of flags interned to symbols.
- def self.max_flag_count
- return @@max_flag_count
- end
-
- # Sets the max number of flags interned to symbols.
- def self.max_flag_count=(count)
- @@max_flag_count = count
- 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,
- # Net::IMAP::CramMD5Authenticator, and Net::IMAP::DigestMD5Authenticator
- # 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
- begin
- # try to call SSL::SSLSocket#io.
- @sock.io.shutdown
- rescue NoMethodError
- # @sock is not an SSL::SSLSocket.
- @sock.shutdown
- end
- rescue Errno::ENOTCONN
- # ignore `Errno::ENOTCONN: Socket is not connected' on some platforms.
- rescue Exception => e
- @receiver_thread.raise(e)
- end
- @receiver_thread.join
- synchronize do
- unless @sock.closed?
- @sock.close
- end
- end
- raise e if e
- 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 a STARTTLS command to start TLS session.
- def starttls(options = {}, verify = true)
- send_command("STARTTLS") do |resp|
- if resp.kind_of?(TaggedResponse) && resp.name == "OK"
- begin
- # for backward compatibility
- certs = options.to_str
- options = create_ssl_params(certs, verify)
- rescue NoMethodError
- end
- start_tls_session(options)
- end
- end
- 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 a XLIST 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 XLIST command is like the LIST command except that the flags
- # returned refer to the function of the folder/mailbox, e.g. :Sent
- #
- # The return value is an array of +Net::IMAP::MailboxList+. For example:
- #
- # imap.create("foo/bar")
- # imap.create("foo/baz")
- # p imap.xlist("", "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 xlist(refname, mailbox)
- synchronize do
- send_command("XLIST", refname, mailbox)
- return @responses.delete("XLIST")
- 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
-
- # Sends an IDLE command that waits for notifications of new or expunged
- # messages. Yields responses from the server during the IDLE.
- #
- # Use #idle_done() to leave IDLE.
- def idle(&response_handler)
- raise LocalJumpError, "no block given" unless response_handler
-
- response = nil
-
- synchronize do
- tag = Thread.current[:net_imap_tag] = generate_tag
- put_string("#{tag} IDLE#{CRLF}")
-
- begin
- add_response_handler(response_handler)
- @idle_done_cond = new_cond
- @idle_done_cond.wait
- @idle_done_cond = nil
- if @receiver_thread_terminating
- raise Net::IMAP::Error, "connection closed"
- end
- ensure
- unless @receiver_thread_terminating
- remove_response_handler(response_handler)
- put_string("DONE#{CRLF}")
- response = get_tagged_response(tag, "IDLE")
- end
- end
- end
-
- return response
- end
-
- # Leaves IDLE.
- def idle_done
- synchronize do
- if @idle_done_cond.nil?
- raise Net::IMAP::Error, "not during IDLE"
- end
- @idle_done_cond.signal
- end
- 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
- base64.unpack("m")[0].unpack("n*").pack("U*")
- end
- }.force_encoding("UTF-8")
- end
-
- # Encode a string from UTF-8 format to modified UTF-7.
- def self.encode_utf7(s)
- return s.gsub(/(&)|([^\x20-\x7e]+)/u) {
- if $1
- "&-"
- else
- base64 = [$&.unpack("U*").pack("n*")].pack("m")
- "&" + base64.delete("=\n").tr("/", ",") + "-"
- end
- }.force_encoding("ASCII-8BIT")
- end
-
- # Formats +time+ as an IMAP-style date.
- def self.format_date(time)
- return time.strftime('%d-%b-%Y')
- end
-
- # Formats +time+ as an IMAP-style date-time.
- def self.format_datetime(time)
- return time.strftime('%d-%b-%Y %H:%M %z')
- end
-
- private
-
- CRLF = "\r\n" # :nodoc:
- PORT = 143 # :nodoc:
- SSL_PORT = 993 # :nodoc:
-
- @@debug = false
- @@authenticators = {}
- @@max_flag_count = 10000
-
- # call-seq:
- # Net::IMAP.new(host, options = {})
- #
- # Creates a new Net::IMAP object and connects it to the specified
- # +host+.
- #
- # +options+ is an option hash, each key of which is a symbol.
- #
- # The available options are:
- #
- # port:: port number (default value is 143 for imap, or 993 for imaps)
- # ssl:: if options[:ssl] 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.
- # if options[:ssl] is a hash, it's passed to
- # OpenSSL::SSL::SSLContext#set_params as parameters.
- #
- # 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
- # immediately said goodbye to us.
- def initialize(host, port_or_options = {},
- usessl = false, certs = nil, verify = true)
- super()
- @host = host
- begin
- options = port_or_options.to_hash
- rescue NoMethodError
- # for backward compatibility
- options = {}
- options[:port] = port_or_options
- if usessl
- options[:ssl] = create_ssl_params(certs, verify)
- end
- end
- @port = options[:port] || (options[:ssl] ? SSL_PORT : PORT)
- @tag_prefix = "RUBY"
- @tagno = 0
- @parser = ResponseParser.new
- @sock = TCPSocket.open(@host, @port)
- if options[:ssl]
- start_tls_session(options[:ssl])
- @usessl = true
- else
- @usessl = false
- end
- @responses = Hash.new([].freeze)
- @tagged_responses = {}
- @response_handlers = []
- @tagged_response_arrival = new_cond
- @continuation_request_arrival = new_cond
- @idle_done_cond = nil
- @logout_command_tag = nil
- @debug_output_bol = true
- @exception = nil
-
- @greeting = get_response
- if @greeting.name == "BYE"
- @sock.close
- raise ByeResponseError, @greeting
- end
-
- @client_thread = Thread.current
- @receiver_thread = Thread.start {
- begin
- receive_responses
- rescue Exception
- end
- }
- @receiver_thread_terminating = false
- end
-
- def receive_responses
- connection_closed = false
- until connection_closed
- synchronize do
- @exception = nil
- end
- begin
- resp = get_response
- rescue Exception => e
- synchronize do
- @sock.close
- @exception = e
- end
- break
- end
- unless resp
- synchronize do
- @exception = EOFError.new("end of file reached")
- end
- break
- end
- begin
- synchronize do
- case resp
- when TaggedResponse
- @tagged_responses[resp.tag] = resp
- @tagged_response_arrival.broadcast
- if resp.tag == @logout_command_tag
- return
- end
- when UntaggedResponse
- record_response(resp.name, resp.data)
- if resp.data.instance_of?(ResponseText) &&
- (code = resp.data.code)
- record_response(code.name, code.data)
- end
- if resp.name == "BYE" && @logout_command_tag.nil?
- @sock.close
- @exception = ByeResponseError.new(resp)
- connection_closed = true
- end
- when ContinuationRequest
- @continuation_request_arrival.signal
- end
- @response_handlers.each do |handler|
- handler.call(resp)
- end
- end
- rescue Exception => e
- @exception = e
- synchronize do
- @tagged_response_arrival.broadcast
- @continuation_request_arrival.broadcast
- end
- end
- end
- synchronize do
- @receiver_thread_terminating = true
- @tagged_response_arrival.broadcast
- @continuation_request_arrival.broadcast
- if @idle_done_cond
- @idle_done_cond.signal
- end
- end
- end
-
- def get_tagged_response(tag, cmd)
- until @tagged_responses.key?(tag)
- raise @exception if @exception
- @tagged_response_arrival.wait
- end
- resp = @tagged_responses.delete(tag)
- case resp.name
- when /\A(?:NO)\z/ni
- raise NoResponseError, resp
- when /\A(?:BAD)\z/ni
- raise BadResponseError, resp
- else
- return resp
- end
- end
-
- def get_response
- buff = ""
- while true
- s = @sock.gets(CRLF)
- break unless s
- buff.concat(s)
- if /\{(\d+)\}\r\n/n =~ s
- s = @sock.read($1.to_i)
- buff.concat(s)
- else
- break
- end
- end
- return nil if buff.length == 0
- if @@debug
- $stderr.print(buff.gsub(/^/n, "S: "))
- end
- return @parser.parse(buff)
- end
-
- def record_response(name, data)
- unless @responses.has_key?(name)
- @responses[name] = []
- end
- @responses[name].push(data)
- end
-
- def send_command(cmd, *args, &block)
- synchronize do
- args.each do |i|
- validate_data(i)
- end
- tag = generate_tag
- put_string(tag + " " + cmd)
- args.each do |i|
- put_string(" ")
- send_data(i)
- end
- put_string(CRLF)
- if cmd == "LOGOUT"
- @logout_command_tag = tag
- end
- if block
- add_response_handler(block)
- end
- begin
- return get_tagged_response(tag, cmd)
- ensure
- if block
- remove_response_handler(block)
- end
- end
- end
- end
-
- def generate_tag
- @tagno += 1
- return format("%s%04d", @tag_prefix, @tagno)
- end
-
- def put_string(str)
- @sock.print(str)
- if @@debug
- if @debug_output_bol
- $stderr.print("C: ")
- end
- $stderr.print(str.gsub(/\n(?!\z)/n, "\nC: "))
- if /\r\n\z/n.match(str)
- @debug_output_bol = true
- else
- @debug_output_bol = false
- end
- end
- end
-
- def validate_data(data)
- case data
- when nil
- when String
- when Integer
- if data < 0 || data >= 4294967296
- raise DataFormatError, num.to_s
- end
- when Array
- data.each do |i|
- validate_data(i)
- end
- when Time
- when Symbol
- else
- data.validate
- end
- end
-
- def send_data(data)
- case data
- when nil
- put_string("NIL")
- when String
- send_string_data(data)
- when Integer
- send_number_data(data)
- when Array
- send_list_data(data)
- when Time
- send_time_data(data)
- when Symbol
- send_symbol_data(data)
- else
- data.send_data(self)
- end
- end
-
- def send_string_data(str)
- case str
- when ""
- put_string('""')
- when /[\x80-\xff\r\n]/n
- # literal
- send_literal(str)
- when /[(){ \x00-\x1f\x7f%*"\\]/n
- # quoted string
- send_quoted_string(str)
- else
- put_string(str)
- end
- end
-
- def send_quoted_string(str)
- put_string('"' + str.gsub(/["\\]/n, "\\\\\\&") + '"')
- end
-
- def send_literal(str)
- put_string("{" + str.bytesize.to_s + "}" + CRLF)
- @continuation_request_arrival.wait
- raise @exception if @exception
- put_string(str)
- end
-
- def send_number_data(num)
- put_string(num.to_s)
- end
-
- def send_list_data(list)
- put_string("(")
- first = true
- list.each do |i|
- if first
- first = false
- else
- put_string(" ")
- end
- send_data(i)
- end
- put_string(")")
- end
-
- DATE_MONTH = %w(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)
-
- def send_time_data(time)
- t = time.dup.gmtime
- s = format('"%2d-%3s-%4d %02d:%02d:%02d +0000"',
- t.day, DATE_MONTH[t.month - 1], t.year,
- t.hour, t.min, t.sec)
- put_string(s)
- end
-
- def send_symbol_data(symbol)
- put_string("\\" + symbol.to_s)
- end
-
- def search_internal(cmd, keys, charset)
- if keys.instance_of?(String)
- keys = [RawData.new(keys)]
- else
- normalize_searching_criteria(keys)
- end
- synchronize do
- if charset
- send_command(cmd, "CHARSET", charset, *keys)
- else
- send_command(cmd, *keys)
- end
- return @responses.delete("SEARCH")[-1]
- end
- end
-
- def fetch_internal(cmd, set, attr)
- case attr
- when String then
- attr = RawData.new(attr)
- when Array then
- attr = attr.map { |arg|
- arg.is_a?(String) ? RawData.new(arg) : arg
- }
- end
-
- synchronize do
- @responses.delete("FETCH")
- send_command(cmd, MessageSet.new(set), attr)
- return @responses.delete("FETCH")
- end
- end
-
- def store_internal(cmd, set, attr, flags)
- if attr.instance_of?(String)
- attr = RawData.new(attr)
- end
- synchronize do
- @responses.delete("FETCH")
- send_command(cmd, MessageSet.new(set), attr, flags)
- return @responses.delete("FETCH")
- end
- end
-
- def copy_internal(cmd, set, mailbox)
- send_command(cmd, MessageSet.new(set), mailbox)
- end
-
- def sort_internal(cmd, sort_keys, search_keys, charset)
- if search_keys.instance_of?(String)
- search_keys = [RawData.new(search_keys)]
- else
- normalize_searching_criteria(search_keys)
- end
- normalize_searching_criteria(search_keys)
- synchronize do
- send_command(cmd, sort_keys, charset, *search_keys)
- return @responses.delete("SORT")[-1]
- end
- end
-
- def thread_internal(cmd, algorithm, search_keys, charset)
- if search_keys.instance_of?(String)
- search_keys = [RawData.new(search_keys)]
- else
- normalize_searching_criteria(search_keys)
- end
- normalize_searching_criteria(search_keys)
- send_command(cmd, algorithm, charset, *search_keys)
- return @responses.delete("THREAD")[-1]
- end
-
- def normalize_searching_criteria(keys)
- keys.collect! do |i|
- case i
- when -1, Range, Array
- MessageSet.new(i)
- else
- i
- end
- end
- end
-
- def create_ssl_params(certs = nil, verify = true)
- params = {}
- if certs
- if File.file?(certs)
- params[:ca_file] = certs
- elsif File.directory?(certs)
- params[:ca_path] = certs
- end
- end
- if verify
- params[:verify_mode] = VERIFY_PEER
- else
- params[:verify_mode] = VERIFY_NONE
- end
- return params
- end
-
- def start_tls_session(params = {})
- unless defined?(OpenSSL)
- raise "SSL extension not installed"
- end
- if @sock.kind_of?(OpenSSL::SSL::SSLSocket)
- raise RuntimeError, "already using SSL"
- end
- begin
- params = params.to_hash
- rescue NoMethodError
- params = {}
- end
- context = SSLContext.new
- context.set_params(params)
- if defined?(VerifyCallbackProc)
- context.verify_callback = VerifyCallbackProc
- end
- @sock = SSLSocket.new(@sock, context)
- @sock.sync_close = true
- @sock.connect
- if context.verify_mode != VERIFY_NONE
- @sock.post_connection_check(@host)
- end
- end
-
- class RawData # :nodoc:
- def send_data(imap)
- imap.send(:put_string, @data)
- end
-
- def validate
- end
-
- private
-
- def initialize(data)
- @data = data
- end
- end
-
- class Atom # :nodoc:
- def send_data(imap)
- imap.send(:put_string, @data)
- end
-
- def validate
- end
-
- private
-
- def initialize(data)
- @data = data
- end
- end
-
- class QuotedString # :nodoc:
- def send_data(imap)
- imap.send(:send_quoted_string, @data)
- end
-
- def validate
- end
-
- private
-
- def initialize(data)
- @data = data
- end
- end
-
- class Literal # :nodoc:
- def send_data(imap)
- imap.send(:send_literal, @data)
- end
-
- def validate
- end
-
- private
-
- def initialize(data)
- @data = data
- end
- end
-
- class MessageSet # :nodoc:
- def send_data(imap)
- imap.send(:put_string, format_internal(@data))
- end
-
- def validate
- validate_internal(@data)
- end
-
- private
-
- def initialize(data)
- @data = data
- end
-
- def format_internal(data)
- case data
- when "*"
- return data
- when Integer
- if data == -1
- return "*"
- else
- return data.to_s
- end
- when Range
- return format_internal(data.first) +
- ":" + format_internal(data.last)
- when Array
- return data.collect {|i| format_internal(i)}.join(",")
- when ThreadMember
- return data.seqno.to_s +
- ":" + data.children.collect {|i| format_internal(i).join(",")}
- end
- end
-
- def validate_internal(data)
- case data
- when "*"
- when Integer
- ensure_nz_number(data)
- when Range
- when Array
- data.each do |i|
- validate_internal(i)
- end
- when ThreadMember
- data.children.each do |i|
- validate_internal(i)
- end
- else
- raise DataFormatError, data.inspect
- end
- end
-
- def ensure_nz_number(num)
- if num < -1 || num == 0 || num >= 4294967296
- msg = "nz_number must be non-zero unsigned 32-bit integer: " +
- num.inspect
- raise DataFormatError, msg
- end
- end
- end
-
- # Net::IMAP::ContinuationRequest represents command continuation requests.
- #
- # The command continuation request response is indicated by a "+" token
- # instead of a tag. This form of response indicates that the server is
- # ready to accept the continuation of a command from the client. The
- # remainder of this response is a line of text.
- #
- # continue_req ::= "+" SPACE (resp_text / base64)
- #
- # ==== Fields:
- #
- # data:: Returns the data (Net::IMAP::ResponseText).
- #
- # raw_data:: Returns the raw data string.
- ContinuationRequest = Struct.new(:data, :raw_data)
-
- # Net::IMAP::UntaggedResponse represents untagged responses.
- #
- # Data transmitted by the server to the client and status responses
- # that do not indicate command completion are prefixed with the token
- # "*", and are called untagged responses.
- #
- # response_data ::= "*" SPACE (resp_cond_state / resp_cond_bye /
- # mailbox_data / message_data / capability_data)
- #
- # ==== Fields:
- #
- # name:: Returns the name such as "FLAGS", "LIST", "FETCH"....
- #
- # data:: Returns the data such as an array of flag symbols,
- # a ((<Net::IMAP::MailboxList>)) object....
- #
- # raw_data:: Returns the raw data string.
- UntaggedResponse = Struct.new(:name, :data, :raw_data)
-
- # Net::IMAP::TaggedResponse represents tagged responses.
- #
- # The server completion result response indicates the success or
- # failure of the operation. It is tagged with the same tag as the
- # client command which began the operation.
- #
- # response_tagged ::= tag SPACE resp_cond_state CRLF
- #
- # tag ::= 1*<any ATOM_CHAR except "+">
- #
- # resp_cond_state ::= ("OK" / "NO" / "BAD") SPACE resp_text
- #
- # ==== Fields:
- #
- # tag:: Returns the tag.
- #
- # name:: Returns the name. the name is one of "OK", "NO", "BAD".
- #
- # data:: Returns the data. See ((<Net::IMAP::ResponseText>)).
- #
- # raw_data:: Returns the raw data string.
- #
- TaggedResponse = Struct.new(:tag, :name, :data, :raw_data)
-
- # Net::IMAP::ResponseText represents texts of responses.
- # The text may be prefixed by the response code.
- #
- # resp_text ::= ["[" resp_text_code "]" SPACE] (text_mime2 / text)
- # ;; text SHOULD NOT begin with "[" or "="
- #
- # ==== Fields:
- #
- # code:: Returns the response code. See ((<Net::IMAP::ResponseCode>)).
- #
- # text:: Returns the text.
- #
- ResponseText = Struct.new(:code, :text)
-
- #
- # Net::IMAP::ResponseCode represents response codes.
- #
- # resp_text_code ::= "ALERT" / "PARSE" /
- # "PERMANENTFLAGS" SPACE "(" #(flag / "\*") ")" /
- # "READ-ONLY" / "READ-WRITE" / "TRYCREATE" /
- # "UIDVALIDITY" SPACE nz_number /
- # "UNSEEN" SPACE nz_number /
- # atom [SPACE 1*<any TEXT_CHAR except "]">]
- #
- # ==== Fields:
- #
- # name:: Returns the name such as "ALERT", "PERMANENTFLAGS", "UIDVALIDITY"....
- #
- # data:: Returns the data if it exists.
- #
- ResponseCode = Struct.new(:name, :data)
-
- # Net::IMAP::MailboxList represents contents of the LIST response.
- #
- # mailbox_list ::= "(" #("\Marked" / "\Noinferiors" /
- # "\Noselect" / "\Unmarked" / flag_extension) ")"
- # SPACE (<"> QUOTED_CHAR <"> / nil) SPACE mailbox
- #
- # ==== Fields:
- #
- # attr:: Returns the name attributes. Each name attribute is a symbol
- # capitalized by String#capitalize, such as :Noselect (not :NoSelect).
- #
- # delim:: Returns the hierarchy delimiter
- #
- # name:: Returns the mailbox name.
- #
- MailboxList = Struct.new(:attr, :delim, :name)
-
- # Net::IMAP::MailboxQuota represents contents of GETQUOTA response.
- # This object can also be a response to GETQUOTAROOT. In the syntax
- # specification below, the delimiter used with the "#" construct is a
- # single space (SPACE).
- #
- # quota_list ::= "(" #quota_resource ")"
- #
- # quota_resource ::= atom SPACE number SPACE number
- #
- # quota_response ::= "QUOTA" SPACE astring SPACE quota_list
- #
- # ==== Fields:
- #
- # mailbox:: The mailbox with the associated quota.
- #
- # usage:: Current storage usage of mailbox.
- #
- # quota:: Quota limit imposed on mailbox.
- #
- MailboxQuota = Struct.new(:mailbox, :usage, :quota)
-
- # Net::IMAP::MailboxQuotaRoot represents part of the GETQUOTAROOT
- # response. (GETQUOTAROOT can also return Net::IMAP::MailboxQuota.)
- #
- # quotaroot_response ::= "QUOTAROOT" SPACE astring *(SPACE astring)
- #
- # ==== Fields:
- #
- # mailbox:: The mailbox with the associated quota.
- #
- # quotaroots:: Zero or more quotaroots that effect the quota on the
- # specified mailbox.
- #
- MailboxQuotaRoot = Struct.new(:mailbox, :quotaroots)
-
- # Net::IMAP::MailboxACLItem represents response from GETACL.
- #
- # acl_data ::= "ACL" SPACE mailbox *(SPACE identifier SPACE rights)
- #
- # identifier ::= astring
- #
- # rights ::= astring
- #
- # ==== Fields:
- #
- # user:: Login name that has certain rights to the mailbox
- # that was specified with the getacl command.
- #
- # rights:: The access rights the indicated user has to the
- # mailbox.
- #
- MailboxACLItem = Struct.new(:user, :rights, :mailbox)
-
- # Net::IMAP::StatusData represents contents of the STATUS response.
- #
- # ==== Fields:
- #
- # mailbox:: Returns the mailbox name.
- #
- # attr:: Returns a hash. Each key is one of "MESSAGES", "RECENT", "UIDNEXT",
- # "UIDVALIDITY", "UNSEEN". Each value is a number.
- #
- StatusData = Struct.new(:mailbox, :attr)
-
- # Net::IMAP::FetchData represents contents of the FETCH response.
- #
- # ==== Fields:
- #
- # seqno:: Returns the message sequence number.
- # (Note: not the unique identifier, even for the UID command response.)
- #
- # attr:: Returns a hash. Each key is a data item name, and each value is
- # its value.
- #
- # The current data items are:
- #
- # [BODY]
- # A form of BODYSTRUCTURE without extension data.
- # [BODY[<section>]<<origin_octet>>]
- # A string expressing the body contents of the specified section.
- # [BODYSTRUCTURE]
- # An object that describes the [MIME-IMB] body structure of a message.
- # See Net::IMAP::BodyTypeBasic, Net::IMAP::BodyTypeText,
- # Net::IMAP::BodyTypeMessage, Net::IMAP::BodyTypeMultipart.
- # [ENVELOPE]
- # A Net::IMAP::Envelope object that describes the envelope
- # structure of a message.
- # [FLAGS]
- # A array of flag symbols that are set for this message. flag symbols
- # are capitalized by String#capitalize.
- # [INTERNALDATE]
- # A string representing the internal date of the message.
- # [RFC822]
- # Equivalent to BODY[].
- # [RFC822.HEADER]
- # Equivalent to BODY.PEEK[HEADER].
- # [RFC822.SIZE]
- # A number expressing the [RFC-822] size of the message.
- # [RFC822.TEXT]
- # Equivalent to BODY[TEXT].
- # [UID]
- # A number expressing the unique identifier of the message.
- #
- FetchData = Struct.new(:seqno, :attr)
-
- # Net::IMAP::Envelope represents envelope structures of messages.
- #
- # ==== Fields:
- #
- # date:: Returns a string that represents the date.
- #
- # subject:: Returns a string that represents the subject.
- #
- # from:: Returns an array of Net::IMAP::Address that represents the from.
- #
- # sender:: Returns an array of Net::IMAP::Address that represents the sender.
- #
- # reply_to:: Returns an array of Net::IMAP::Address that represents the reply-to.
- #
- # to:: Returns an array of Net::IMAP::Address that represents the to.
- #
- # cc:: Returns an array of Net::IMAP::Address that represents the cc.
- #
- # bcc:: Returns an array of Net::IMAP::Address that represents the bcc.
- #
- # in_reply_to:: Returns a string that represents the in-reply-to.
- #
- # message_id:: Returns a string that represents the message-id.
- #
- Envelope = Struct.new(:date, :subject, :from, :sender, :reply_to,
- :to, :cc, :bcc, :in_reply_to, :message_id)
-
- #
- # Net::IMAP::Address represents electronic mail addresses.
- #
- # ==== Fields:
- #
- # name:: Returns the phrase from [RFC-822] mailbox.
- #
- # route:: Returns the route from [RFC-822] route-addr.
- #
- # mailbox:: nil indicates end of [RFC-822] group.
- # If non-nil and host is nil, returns [RFC-822] group name.
- # Otherwise, returns [RFC-822] local-part
- #
- # host:: nil indicates [RFC-822] group syntax.
- # Otherwise, returns [RFC-822] domain name.
- #
- Address = Struct.new(:name, :route, :mailbox, :host)
-
- #
- # Net::IMAP::ContentDisposition represents Content-Disposition fields.
- #
- # ==== Fields:
- #
- # dsp_type:: Returns the disposition type.
- #
- # param:: Returns a hash that represents parameters of the Content-Disposition
- # field.
- #
- ContentDisposition = Struct.new(:dsp_type, :param)
-
- # Net::IMAP::ThreadMember represents a thread-node returned
- # by Net::IMAP#thread
- #
- # ==== Fields:
- #
- # seqno:: The sequence number of this message.
- #
- # children:: an array of Net::IMAP::ThreadMember objects for mail
- # items that are children of this in the thread.
- #
- ThreadMember = Struct.new(:seqno, :children)
-
- # Net::IMAP::BodyTypeBasic represents basic body structures of messages.
- #
- # ==== Fields:
- #
- # media_type:: Returns the content media type name as defined in [MIME-IMB].
- #
- # subtype:: Returns the content subtype name as defined in [MIME-IMB].
- #
- # param:: Returns a hash that represents parameters as defined in [MIME-IMB].
- #
- # content_id:: Returns a string giving the content id as defined in [MIME-IMB].
- #
- # description:: Returns a string giving the content description as defined in
- # [MIME-IMB].
- #
- # encoding:: Returns a string giving the content transfer encoding as defined in
- # [MIME-IMB].
- #
- # size:: Returns a number giving the size of the body in octets.
- #
- # md5:: Returns a string giving the body MD5 value as defined in [MD5].
- #
- # disposition:: Returns a Net::IMAP::ContentDisposition object giving
- # the content disposition.
- #
- # language:: Returns a string or an array of strings giving the body
- # language value as defined in [LANGUAGE-TAGS].
- #
- # extension:: Returns extension data.
- #
- # multipart?:: Returns false.
- #
- class BodyTypeBasic < Struct.new(:media_type, :subtype,
- :param, :content_id,
- :description, :encoding, :size,
- :md5, :disposition, :language,
- :extension)
- def multipart?
- return false
- end
-
- # Obsolete: use +subtype+ instead. Calling this will
- # generate a warning message to +stderr+, then return
- # the value of +subtype+.
- def media_subtype
- $stderr.printf("warning: media_subtype is obsolete.\n")
- $stderr.printf(" use subtype instead.\n")
- return subtype
- end
- end
-
- # Net::IMAP::BodyTypeText represents TEXT body structures of messages.
- #
- # ==== Fields:
- #
- # lines:: Returns the size of the body in text lines.
- #
- # And Net::IMAP::BodyTypeText has all fields of Net::IMAP::BodyTypeBasic.
- #
- class BodyTypeText < Struct.new(:media_type, :subtype,
- :param, :content_id,
- :description, :encoding, :size,
- :lines,
- :md5, :disposition, :language,
- :extension)
- def multipart?
- return false
- end
-
- # Obsolete: use +subtype+ instead. Calling this will
- # generate a warning message to +stderr+, then return
- # the value of +subtype+.
- def media_subtype
- $stderr.printf("warning: media_subtype is obsolete.\n")
- $stderr.printf(" use subtype instead.\n")
- return subtype
- end
- end
-
- # Net::IMAP::BodyTypeMessage represents MESSAGE/RFC822 body structures of messages.
- #
- # ==== Fields:
- #
- # envelope:: Returns a Net::IMAP::Envelope giving the envelope structure.
- #
- # body:: Returns an object giving the body structure.
- #
- # And Net::IMAP::BodyTypeMessage has all methods of Net::IMAP::BodyTypeText.
- #
- class BodyTypeMessage < Struct.new(:media_type, :subtype,
- :param, :content_id,
- :description, :encoding, :size,
- :envelope, :body, :lines,
- :md5, :disposition, :language,
- :extension)
- def multipart?
- return false
- end
-
- # Obsolete: use +subtype+ instead. Calling this will
- # generate a warning message to +stderr+, then return
- # the value of +subtype+.
- def media_subtype
- $stderr.printf("warning: media_subtype is obsolete.\n")
- $stderr.printf(" use subtype instead.\n")
- return subtype
- end
- end
-
- # Net::IMAP::BodyTypeMultipart represents multipart body structures
- # of messages.
- #
- # ==== Fields:
- #
- # media_type:: Returns the content media type name as defined in [MIME-IMB].
- #
- # subtype:: Returns the content subtype name as defined in [MIME-IMB].
- #
- # parts:: Returns multiple parts.
- #
- # param:: Returns a hash that represents parameters as defined in [MIME-IMB].
- #
- # disposition:: Returns a Net::IMAP::ContentDisposition object giving
- # the content disposition.
- #
- # language:: Returns a string or an array of strings giving the body
- # language value as defined in [LANGUAGE-TAGS].
- #
- # extension:: Returns extension data.
- #
- # multipart?:: Returns true.
- #
- class BodyTypeMultipart < Struct.new(:media_type, :subtype,
- :parts,
- :param, :disposition, :language,
- :extension)
- def multipart?
- return true
- end
-
- # Obsolete: use +subtype+ instead. Calling this will
- # generate a warning message to +stderr+, then return
- # the value of +subtype+.
- def media_subtype
- $stderr.printf("warning: media_subtype is obsolete.\n")
- $stderr.printf(" use subtype instead.\n")
- return subtype
- end
- end
-
- class ResponseParser # :nodoc:
- def initialize
- @str = nil
- @pos = nil
- @lex_state = nil
- @token = nil
- @flag_symbols = {}
- end
-
- def parse(str)
- @str = str
- @pos = 0
- @lex_state = EXPR_BEG
- @token = nil
- return response
- end
-
- private
-
- EXPR_BEG = :EXPR_BEG
- EXPR_DATA = :EXPR_DATA
- EXPR_TEXT = :EXPR_TEXT
- EXPR_RTEXT = :EXPR_RTEXT
- EXPR_CTEXT = :EXPR_CTEXT
-
- T_SPACE = :SPACE
- T_NIL = :NIL
- T_NUMBER = :NUMBER
- T_ATOM = :ATOM
- T_QUOTED = :QUOTED
- T_LPAR = :LPAR
- T_RPAR = :RPAR
- T_BSLASH = :BSLASH
- T_STAR = :STAR
- T_LBRA = :LBRA
- T_RBRA = :RBRA
- T_LITERAL = :LITERAL
- T_PLUS = :PLUS
- T_PERCENT = :PERCENT
- T_CRLF = :CRLF
- T_EOF = :EOF
- T_TEXT = :TEXT
-
- BEG_REGEXP = /\G(?:\
-(?# 1: SPACE )( +)|\
-(?# 2: NIL )(NIL)(?=[\x80-\xff(){ \x00-\x1f\x7f%*#{'"'}\\\[\]+])|\
-(?# 3: NUMBER )(\d+)(?=[\x80-\xff(){ \x00-\x1f\x7f%*#{'"'}\\\[\]+])|\
-(?# 4: ATOM )([^\x80-\xff(){ \x00-\x1f\x7f%*#{'"'}\\\[\]+]+)|\
-(?# 5: QUOTED )"((?:[^\x00\r\n"\\]|\\["\\])*)"|\
-(?# 6: LPAR )(\()|\
-(?# 7: RPAR )(\))|\
-(?# 8: BSLASH )(\\)|\
-(?# 9: STAR )(\*)|\
-(?# 10: LBRA )(\[)|\
-(?# 11: RBRA )(\])|\
-(?# 12: LITERAL )\{(\d+)\}\r\n|\
-(?# 13: PLUS )(\+)|\
-(?# 14: PERCENT )(%)|\
-(?# 15: CRLF )(\r\n)|\
-(?# 16: EOF )(\z))/ni
-
- DATA_REGEXP = /\G(?:\
-(?# 1: SPACE )( )|\
-(?# 2: NIL )(NIL)|\
-(?# 3: NUMBER )(\d+)|\
-(?# 4: QUOTED )"((?:[^\x00\r\n"\\]|\\["\\])*)"|\
-(?# 5: LITERAL )\{(\d+)\}\r\n|\
-(?# 6: LPAR )(\()|\
-(?# 7: RPAR )(\)))/ni
-
- TEXT_REGEXP = /\G(?:\
-(?# 1: TEXT )([^\x00\r\n]*))/ni
-
- RTEXT_REGEXP = /\G(?:\
-(?# 1: LBRA )(\[)|\
-(?# 2: TEXT )([^\x00\r\n]*))/ni
-
- CTEXT_REGEXP = /\G(?:\
-(?# 1: TEXT )([^\x00\r\n\]]*))/ni
-
- Token = Struct.new(:symbol, :value)
-
- def response
- token = lookahead
- case token.symbol
- when T_PLUS
- result = continue_req
- when T_STAR
- result = response_untagged
- else
- result = response_tagged
- end
- match(T_CRLF)
- match(T_EOF)
- return result
- end
-
- def continue_req
- match(T_PLUS)
- match(T_SPACE)
- return ContinuationRequest.new(resp_text, @str)
- end
-
- def response_untagged
- match(T_STAR)
- match(T_SPACE)
- token = lookahead
- if token.symbol == T_NUMBER
- return numeric_response
- elsif token.symbol == T_ATOM
- case token.value
- when /\A(?:OK|NO|BAD|BYE|PREAUTH)\z/ni
- return response_cond
- when /\A(?:FLAGS)\z/ni
- return flags_response
- when /\A(?:LIST|LSUB|XLIST)\z/ni
- return list_response
- when /\A(?:QUOTA)\z/ni
- return getquota_response
- when /\A(?:QUOTAROOT)\z/ni
- return getquotaroot_response
- when /\A(?:ACL)\z/ni
- return getacl_response
- when /\A(?:SEARCH|SORT)\z/ni
- return search_response
- when /\A(?:THREAD)\z/ni
- return thread_response
- when /\A(?:STATUS)\z/ni
- return status_response
- when /\A(?:CAPABILITY)\z/ni
- return capability_response
- else
- return text_response
- end
- else
- parse_error("unexpected token %s", token.symbol)
- end
- end
-
- def response_tagged
- tag = atom
- match(T_SPACE)
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- return TaggedResponse.new(tag, name, resp_text, @str)
- end
-
- def response_cond
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- return UntaggedResponse.new(name, resp_text, @str)
- end
-
- def numeric_response
- n = number
- match(T_SPACE)
- token = match(T_ATOM)
- name = token.value.upcase
- case name
- when "EXISTS", "RECENT", "EXPUNGE"
- return UntaggedResponse.new(name, n, @str)
- when "FETCH"
- shift_token
- match(T_SPACE)
- data = FetchData.new(n, msg_att)
- return UntaggedResponse.new(name, data, @str)
- end
- end
-
- def msg_att
- match(T_LPAR)
- attr = {}
- while true
- token = lookahead
- case token.symbol
- when T_RPAR
- shift_token
- break
- when T_SPACE
- shift_token
- next
- end
- case token.value
- when /\A(?:ENVELOPE)\z/ni
- name, val = envelope_data
- when /\A(?:FLAGS)\z/ni
- name, val = flags_data
- when /\A(?:INTERNALDATE)\z/ni
- name, val = internaldate_data
- when /\A(?:RFC822(?:\.HEADER|\.TEXT)?)\z/ni
- name, val = rfc822_text
- when /\A(?:RFC822\.SIZE)\z/ni
- name, val = rfc822_size
- when /\A(?:BODY(?:STRUCTURE)?)\z/ni
- name, val = body_data
- when /\A(?:UID)\z/ni
- name, val = uid_data
- else
- parse_error("unknown attribute `%s'", token.value)
- end
- attr[name] = val
- end
- return attr
- end
-
- def envelope_data
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- return name, envelope
- end
-
- def envelope
- @lex_state = EXPR_DATA
- token = lookahead
- if token.symbol == T_NIL
- shift_token
- result = nil
- else
- match(T_LPAR)
- date = nstring
- match(T_SPACE)
- subject = nstring
- match(T_SPACE)
- from = address_list
- match(T_SPACE)
- sender = address_list
- match(T_SPACE)
- reply_to = address_list
- match(T_SPACE)
- to = address_list
- match(T_SPACE)
- cc = address_list
- match(T_SPACE)
- bcc = address_list
- match(T_SPACE)
- in_reply_to = nstring
- match(T_SPACE)
- message_id = nstring
- match(T_RPAR)
- result = Envelope.new(date, subject, from, sender, reply_to,
- to, cc, bcc, in_reply_to, message_id)
- end
- @lex_state = EXPR_BEG
- return result
- end
-
- def flags_data
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- return name, flag_list
- end
-
- def internaldate_data
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- token = match(T_QUOTED)
- return name, token.value
- end
-
- def rfc822_text
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- return name, nstring
- end
-
- def rfc822_size
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- return name, number
- end
-
- def body_data
- token = match(T_ATOM)
- name = token.value.upcase
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- return name, body
- end
- name.concat(section)
- token = lookahead
- if token.symbol == T_ATOM
- name.concat(token.value)
- shift_token
- end
- match(T_SPACE)
- data = nstring
- return name, data
- end
-
- def body
- @lex_state = EXPR_DATA
- token = lookahead
- if token.symbol == T_NIL
- shift_token
- result = nil
- else
- match(T_LPAR)
- token = lookahead
- if token.symbol == T_LPAR
- result = body_type_mpart
- else
- result = body_type_1part
- end
- match(T_RPAR)
- end
- @lex_state = EXPR_BEG
- return result
- end
-
- def body_type_1part
- token = lookahead
- case token.value
- when /\A(?:TEXT)\z/ni
- return body_type_text
- when /\A(?:MESSAGE)\z/ni
- return body_type_msg
- else
- return body_type_basic
- end
- end
-
- def body_type_basic
- mtype, msubtype = media_type
- token = lookahead
- if token.symbol == T_RPAR
- return BodyTypeBasic.new(mtype, msubtype)
- end
- match(T_SPACE)
- param, content_id, desc, enc, size = body_fields
- md5, disposition, language, extension = body_ext_1part
- return BodyTypeBasic.new(mtype, msubtype,
- param, content_id,
- desc, enc, size,
- md5, disposition, language, extension)
- end
-
- def body_type_text
- mtype, msubtype = media_type
- match(T_SPACE)
- param, content_id, desc, enc, size = body_fields
- match(T_SPACE)
- lines = number
- md5, disposition, language, extension = body_ext_1part
- return BodyTypeText.new(mtype, msubtype,
- param, content_id,
- desc, enc, size,
- lines,
- md5, disposition, language, extension)
- end
-
- def body_type_msg
- mtype, msubtype = media_type
- match(T_SPACE)
- param, content_id, desc, enc, size = body_fields
- match(T_SPACE)
- env = envelope
- match(T_SPACE)
- b = body
- match(T_SPACE)
- lines = number
- md5, disposition, language, extension = body_ext_1part
- return BodyTypeMessage.new(mtype, msubtype,
- param, content_id,
- desc, enc, size,
- env, b, lines,
- md5, disposition, language, extension)
- end
-
- def body_type_mpart
- parts = []
- while true
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- break
- end
- parts.push(body)
- end
- mtype = "MULTIPART"
- msubtype = case_insensitive_string
- param, disposition, language, extension = body_ext_mpart
- return BodyTypeMultipart.new(mtype, msubtype, parts,
- param, disposition, language,
- extension)
- end
-
- def media_type
- mtype = case_insensitive_string
- match(T_SPACE)
- msubtype = case_insensitive_string
- return mtype, msubtype
- end
-
- def body_fields
- param = body_fld_param
- match(T_SPACE)
- content_id = nstring
- match(T_SPACE)
- desc = nstring
- match(T_SPACE)
- enc = case_insensitive_string
- match(T_SPACE)
- size = number
- return param, content_id, desc, enc, size
- end
-
- def body_fld_param
- token = lookahead
- if token.symbol == T_NIL
- shift_token
- return nil
- end
- match(T_LPAR)
- param = {}
- while true
- token = lookahead
- case token.symbol
- when T_RPAR
- shift_token
- break
- when T_SPACE
- shift_token
- end
- name = case_insensitive_string
- match(T_SPACE)
- val = string
- param[name] = val
- end
- return param
- end
-
- def body_ext_1part
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- else
- return nil
- end
- md5 = nstring
-
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- else
- return md5
- end
- disposition = body_fld_dsp
-
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- else
- return md5, disposition
- end
- language = body_fld_lang
-
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- else
- return md5, disposition, language
- end
-
- extension = body_extensions
- return md5, disposition, language, extension
- end
-
- def body_ext_mpart
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- else
- return nil
- end
- param = body_fld_param
-
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- else
- return param
- end
- disposition = body_fld_dsp
- match(T_SPACE)
- language = body_fld_lang
-
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- else
- return param, disposition, language
- end
-
- extension = body_extensions
- return param, disposition, language, extension
- end
-
- def body_fld_dsp
- token = lookahead
- if token.symbol == T_NIL
- shift_token
- return nil
- end
- match(T_LPAR)
- dsp_type = case_insensitive_string
- match(T_SPACE)
- param = body_fld_param
- match(T_RPAR)
- return ContentDisposition.new(dsp_type, param)
- end
-
- def body_fld_lang
- token = lookahead
- if token.symbol == T_LPAR
- shift_token
- result = []
- while true
- token = lookahead
- case token.symbol
- when T_RPAR
- shift_token
- return result
- when T_SPACE
- shift_token
- end
- result.push(case_insensitive_string)
- end
- else
- lang = nstring
- if lang
- return lang.upcase
- else
- return lang
- end
- end
- end
-
- def body_extensions
- result = []
- while true
- token = lookahead
- case token.symbol
- when T_RPAR
- return result
- when T_SPACE
- shift_token
- end
- result.push(body_extension)
- end
- end
-
- def body_extension
- token = lookahead
- case token.symbol
- when T_LPAR
- shift_token
- result = body_extensions
- match(T_RPAR)
- return result
- when T_NUMBER
- return number
- else
- return nstring
- end
- end
-
- def section
- str = ""
- token = match(T_LBRA)
- str.concat(token.value)
- token = match(T_ATOM, T_NUMBER, T_RBRA)
- if token.symbol == T_RBRA
- str.concat(token.value)
- return str
- end
- str.concat(token.value)
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- str.concat(token.value)
- token = match(T_LPAR)
- str.concat(token.value)
- while true
- token = lookahead
- case token.symbol
- when T_RPAR
- str.concat(token.value)
- shift_token
- break
- when T_SPACE
- shift_token
- str.concat(token.value)
- end
- str.concat(format_string(astring))
- end
- end
- token = match(T_RBRA)
- str.concat(token.value)
- return str
- end
-
- def format_string(str)
- case str
- when ""
- return '""'
- when /[\x80-\xff\r\n]/n
- # literal
- return "{" + str.bytesize.to_s + "}" + CRLF + str
- when /[(){ \x00-\x1f\x7f%*"\\]/n
- # quoted string
- return '"' + str.gsub(/["\\]/n, "\\\\\\&") + '"'
- else
- # atom
- return str
- end
- end
-
- def uid_data
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- return name, number
- end
-
- def text_response
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- @lex_state = EXPR_TEXT
- token = match(T_TEXT)
- @lex_state = EXPR_BEG
- return UntaggedResponse.new(name, token.value)
- end
-
- def flags_response
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- return UntaggedResponse.new(name, flag_list, @str)
- end
-
- def list_response
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- return UntaggedResponse.new(name, mailbox_list, @str)
- end
-
- def mailbox_list
- attr = flag_list
- match(T_SPACE)
- token = match(T_QUOTED, T_NIL)
- if token.symbol == T_NIL
- delim = nil
- else
- delim = token.value
- end
- match(T_SPACE)
- name = astring
- return MailboxList.new(attr, delim, name)
- end
-
- def getquota_response
- # If quota never established, get back
- # `NO Quota root does not exist'.
- # If quota removed, get `()' after the
- # folder spec with no mention of `STORAGE'.
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- mailbox = astring
- match(T_SPACE)
- match(T_LPAR)
- token = lookahead
- case token.symbol
- when T_RPAR
- shift_token
- data = MailboxQuota.new(mailbox, nil, nil)
- return UntaggedResponse.new(name, data, @str)
- when T_ATOM
- shift_token
- match(T_SPACE)
- token = match(T_NUMBER)
- usage = token.value
- match(T_SPACE)
- token = match(T_NUMBER)
- quota = token.value
- match(T_RPAR)
- data = MailboxQuota.new(mailbox, usage, quota)
- return UntaggedResponse.new(name, data, @str)
- else
- parse_error("unexpected token %s", token.symbol)
- end
- end
-
- def getquotaroot_response
- # Similar to getquota, but only admin can use getquota.
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- mailbox = astring
- quotaroots = []
- while true
- token = lookahead
- break unless token.symbol == T_SPACE
- shift_token
- quotaroots.push(astring)
- end
- data = MailboxQuotaRoot.new(mailbox, quotaroots)
- return UntaggedResponse.new(name, data, @str)
- end
-
- def getacl_response
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- mailbox = astring
- data = []
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- while true
- token = lookahead
- case token.symbol
- when T_CRLF
- break
- when T_SPACE
- shift_token
- end
- user = astring
- match(T_SPACE)
- rights = astring
- data.push(MailboxACLItem.new(user, rights, mailbox))
- end
- end
- return UntaggedResponse.new(name, data, @str)
- end
-
- def search_response
- token = match(T_ATOM)
- name = token.value.upcase
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- data = []
- while true
- token = lookahead
- case token.symbol
- when T_CRLF
- break
- when T_SPACE
- shift_token
- else
- data.push(number)
- end
- end
- else
- data = []
- end
- return UntaggedResponse.new(name, data, @str)
- end
-
- def thread_response
- token = match(T_ATOM)
- name = token.value.upcase
- token = lookahead
-
- if token.symbol == T_SPACE
- threads = []
-
- while true
- shift_token
- token = lookahead
-
- case token.symbol
- when T_LPAR
- threads << thread_branch(token)
- when T_CRLF
- break
- end
- end
- else
- # no member
- threads = []
- end
-
- return UntaggedResponse.new(name, threads, @str)
- end
-
- def thread_branch(token)
- rootmember = nil
- lastmember = nil
-
- while true
- shift_token # ignore first T_LPAR
- token = lookahead
-
- case token.symbol
- when T_NUMBER
- # new member
- newmember = ThreadMember.new(number, [])
- if rootmember.nil?
- rootmember = newmember
- else
- lastmember.children << newmember
- end
- lastmember = newmember
- when T_SPACE
- # do nothing
- when T_LPAR
- if rootmember.nil?
- # dummy member
- lastmember = rootmember = ThreadMember.new(nil, [])
- end
-
- lastmember.children << thread_branch(token)
- when T_RPAR
- break
- end
- end
-
- return rootmember
- end
-
- def status_response
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- mailbox = astring
- match(T_SPACE)
- match(T_LPAR)
- attr = {}
- while true
- token = lookahead
- case token.symbol
- when T_RPAR
- shift_token
- break
- when T_SPACE
- shift_token
- end
- token = match(T_ATOM)
- key = token.value.upcase
- match(T_SPACE)
- val = number
- attr[key] = val
- end
- data = StatusData.new(mailbox, attr)
- return UntaggedResponse.new(name, data, @str)
- end
-
- def capability_response
- token = match(T_ATOM)
- name = token.value.upcase
- match(T_SPACE)
- data = []
- while true
- token = lookahead
- case token.symbol
- when T_CRLF
- break
- when T_SPACE
- shift_token
- end
- data.push(atom.upcase)
- end
- return UntaggedResponse.new(name, data, @str)
- end
-
- def resp_text
- @lex_state = EXPR_RTEXT
- token = lookahead
- if token.symbol == T_LBRA
- code = resp_text_code
- else
- code = nil
- end
- token = match(T_TEXT)
- @lex_state = EXPR_BEG
- return ResponseText.new(code, token.value)
- end
-
- def resp_text_code
- @lex_state = EXPR_BEG
- match(T_LBRA)
- token = match(T_ATOM)
- name = token.value.upcase
- case name
- when /\A(?:ALERT|PARSE|READ-ONLY|READ-WRITE|TRYCREATE|NOMODSEQ)\z/n
- result = ResponseCode.new(name, nil)
- when /\A(?:PERMANENTFLAGS)\z/n
- match(T_SPACE)
- result = ResponseCode.new(name, flag_list)
- when /\A(?:UIDVALIDITY|UIDNEXT|UNSEEN)\z/n
- match(T_SPACE)
- result = ResponseCode.new(name, number)
- else
- token = lookahead
- if token.symbol == T_SPACE
- shift_token
- @lex_state = EXPR_CTEXT
- token = match(T_TEXT)
- @lex_state = EXPR_BEG
- result = ResponseCode.new(name, token.value)
- else
- result = ResponseCode.new(name, nil)
- end
- end
- match(T_RBRA)
- @lex_state = EXPR_RTEXT
- return result
- end
-
- def address_list
- token = lookahead
- if token.symbol == T_NIL
- shift_token
- return nil
- else
- result = []
- match(T_LPAR)
- while true
- token = lookahead
- case token.symbol
- when T_RPAR
- shift_token
- break
- when T_SPACE
- shift_token
- end
- result.push(address)
- end
- return result
- end
- end
-
- ADDRESS_REGEXP = /\G\
-(?# 1: NAME )(?:NIL|"((?:[^\x80-\xff\x00\r\n"\\]|\\["\\])*)") \
-(?# 2: ROUTE )(?:NIL|"((?:[^\x80-\xff\x00\r\n"\\]|\\["\\])*)") \
-(?# 3: MAILBOX )(?:NIL|"((?:[^\x80-\xff\x00\r\n"\\]|\\["\\])*)") \
-(?# 4: HOST )(?:NIL|"((?:[^\x80-\xff\x00\r\n"\\]|\\["\\])*)")\
-\)/ni
-
- def address
- match(T_LPAR)
- if @str.index(ADDRESS_REGEXP, @pos)
- # address does not include literal.
- @pos = $~.end(0)
- name = $1
- route = $2
- mailbox = $3
- host = $4
- for s in [name, route, mailbox, host]
- if s
- s.gsub!(/\\(["\\])/n, "\\1")
- end
- end
- else
- name = nstring
- match(T_SPACE)
- route = nstring
- match(T_SPACE)
- mailbox = nstring
- match(T_SPACE)
- host = nstring
- match(T_RPAR)
- end
- return Address.new(name, route, mailbox, host)
- end
-
-# def flag_list
-# result = []
-# match(T_LPAR)
-# while true
-# token = lookahead
-# case token.symbol
-# when T_RPAR
-# shift_token
-# break
-# when T_SPACE
-# shift_token
-# end
-# result.push(flag)
-# end
-# return result
-# end
-
-# def flag
-# token = lookahead
-# if token.symbol == T_BSLASH
-# shift_token
-# token = lookahead
-# if token.symbol == T_STAR
-# shift_token
-# return token.value.intern
-# else
-# return atom.intern
-# end
-# else
-# return atom
-# end
-# end
-
- FLAG_REGEXP = /\
-(?# FLAG )\\([^\x80-\xff(){ \x00-\x1f\x7f%"\\]+)|\
-(?# ATOM )([^\x80-\xff(){ \x00-\x1f\x7f%*"\\]+)/n
-
- def flag_list
- if @str.index(/\(([^)]*)\)/ni, @pos)
- @pos = $~.end(0)
- return $1.scan(FLAG_REGEXP).collect { |flag, atom|
- if atom
- atom
- else
- symbol = flag.capitalize.untaint.intern
- @flag_symbols[symbol] = true
- if @flag_symbols.length > IMAP.max_flag_count
- raise FlagCountError, "number of flag symbols exceeded"
- end
- symbol
- end
- }
- else
- parse_error("invalid flag list")
- end
- end
-
- def nstring
- token = lookahead
- if token.symbol == T_NIL
- shift_token
- return nil
- else
- return string
- end
- end
-
- def astring
- token = lookahead
- if string_token?(token)
- return string
- else
- return atom
- end
- end
-
- def string
- token = lookahead
- if token.symbol == T_NIL
- shift_token
- return nil
- end
- token = match(T_QUOTED, T_LITERAL)
- return token.value
- end
-
- STRING_TOKENS = [T_QUOTED, T_LITERAL, T_NIL]
-
- def string_token?(token)
- return STRING_TOKENS.include?(token.symbol)
- end
-
- def case_insensitive_string
- token = lookahead
- if token.symbol == T_NIL
- shift_token
- return nil
- end
- token = match(T_QUOTED, T_LITERAL)
- return token.value.upcase
- end
-
- def atom
- result = ""
- while true
- token = lookahead
- if atom_token?(token)
- result.concat(token.value)
- shift_token
- else
- if result.empty?
- parse_error("unexpected token %s", token.symbol)
- else
- return result
- end
- end
- end
- end
-
- ATOM_TOKENS = [
- T_ATOM,
- T_NUMBER,
- T_NIL,
- T_LBRA,
- T_RBRA,
- T_PLUS
- ]
-
- def atom_token?(token)
- return ATOM_TOKENS.include?(token.symbol)
- end
-
- def number
- token = lookahead
- if token.symbol == T_NIL
- shift_token
- return nil
- end
- token = match(T_NUMBER)
- return token.value.to_i
- end
-
- def nil_atom
- match(T_NIL)
- return nil
- end
-
- def match(*args)
- token = lookahead
- unless args.include?(token.symbol)
- parse_error('unexpected token %s (expected %s)',
- token.symbol.id2name,
- args.collect {|i| i.id2name}.join(" or "))
- end
- shift_token
- return token
- end
-
- def lookahead
- unless @token
- @token = next_token
- end
- return @token
- end
-
- def shift_token
- @token = nil
- end
-
- def next_token
- case @lex_state
- when EXPR_BEG
- if @str.index(BEG_REGEXP, @pos)
- @pos = $~.end(0)
- if $1
- return Token.new(T_SPACE, $+)
- elsif $2
- return Token.new(T_NIL, $+)
- elsif $3
- return Token.new(T_NUMBER, $+)
- elsif $4
- return Token.new(T_ATOM, $+)
- elsif $5
- return Token.new(T_QUOTED,
- $+.gsub(/\\(["\\])/n, "\\1"))
- elsif $6
- return Token.new(T_LPAR, $+)
- elsif $7
- return Token.new(T_RPAR, $+)
- elsif $8
- return Token.new(T_BSLASH, $+)
- elsif $9
- return Token.new(T_STAR, $+)
- elsif $10
- return Token.new(T_LBRA, $+)
- elsif $11
- return Token.new(T_RBRA, $+)
- elsif $12
- len = $+.to_i
- val = @str[@pos, len]
- @pos += len
- return Token.new(T_LITERAL, val)
- elsif $13
- return Token.new(T_PLUS, $+)
- elsif $14
- return Token.new(T_PERCENT, $+)
- elsif $15
- return Token.new(T_CRLF, $+)
- elsif $16
- return Token.new(T_EOF, $+)
- else
- parse_error("[Net::IMAP BUG] BEG_REGEXP is invalid")
- end
- else
- @str.index(/\S*/n, @pos)
- parse_error("unknown token - %s", $&.dump)
- end
- when EXPR_DATA
- if @str.index(DATA_REGEXP, @pos)
- @pos = $~.end(0)
- if $1
- return Token.new(T_SPACE, $+)
- elsif $2
- return Token.new(T_NIL, $+)
- elsif $3
- return Token.new(T_NUMBER, $+)
- elsif $4
- return Token.new(T_QUOTED,
- $+.gsub(/\\(["\\])/n, "\\1"))
- elsif $5
- len = $+.to_i
- val = @str[@pos, len]
- @pos += len
- return Token.new(T_LITERAL, val)
- elsif $6
- return Token.new(T_LPAR, $+)
- elsif $7
- return Token.new(T_RPAR, $+)
- else
- parse_error("[Net::IMAP BUG] DATA_REGEXP is invalid")
- end
- else
- @str.index(/\S*/n, @pos)
- parse_error("unknown token - %s", $&.dump)
- end
- when EXPR_TEXT
- if @str.index(TEXT_REGEXP, @pos)
- @pos = $~.end(0)
- if $1
- return Token.new(T_TEXT, $+)
- else
- parse_error("[Net::IMAP BUG] TEXT_REGEXP is invalid")
- end
- else
- @str.index(/\S*/n, @pos)
- parse_error("unknown token - %s", $&.dump)
- end
- when EXPR_RTEXT
- if @str.index(RTEXT_REGEXP, @pos)
- @pos = $~.end(0)
- if $1
- return Token.new(T_LBRA, $+)
- elsif $2
- return Token.new(T_TEXT, $+)
- else
- parse_error("[Net::IMAP BUG] RTEXT_REGEXP is invalid")
- end
- else
- @str.index(/\S*/n, @pos)
- parse_error("unknown token - %s", $&.dump)
- end
- when EXPR_CTEXT
- if @str.index(CTEXT_REGEXP, @pos)
- @pos = $~.end(0)
- if $1
- return Token.new(T_TEXT, $+)
- else
- parse_error("[Net::IMAP BUG] CTEXT_REGEXP is invalid")
- end
- else
- @str.index(/\S*/n, @pos) #/
- parse_error("unknown token - %s", $&.dump)
- end
- else
- parse_error("invalid @lex_state - %s", @lex_state.inspect)
- end
- end
-
- def parse_error(fmt, *args)
- if IMAP.debug
- $stderr.printf("@str: %s\n", @str.dump)
- $stderr.printf("@pos: %d\n", @pos)
- $stderr.printf("@lex_state: %s\n", @lex_state)
- if @token
- $stderr.printf("@token.symbol: %s\n", @token.symbol)
- $stderr.printf("@token.value: %s\n", @token.value.inspect)
- end
- end
- raise ResponseParseError, format(fmt, *args)
- end
- end
-
- # Authenticator for the "LOGIN" authentication type. See
- # #authenticate().
- class LoginAuthenticator
- def process(data)
- case @state
- when STATE_USER
- @state = STATE_PASSWORD
- return @user
- when STATE_PASSWORD
- return @password
- end
- end
-
- private
-
- STATE_USER = :USER
- STATE_PASSWORD = :PASSWORD
-
- def initialize(user, password)
- @user = user
- @password = password
- @state = STATE_USER
- end
- end
- add_authenticator "LOGIN", LoginAuthenticator
-
- # Authenticator for the "PLAIN" authentication type. See
- # #authenticate().
- class PlainAuthenticator
- def process(data)
- return "\0#{@user}\0#{@password}"
- end
-
- private
-
- def initialize(user, password)
- @user = user
- @password = password
- end
- end
- add_authenticator "PLAIN", PlainAuthenticator
-
- # Authenticator for the "CRAM-MD5" authentication type. See
- # #authenticate().
- class CramMD5Authenticator
- def process(challenge)
- digest = hmac_md5(challenge, @password)
- return @user + " " + digest
- end
-
- private
-
- def initialize(user, password)
- @user = user
- @password = password
- end
-
- def hmac_md5(text, key)
- if key.length > 64
- key = Digest::MD5.digest(key)
- end
-
- k_ipad = key + "\0" * (64 - key.length)
- k_opad = key + "\0" * (64 - key.length)
- for i in 0..63
- k_ipad[i] = (k_ipad[i].ord ^ 0x36).chr
- k_opad[i] = (k_opad[i].ord ^ 0x5c).chr
- end
-
- digest = Digest::MD5.digest(k_ipad + text)
-
- return Digest::MD5.hexdigest(k_opad + digest)
- end
- end
- add_authenticator "CRAM-MD5", CramMD5Authenticator
-
- # Authenticator for the "DIGEST-MD5" authentication type. See
- # #authenticate().
- class DigestMD5Authenticator
- def process(challenge)
- case @stage
- when STAGE_ONE
- @stage = STAGE_TWO
- sparams = {}
- c = StringScanner.new(challenge)
- while c.scan(/(?:\s*,)?\s*(\w+)=("(?:[^\\"]+|\\.)*"|[^,]+)\s*/)
- k, v = c[1], c[2]
- if v =~ /^"(.*)"$/
- v = $1
- if v =~ /,/
- v = v.split(',')
- end
- end
- sparams[k] = v
- end
-
- raise DataFormatError, "Bad Challenge: '#{challenge}'" unless c.rest.size == 0
- raise Error, "Server does not support auth (qop = #{sparams['qop'].join(',')})" unless sparams['qop'].include?("auth")
-
- response = {
- :nonce => sparams['nonce'],
- :username => @user,
- :realm => sparams['realm'],
- :cnonce => Digest::MD5.hexdigest("%.15f:%.15f:%d" % [Time.now.to_f, rand, Process.pid.to_s]),
- :'digest-uri' => 'imap/' + sparams['realm'],
- :qop => 'auth',
- :maxbuf => 65535,
- :nc => "%08d" % nc(sparams['nonce']),
- :charset => sparams['charset'],
- }
-
- response[:authzid] = @authname unless @authname.nil?
-
- # now, the real thing
- a0 = Digest::MD5.digest( [ response.values_at(:username, :realm), @password ].join(':') )
-
- a1 = [ a0, response.values_at(:nonce,:cnonce) ].join(':')
- a1 << ':' + response[:authzid] unless response[:authzid].nil?
-
- a2 = "AUTHENTICATE:" + response[:'digest-uri']
- a2 << ":00000000000000000000000000000000" if response[:qop] and response[:qop] =~ /^auth-(?:conf|int)$/
-
- response[:response] = Digest::MD5.hexdigest(
- [
- Digest::MD5.hexdigest(a1),
- response.values_at(:nonce, :nc, :cnonce, :qop),
- Digest::MD5.hexdigest(a2)
- ].join(':')
- )
-
- return response.keys.map {|key| qdval(key.to_s, response[key]) }.join(',')
- when STAGE_TWO
- @stage = nil
- # if at the second stage, return an empty string
- if challenge =~ /rspauth=/
- return ''
- else
- raise ResponseParseError, challenge
- end
- else
- raise ResponseParseError, challenge
- end
- end
-
- def initialize(user, password, authname = nil)
- @user, @password, @authname = user, password, authname
- @nc, @stage = {}, STAGE_ONE
- end
-
- private
-
- STAGE_ONE = :stage_one
- STAGE_TWO = :stage_two
-
- def nc(nonce)
- if @nc.has_key? nonce
- @nc[nonce] = @nc[nonce] + 1
- else
- @nc[nonce] = 1
- end
- return @nc[nonce]
- end
-
- # some responses need quoting
- def qdval(k, v)
- return if k.nil? or v.nil?
- if %w"username authzid realm nonce cnonce digest-uri qop".include? k
- v.gsub!(/([\\"])/, "\\\1")
- return '%s="%s"' % [k, v]
- else
- return '%s=%s' % [k, v]
- end
- end
- end
- add_authenticator "DIGEST-MD5", DigestMD5Authenticator
-
- # Superclass of IMAP errors.
- class Error < StandardError
- end
-
- # Error raised when data is in the incorrect format.
- class DataFormatError < Error
- end
-
- # Error raised when a response from the server is non-parseable.
- class ResponseParseError < Error
- end
-
- # Superclass of all errors used to encapsulate "fail" responses
- # from the server.
- class ResponseError < Error
-
- # The response that caused this error
- attr_accessor :response
-
- def initialize(response)
- @response = response
-
- super @response.data.text
- end
-
- end
-
- # Error raised upon a "NO" response from the server, indicating
- # that the client command could not be completed successfully.
- class NoResponseError < ResponseError
- end
-
- # Error raised upon a "BAD" response from the server, indicating
- # that the client command violated the IMAP protocol, or an internal
- # server failure has occurred.
- class BadResponseError < ResponseError
- end
-
- # Error raised upon a "BYE" response from the server, indicating
- # that the client is not being allowed to login, or has been timed
- # out due to inactivity.
- class ByeResponseError < ResponseError
- end
-
- # Error raised when too many flags are interned to symbols.
- class FlagCountError < Error
- end
- end
-end
-
-if __FILE__ == $0
- # :enddoc:
- require "getoptlong"
-
- $stdout.sync = true
- $port = nil
- $user = ENV["USER"] || ENV["LOGNAME"]
- $auth = "login"
- $ssl = false
- $starttls = false
-
- def usage
- <<EOF
-usage: #{$0} [options] <host>
-
- --help print this message
- --port=PORT specifies port
- --user=USER specifies user
- --auth=AUTH specifies auth type
- --starttls use starttls
- --ssl use ssl
-EOF
- end
-
- begin
- require 'io/console'
- rescue LoadError
- def _noecho(&block)
- system("stty", "-echo")
- begin
- yield STDIN
- ensure
- system("stty", "echo")
- end
- end
- else
- def _noecho(&block)
- STDIN.noecho(&block)
- end
- end
-
- def get_password
- print "password: "
- begin
- return _noecho(&:gets).chomp
- ensure
- puts
- end
- end
-
- def get_command
- printf("%s@%s> ", $user, $host)
- if line = gets
- return line.strip.split(/\s+/)
- else
- return nil
- end
- end
-
- parser = GetoptLong.new
- parser.set_options(['--debug', GetoptLong::NO_ARGUMENT],
- ['--help', GetoptLong::NO_ARGUMENT],
- ['--port', GetoptLong::REQUIRED_ARGUMENT],
- ['--user', GetoptLong::REQUIRED_ARGUMENT],
- ['--auth', GetoptLong::REQUIRED_ARGUMENT],
- ['--starttls', GetoptLong::NO_ARGUMENT],
- ['--ssl', GetoptLong::NO_ARGUMENT])
- begin
- parser.each_option do |name, arg|
- case name
- when "--port"
- $port = arg
- when "--user"
- $user = arg
- when "--auth"
- $auth = arg
- when "--ssl"
- $ssl = true
- when "--starttls"
- $starttls = true
- when "--debug"
- Net::IMAP.debug = true
- when "--help"
- usage
- exit
- end
- end
- rescue
- abort usage
- end
-
- $host = ARGV.shift
- unless $host
- abort usage
- end
-
- imap = Net::IMAP.new($host, :port => $port, :ssl => $ssl)
- begin
- imap.starttls if $starttls
- class << password = method(:get_password)
- alias to_str call
- end
- imap.authenticate($auth, $user, password)
- while true
- cmd, *args = get_command
- break unless cmd
- begin
- case cmd
- when "list"
- for mbox in imap.list("", args[0] || "*")
- if mbox.attr.include?(Net::IMAP::NOSELECT)
- prefix = "!"
- elsif mbox.attr.include?(Net::IMAP::MARKED)
- prefix = "*"
- else
- prefix = " "
- end
- print prefix, mbox.name, "\n"
- end
- when "select"
- imap.select(args[0] || "inbox")
- print "ok\n"
- when "close"
- imap.close
- print "ok\n"
- when "summary"
- unless messages = imap.responses["EXISTS"][-1]
- puts "not selected"
- next
- end
- if messages > 0
- for data in imap.fetch(1..-1, ["ENVELOPE"])
- print data.seqno, ": ", data.attr["ENVELOPE"].subject, "\n"
- end
- else
- puts "no message"
- end
- when "fetch"
- if args[0]
- data = imap.fetch(args[0].to_i, ["RFC822.HEADER", "RFC822.TEXT"])[0]
- puts data.attr["RFC822.HEADER"]
- puts data.attr["RFC822.TEXT"]
- else
- puts "missing argument"
- end
- when "logout", "exit", "quit"
- break
- when "help", "?"
- print <<EOF
-list [pattern] list mailboxes
-select [mailbox] select mailbox
-close close mailbox
-summary display summary
-fetch [msgno] display message
-logout logout
-help, ? display help message
-EOF
- else
- print "unknown command: ", cmd, "\n"
- end
- rescue Net::IMAP::Error
- puts $!
- end
- end
- ensure
- imap.logout
- imap.disconnect
- end
-end
-
diff --git a/ruby_1_9_3/lib/net/pop.rb b/ruby_1_9_3/lib/net/pop.rb
deleted file mode 100644
index ff2d77f72a..0000000000
--- a/ruby_1_9_3/lib/net/pop.rb
+++ /dev/null
@@ -1,1021 +0,0 @@
-# = 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$
-#
-# See Net::POP3 for documentation.
-#
-
-require 'net/protocol'
-require 'digest/md5'
-require 'timeout'
-
-begin
- require "openssl"
-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
-
- # svn revision of this library
- Revision = %q$Revision$.split[1]
-
- #
- # Class Parameters
- #
-
- # returns the port for POP3
- 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
-
- # Constructs proper parameters from arguments
- 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
-
- # returns the SSL Parameters
- #
- # see also POP3.enable_ssl
- def POP3.ssl_params
- return @ssl_params
- end
-
- # returns +true+ if POP3.ssl_params is set
- def POP3.use_ssl?
- return !@ssl_params.nil?
- end
-
- # returns whether verify_mode is enable from POP3.ssl_params
- def POP3.verify
- return @ssl_params[:verify_mode]
- end
-
- # returns the :ca_file or :ca_path from POP3.ssh_params
- 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
-
- # Disable SSL for all new instances.
- 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. The default value is 30 seconds.
- 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. The default value is 60 seconds.
- 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
-
- # internal method for Net::POP3.start
- def do_start(account, password) # :nodoc:
- 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
-
- # Does nothing
- def on_connect # :nodoc:
- 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
-
- # nil's out the:
- # - mails
- # - number counter for mails
- # - number counter for bytes
- # - quits the current command, if any
- def do_finish # :nodoc:
- @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
-
- # Returns the current command.
- #
- # Raises IOError if there is no active socket
- def command # :nodoc:
- 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)
- uidl = command().uidl
- @mails.each {|m| m.uid = uidl[m.number] }
- end
-
- # deguging output for +msg+
- 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
-
- attr_reader :socket
-
- 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
diff --git a/ruby_1_9_3/lib/net/protocol.rb b/ruby_1_9_3/lib/net/protocol.rb
deleted file mode 100644
index f3744661f5..0000000000
--- a/ruby_1_9_3/lib/net/protocol.rb
+++ /dev/null
@@ -1,404 +0,0 @@
-#
-# = net/protocol.rb
-#
-#--
-# Copyright (c) 1999-2004 Yukihiro Matsumoto
-# Copyright (c) 1999-2004 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$
-#++
-#
-# 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
- @continue_timeout = nil
- @debug_output = nil
- @rbuf = ''
- end
-
- attr_reader :io
- attr_accessor :read_timeout
- attr_accessor :continue_timeout
- attr_accessor :debug_output
-
- def inspect
- "#<#{self.class} io=#{@io}>"
- end
-
- def eof?
- @io.eof?
- 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
- begin
- @rbuf << @io.read_nonblock(BUFSIZE)
- rescue IO::WaitReadable
- if IO.select([@io], nil, nil, @read_timeout)
- retry
- else
- raise Timeout::Error
- end
- rescue IO::WaitWritable
- # OpenSSL::Buffering#read_nonblock may fail with IO::WaitWritable.
- # http://www.openssl.org/support/faq.html#PROG10
- if IO.select(nil, [@io], nil, @read_timeout)
- retry
- else
- raise Timeout::Error
- end
- end
- 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
-
- alias << write
-
- 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 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[^\r\n]*(?:\n|\r(?:\n|(?!\z)))/)
- 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 |str|
- buf << str
- 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
diff --git a/ruby_1_9_3/lib/net/smtp.rb b/ruby_1_9_3/lib/net/smtp.rb
deleted file mode 100644
index f6e2ea9d9c..0000000000
--- a/ruby_1_9_3/lib/net/smtp.rb
+++ /dev/null
@@ -1,1057 +0,0 @@
-# = 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$
-#
-# 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_address@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$.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
-
- #
- # 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).
- #
- attr_accessor :esmtp
-
- # +true+ if the SMTP object uses ESMTP (which it does by default).
- 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. The default value is 30 seconds.
- 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. The default value is 60 seconds.
- 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'.
- #
- # 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',
- 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',
- 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 tcp_socket(address, port)
- TCPSocket.open address, port
- end
-
- 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) { tcp_socket(@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 ssl_socket(socket, context)
- OpenSSL::SSL::SSLSocket.new socket, context
- end
-
- def tlsconnect(s)
- verified = false
- s = ssl_socket(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
- verified = true
- s
- ensure
- s.close unless verified
- 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, authtype = DEFAULT_AUTH_TYPE)
- 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?
- ok_users = []
- unknown_users = []
- to_addrs.flatten.each do |addr|
- begin
- rcptto addr
- rescue SMTPAuthenticationError
- unknown_users << addr.dump
- else
- ok_users << addr
- end
- end
- raise ArgumentError, 'mail destination not given' if ok_users.empty?
- ret = yield
- unless unknown_users.empty?
- raise SMTPAuthenticationError, "failed to deliver for #{unknown_users.join(', ')}"
- end
- ret
- 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
-
- # This class represents a response received by the SMTP server. Instances
- # of this class are created by the SMTP class; they should not be directly
- # created by the user. For more information on SMTP responses, view
- # {Section 4.2 of RFC 5321}[http://tools.ietf.org/html/rfc5321#section-4.2]
- class Response
- # Parses the received response and separates the reply code and the human
- # readable reply text
- def self.parse(str)
- new(str[0,3], str)
- end
-
- # Creates a new instance of the Response class and sets the status and
- # string attributes
- def initialize(status, string)
- @status = status
- @string = string
- end
-
- # The three digit reply code of the SMTP response
- attr_reader :status
-
- # The human readable reply text of the SMTP response
- attr_reader :string
-
- # Takes the first digit of the reply code to determine the status type
- def status_type_char
- @status[0, 1]
- end
-
- # Determines whether the response received was a Positive Completion
- # reply (2xx reply code)
- def success?
- status_type_char() == '2'
- end
-
- # Determines whether the response received was a Positive Intermediate
- # reply (3xx reply code)
- def continue?
- status_type_char() == '3'
- end
-
- # The first line of the human readable reply text
- def message
- @string.lines.first
- end
-
- # Creates a CRAM-MD5 challenge. You can view more information on CRAM-MD5
- # on Wikipedia: http://en.wikipedia.org/wiki/CRAM-MD5
- def cram_md5_challenge
- @string.split(/ /)[1].unpack('m')[0]
- end
-
- # Returns a hash of the human readable reply text in the response if it
- # is multiple lines. It does not return the first line. The key of the
- # hash is the first word the value of the hash is an array with each word
- # thereafter being a value in the array
- def capabilities
- return {} unless @string[3, 1] == '-'
- h = {}
- @string.lines.drop(1).each do |line|
- k, *v = line[4..-1].chomp.split
- h[k] = v
- end
- h
- end
-
- # Determines whether there was an error and raies the appropriate error
- # based on the reply code of the response
- 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
diff --git a/ruby_1_9_3/lib/net/telnet.rb b/ruby_1_9_3/lib/net/telnet.rb
deleted file mode 100644
index fe463c63dc..0000000000
--- a/ruby_1_9_3/lib/net/telnet.rb
+++ /dev/null
@@ -1,764 +0,0 @@
-# = 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 "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
-
- # :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$'
- # :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
-
- 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"]
-
- # remove NULL
- string = string.gsub(/#{NULL}/no, '') 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) || 0) <
- Integer(c.rindex(/#{IAC}#{SB}/no) || 0)
- 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"]
- fail_eof = @options["FailEOF"]
-
- 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")
- fail_eof = options["FailEOF"] if options.has_key?("FailEOF")
- else
- string = options
- end
-
- self.puts(string)
- if block_given?
- waitfor({"Prompt" => match, "Timeout" => time_out, "FailEOF" => fail_eof}){|c| yield c }
- else
- waitfor({"Prompt" => match, "Timeout" => time_out, "FailEOF" => fail_eof})
- 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
-
- # Closes the connection
- def close
- @sock.close
- end
-
- end # class Telnet
-end # module Net
-
diff --git a/ruby_1_9_3/lib/observer.rb b/ruby_1_9_3/lib/observer.rb
deleted file mode 100644
index a5d0dc0f4e..0000000000
--- a/ruby_1_9_3/lib/observer.rb
+++ /dev/null
@@ -1,202 +0,0 @@
-#
-# Implementation of the _Observer_ object-oriented design pattern. The
-# following documentation is copied, with modifications, from "Programming
-# Ruby", by Hunt and Thomas; http://www.rubycentral.com/book/lib_patterns.html.
-#
-# See Observable for more info.
-
-# The Observer pattern (also known as publish/subscribe) provides a simple
-# mechanism for one object to inform a set of interested third-party objects
-# when its state changes.
-#
-# == Mechanism
-#
-# The notifying class mixes in the +Observable+
-# module, which provides the methods for managing the associated observer
-# objects.
-#
-# The observers must implement a method called +update+ to receive
-# notifications.
-#
-# The observable object must:
-# * assert that it has +#changed+
-# * call +#notify_observers+
-#
-# === Example
-#
-# The following example demonstrates this nicely. A +Ticker+, when run,
-# continually receives the stock +Price+ for its <tt>@symbol</tt>. A +Warner+
-# is a general observer of the price, and two warners are demonstrated, a
-# +WarnLow+ and a +WarnHigh+, which print a warning if the price is below or
-# above their set limits, respectively.
-#
-# The +update+ callback allows the warners to run without being explicitly
-# called. The system is set up with the +Ticker+ and several observers, and the
-# observers do their duty without the top-level code having to interfere.
-#
-# Note that the contract between publisher and subscriber (observable and
-# observer) is not declared or enforced. The +Ticker+ publishes a time and a
-# price, and the warners receive that. But if you don't ensure that your
-# contracts are correct, nothing else can warn you.
-#
-# require "observer"
-#
-# class Ticker ### Periodically fetch a stock price.
-# include Observable
-#
-# def initialize(symbol)
-# @symbol = symbol
-# end
-#
-# def run
-# lastPrice = nil
-# loop do
-# price = Price.fetch(@symbol)
-# print "Current price: #{price}\n"
-# if price != lastPrice
-# changed # notify observers
-# lastPrice = price
-# notify_observers(Time.now, price)
-# end
-# sleep 1
-# end
-# end
-# end
-#
-# class Price ### A mock class to fetch a stock price (60 - 140).
-# def Price.fetch(symbol)
-# 60 + rand(80)
-# end
-# end
-#
-# class Warner ### An abstract observer of Ticker objects.
-# def initialize(ticker, limit)
-# @limit = limit
-# ticker.add_observer(self)
-# end
-# end
-#
-# class WarnLow < Warner
-# def update(time, price) # callback for observer
-# if price < @limit
-# print "--- #{time.to_s}: Price below #@limit: #{price}\n"
-# end
-# end
-# end
-#
-# class WarnHigh < Warner
-# def update(time, price) # callback for observer
-# if price > @limit
-# print "+++ #{time.to_s}: Price above #@limit: #{price}\n"
-# end
-# end
-# end
-#
-# ticker = Ticker.new("MSFT")
-# WarnLow.new(ticker, 80)
-# WarnHigh.new(ticker, 120)
-# ticker.run
-#
-# Produces:
-#
-# Current price: 83
-# Current price: 75
-# --- Sun Jun 09 00:10:25 CDT 2002: Price below 80: 75
-# Current price: 90
-# Current price: 134
-# +++ Sun Jun 09 00:10:25 CDT 2002: Price above 120: 134
-# Current price: 134
-# Current price: 112
-# Current price: 79
-# --- Sun Jun 09 00:10:25 CDT 2002: Price below 80: 79
-module Observable
-
- #
- # Add +observer+ as an observer on this object. so that it will receive
- # notifications.
- #
- # +observer+:: the object that will be notified of changes.
- # +func+:: Symbol naming the method that will be called when this Observable
- # has changes.
- #
- # This method must return true for +observer.respond_to?+ and will
- # receive <tt>*arg</tt> when #notify_observers is called, where
- # <tt>*arg</tt> is the value passed to #notify_observers by this
- # Observable
- def add_observer(observer, func=:update)
- @observer_peers = {} unless defined? @observer_peers
- unless observer.respond_to? func
- raise NoMethodError, "observer does not respond to `#{func.to_s}'"
- end
- @observer_peers[observer] = func
- end
-
- #
- # Remove +observer+ as an observer on this object so that it will no longer
- # receive notifications.
- #
- # +observer+:: An observer of this Observable
- def delete_observer(observer)
- @observer_peers.delete observer if defined? @observer_peers
- end
-
- #
- # Remove all observers associated with this object.
- #
- def delete_observers
- @observer_peers.clear if defined? @observer_peers
- end
-
- #
- # Return the number of observers associated with this object.
- #
- def count_observers
- if defined? @observer_peers
- @observer_peers.size
- else
- 0
- end
- end
-
- #
- # Set the changed state of this object. Notifications will be sent only if
- # the changed +state+ is +true+.
- #
- # +state+:: Boolean indicating the changed state of this Observable.
- #
- def changed(state=true)
- @observer_state = state
- end
-
- #
- # Returns true if this object's state has been changed since the last
- # #notify_observers call.
- #
- def changed?
- if defined? @observer_state and @observer_state
- true
- else
- false
- end
- end
-
- #
- # Notify observers of a change in state *if* this object's changed state is
- # +true+.
- #
- # This will invoke the method named in #add_observer, pasing <tt>*arg</tt>.
- # The changed state is then set to +false+.
- #
- # <tt>*arg</tt>:: Any arguments to pass to the observers.
- def notify_observers(*arg)
- if defined? @observer_state and @observer_state
- if defined? @observer_peers
- @observer_peers.each do |k, v|
- k.send v, *arg
- end
- end
- @observer_state = false
- end
- end
-
-end
diff --git a/ruby_1_9_3/lib/open-uri.rb b/ruby_1_9_3/lib/open-uri.rb
deleted file mode 100644
index 6e24b40ba5..0000000000
--- a/ruby_1_9_3/lib/open-uri.rb
+++ /dev/null
@@ -1,840 +0,0 @@
-require 'uri'
-require 'stringio'
-require 'time'
-
-module Kernel
- private
- alias open_uri_original_open open # :nodoc:
- class << self
- alias open_uri_original_open open # :nodoc:
- end
-
- # Allows the opening of various resources including URIs.
- #
- # If the first argument responds to the 'open' method, 'open' is called on
- # it with the rest of the arguments.
- #
- # If the first argument is a string that begins with xxx://, it is parsed by
- # URI.parse. If the parsed object responds to the 'open' method,
- # 'open' is called on it with the rest of the arguments.
- #
- # Otherwise, the original Kernel#open is called.
- #
- # Since open-uri.rb provides URI::HTTP#open, URI::HTTPS#open and
- # URI::FTP#open, Kernel[#.]open can accept URIs and strings that begin with
- # http://, https:// and ftp://. In these cases, the opened file object is
- # extended by OpenURI::Meta.
- def open(name, *rest, &block) # :doc:
- if name.respond_to?(:open)
- name.open(*rest, &block)
- elsif name.respond_to?(:to_str) &&
- %r{\A[A-Za-z][A-Za-z0-9+\-\.]*://} =~ name &&
- (uri = URI.parse(name)).respond_to?(:open)
- uri.open(*rest, &block)
- else
- open_uri_original_open(name, *rest, &block)
- end
- end
- module_function :open
-end
-
-# OpenURI is an easy-to-use wrapper for net/http, net/https and net/ftp.
-#
-#== Example
-#
-# It is possible to open an http, https or ftp URL as though it were a file:
-#
-# open("http://www.ruby-lang.org/") {|f|
-# f.each_line {|line| p line}
-# }
-#
-# The opened file has several getter methods for its meta-information, as
-# follows, since it is extended by OpenURI::Meta.
-#
-# open("http://www.ruby-lang.org/en") {|f|
-# f.each_line {|line| p line}
-# p f.base_uri # <URI::HTTP:0x40e6ef2 URL:http://www.ruby-lang.org/en/>
-# p f.content_type # "text/html"
-# p f.charset # "iso-8859-1"
-# p f.content_encoding # []
-# p f.last_modified # Thu Dec 05 02:45:02 UTC 2002
-# }
-#
-# Additional header fields can be specified by an optional hash argument.
-#
-# open("http://www.ruby-lang.org/en/",
-# "User-Agent" => "Ruby/#{RUBY_VERSION}",
-# "From" => "foo@bar.invalid",
-# "Referer" => "http://www.ruby-lang.org/") {|f|
-# # ...
-# }
-#
-# The environment variables such as http_proxy, https_proxy and ftp_proxy
-# are in effect by default. :proxy => nil disables proxy.
-#
-# open("http://www.ruby-lang.org/en/raa.html", :proxy => nil) {|f|
-# # ...
-# }
-#
-# URI objects can be opened in a similar way.
-#
-# uri = URI.parse("http://www.ruby-lang.org/en/")
-# uri.open {|f|
-# # ...
-# }
-#
-# URI objects can be read directly. The returned string is also extended by
-# OpenURI::Meta.
-#
-# str = uri.read
-# p str.base_uri
-#
-# Author:: Tanaka Akira <akr@m17n.org>
-
-module OpenURI
- Options = {
- :proxy => true,
- :proxy_http_basic_authentication => true,
- :progress_proc => true,
- :content_length_proc => true,
- :http_basic_authentication => true,
- :read_timeout => true,
- :ssl_ca_cert => nil,
- :ssl_verify_mode => nil,
- :ftp_active_mode => false,
- :redirect => true,
- }
-
- def OpenURI.check_options(options) # :nodoc:
- options.each {|k, v|
- next unless Symbol === k
- unless Options.include? k
- raise ArgumentError, "unrecognized option: #{k}"
- end
- }
- end
-
- def OpenURI.scan_open_optional_arguments(*rest) # :nodoc:
- if !rest.empty? && (String === rest.first || Integer === rest.first)
- mode = rest.shift
- if !rest.empty? && Integer === rest.first
- perm = rest.shift
- end
- end
- return mode, perm, rest
- end
-
- def OpenURI.open_uri(name, *rest) # :nodoc:
- uri = URI::Generic === name ? name : URI.parse(name)
- mode, _, rest = OpenURI.scan_open_optional_arguments(*rest)
- options = rest.shift if !rest.empty? && Hash === rest.first
- raise ArgumentError.new("extra arguments") if !rest.empty?
- options ||= {}
- OpenURI.check_options(options)
-
- if /\Arb?(?:\Z|:([^:]+))/ =~ mode
- encoding, = $1,Encoding.find($1) if $1
- mode = nil
- end
-
- unless mode == nil ||
- mode == 'r' || mode == 'rb' ||
- mode == File::RDONLY
- raise ArgumentError.new("invalid access mode #{mode} (#{uri.class} resource is read only.)")
- end
-
- io = open_loop(uri, options)
- io.set_encoding(encoding) if encoding
- if block_given?
- begin
- yield io
- ensure
- io.close
- end
- else
- io
- end
- end
-
- def OpenURI.open_loop(uri, options) # :nodoc:
- proxy_opts = []
- proxy_opts << :proxy_http_basic_authentication if options.include? :proxy_http_basic_authentication
- proxy_opts << :proxy if options.include? :proxy
- proxy_opts.compact!
- if 1 < proxy_opts.length
- raise ArgumentError, "multiple proxy options specified"
- end
- case proxy_opts.first
- when :proxy_http_basic_authentication
- opt_proxy, proxy_user, proxy_pass = options.fetch(:proxy_http_basic_authentication)
- proxy_user = proxy_user.to_str
- proxy_pass = proxy_pass.to_str
- if opt_proxy == true
- raise ArgumentError.new("Invalid authenticated proxy option: #{options[:proxy_http_basic_authentication].inspect}")
- end
- when :proxy
- opt_proxy = options.fetch(:proxy)
- proxy_user = nil
- proxy_pass = nil
- when nil
- opt_proxy = true
- proxy_user = nil
- proxy_pass = nil
- end
- case opt_proxy
- when true
- find_proxy = lambda {|u| pxy = u.find_proxy; pxy ? [pxy, nil, nil] : nil}
- when nil, false
- find_proxy = lambda {|u| nil}
- when String
- opt_proxy = URI.parse(opt_proxy)
- find_proxy = lambda {|u| [opt_proxy, proxy_user, proxy_pass]}
- when URI::Generic
- find_proxy = lambda {|u| [opt_proxy, proxy_user, proxy_pass]}
- else
- raise ArgumentError.new("Invalid proxy option: #{opt_proxy}")
- end
-
- uri_set = {}
- buf = nil
- while true
- redirect = catch(:open_uri_redirect) {
- buf = Buffer.new
- uri.buffer_open(buf, find_proxy.call(uri), options)
- nil
- }
- if redirect
- if redirect.relative?
- # Although it violates RFC2616, Location: field may have relative
- # URI. It is converted to absolute URI using uri as a base URI.
- redirect = uri + redirect
- end
- if !options.fetch(:redirect, true)
- raise HTTPRedirect.new(buf.io.status.join(' '), buf.io, redirect)
- end
- unless OpenURI.redirectable?(uri, redirect)
- raise "redirection forbidden: #{uri} -> #{redirect}"
- end
- if options.include? :http_basic_authentication
- # send authentication only for the URI directly specified.
- options = options.dup
- options.delete :http_basic_authentication
- end
- uri = redirect
- raise "HTTP redirection loop: #{uri}" if uri_set.include? uri.to_s
- uri_set[uri.to_s] = true
- else
- break
- end
- end
- io = buf.io
- io.base_uri = uri
- io
- end
-
- def OpenURI.redirectable?(uri1, uri2) # :nodoc:
- # This test is intended to forbid a redirection from http://... to
- # file:///etc/passwd, file:///dev/zero, etc. CVE-2011-1521
- # https to http redirect is also forbidden intentionally.
- # It avoids sending secure cookie or referer by non-secure HTTP protocol.
- # (RFC 2109 4.3.1, RFC 2965 3.3, RFC 2616 15.1.3)
- # However this is ad hoc. It should be extensible/configurable.
- uri1.scheme.downcase == uri2.scheme.downcase ||
- (/\A(?:http|ftp)\z/i =~ uri1.scheme && /\A(?:http|ftp)\z/i =~ uri2.scheme)
- end
-
- def OpenURI.open_http(buf, target, proxy, options) # :nodoc:
- if proxy
- proxy_uri, proxy_user, proxy_pass = proxy
- raise "Non-HTTP proxy URI: #{proxy_uri}" if proxy_uri.class != URI::HTTP
- end
-
- if target.userinfo && "1.9.0" <= RUBY_VERSION
- # don't raise for 1.8 because compatibility.
- raise ArgumentError, "userinfo not supported. [RFC3986]"
- end
-
- header = {}
- options.each {|k, v| header[k] = v if String === k }
-
- require 'net/http'
- klass = Net::HTTP
- if URI::HTTP === target
- # HTTP or HTTPS
- if proxy
- if proxy_user && proxy_pass
- klass = Net::HTTP::Proxy(proxy_uri.hostname, proxy_uri.port, proxy_user, proxy_pass)
- else
- klass = Net::HTTP::Proxy(proxy_uri.hostname, proxy_uri.port)
- end
- end
- target_host = target.hostname
- target_port = target.port
- request_uri = target.request_uri
- else
- # FTP over HTTP proxy
- target_host = proxy_uri.hostname
- target_port = proxy_uri.port
- request_uri = target.to_s
- if proxy_user && proxy_pass
- header["Proxy-Authorization"] = 'Basic ' + ["#{proxy_user}:#{proxy_pass}"].pack('m').delete("\r\n")
- end
- end
-
- http = klass.new(target_host, target_port)
- if target.class == URI::HTTPS
- require 'net/https'
- http.use_ssl = true
- http.verify_mode = options[:ssl_verify_mode] || OpenSSL::SSL::VERIFY_PEER
- store = OpenSSL::X509::Store.new
- if options[:ssl_ca_cert]
- if File.directory? options[:ssl_ca_cert]
- store.add_path options[:ssl_ca_cert]
- else
- store.add_file options[:ssl_ca_cert]
- end
- else
- store.set_default_paths
- end
- http.cert_store = store
- end
- if options.include? :read_timeout
- http.read_timeout = options[:read_timeout]
- end
-
- resp = nil
- http.start {
- req = Net::HTTP::Get.new(request_uri, header)
- if options.include? :http_basic_authentication
- user, pass = options[:http_basic_authentication]
- req.basic_auth user, pass
- end
- http.request(req) {|response|
- resp = response
- if options[:content_length_proc] && Net::HTTPSuccess === resp
- if resp.key?('Content-Length')
- options[:content_length_proc].call(resp['Content-Length'].to_i)
- else
- options[:content_length_proc].call(nil)
- end
- end
- resp.read_body {|str|
- buf << str
- if options[:progress_proc] && Net::HTTPSuccess === resp
- options[:progress_proc].call(buf.size)
- end
- }
- }
- }
- io = buf.io
- io.rewind
- io.status = [resp.code, resp.message]
- resp.each {|name,value| buf.io.meta_add_field name, value }
- case resp
- when Net::HTTPSuccess
- when Net::HTTPMovedPermanently, # 301
- Net::HTTPFound, # 302
- Net::HTTPSeeOther, # 303
- Net::HTTPTemporaryRedirect # 307
- begin
- loc_uri = URI.parse(resp['location'])
- rescue URI::InvalidURIError
- raise OpenURI::HTTPError.new(io.status.join(' ') + ' (Invalid Location URI)', io)
- end
- throw :open_uri_redirect, loc_uri
- else
- raise OpenURI::HTTPError.new(io.status.join(' '), io)
- end
- end
-
- class HTTPError < StandardError
- def initialize(message, io)
- super(message)
- @io = io
- end
- attr_reader :io
- end
-
- class HTTPRedirect < HTTPError
- def initialize(message, io, uri)
- super(message, io)
- @uri = uri
- end
- attr_reader :uri
- end
-
- class Buffer # :nodoc:
- def initialize
- @io = StringIO.new
- @size = 0
- end
- attr_reader :size
-
- StringMax = 10240
- def <<(str)
- @io << str
- @size += str.length
- if StringIO === @io && StringMax < @size
- require 'tempfile'
- io = Tempfile.new('open-uri')
- io.binmode
- Meta.init io, @io if Meta === @io
- io << @io.string
- @io = io
- end
- end
-
- def io
- Meta.init @io unless Meta === @io
- @io
- end
- end
-
- # Mixin for holding meta-information.
- module Meta
- def Meta.init(obj, src=nil) # :nodoc:
- obj.extend Meta
- obj.instance_eval {
- @base_uri = nil
- @meta = {}
- }
- if src
- obj.status = src.status
- obj.base_uri = src.base_uri
- src.meta.each {|name, value|
- obj.meta_add_field(name, value)
- }
- end
- end
-
- # returns an Array that consists of status code and message.
- attr_accessor :status
-
- # returns a URI that is the base of relative URIs in the data.
- # It may differ from the URI supplied by a user due to redirection.
- attr_accessor :base_uri
-
- # returns a Hash that represents header fields.
- # The Hash keys are downcased for canonicalization.
- attr_reader :meta
-
- def meta_setup_encoding # :nodoc:
- charset = self.charset
- enc = nil
- if charset
- begin
- enc = Encoding.find(charset)
- rescue ArgumentError
- end
- end
- enc = Encoding::ASCII_8BIT unless enc
- if self.respond_to? :force_encoding
- self.force_encoding(enc)
- elsif self.respond_to? :string
- self.string.force_encoding(enc)
- else # Tempfile
- self.set_encoding enc
- end
- end
-
- def meta_add_field(name, value) # :nodoc:
- name = name.downcase
- @meta[name] = value
- meta_setup_encoding if name == 'content-type'
- end
-
- # returns a Time that represents the Last-Modified field.
- def last_modified
- if v = @meta['last-modified']
- Time.httpdate(v)
- else
- nil
- end
- end
-
- RE_LWS = /[\r\n\t ]+/n
- RE_TOKEN = %r{[^\x00- ()<>@,;:\\"/\[\]?={}\x7f]+}n
- RE_QUOTED_STRING = %r{"(?:[\r\n\t !#-\[\]-~\x80-\xff]|\\[\x00-\x7f])*"}n
- RE_PARAMETERS = %r{(?:;#{RE_LWS}?#{RE_TOKEN}#{RE_LWS}?=#{RE_LWS}?(?:#{RE_TOKEN}|#{RE_QUOTED_STRING})#{RE_LWS}?)*}n
-
- def content_type_parse # :nodoc:
- v = @meta['content-type']
- # The last (?:;#{RE_LWS}?)? matches extra ";" which violates RFC2045.
- if v && %r{\A#{RE_LWS}?(#{RE_TOKEN})#{RE_LWS}?/(#{RE_TOKEN})#{RE_LWS}?(#{RE_PARAMETERS})(?:;#{RE_LWS}?)?\z}no =~ v
- type = $1.downcase
- subtype = $2.downcase
- parameters = []
- $3.scan(/;#{RE_LWS}?(#{RE_TOKEN})#{RE_LWS}?=#{RE_LWS}?(?:(#{RE_TOKEN})|(#{RE_QUOTED_STRING}))/no) {|att, val, qval|
- if qval
- val = qval[1...-1].gsub(/[\r\n\t !#-\[\]-~\x80-\xff]+|(\\[\x00-\x7f])/n) { $1 ? $1[1,1] : $& }
- end
- parameters << [att.downcase, val]
- }
- ["#{type}/#{subtype}", *parameters]
- else
- nil
- end
- end
-
- # returns "type/subtype" which is MIME Content-Type.
- # It is downcased for canonicalization.
- # Content-Type parameters are stripped.
- def content_type
- type, *_ = content_type_parse
- type || 'application/octet-stream'
- end
-
- # returns a charset parameter in Content-Type field.
- # It is downcased for canonicalization.
- #
- # If charset parameter is not given but a block is given,
- # the block is called and its result is returned.
- # It can be used to guess charset.
- #
- # If charset parameter and block is not given,
- # nil is returned except text type in HTTP.
- # In that case, "iso-8859-1" is returned as defined by RFC2616 3.7.1.
- def charset
- type, *parameters = content_type_parse
- if pair = parameters.assoc('charset')
- pair.last.downcase
- elsif block_given?
- yield
- elsif type && %r{\Atext/} =~ type &&
- @base_uri && /\Ahttp\z/i =~ @base_uri.scheme
- "iso-8859-1" # RFC2616 3.7.1
- else
- nil
- end
- end
-
- # returns a list of encodings in Content-Encoding field
- # as an Array of String.
- # The encodings are downcased for canonicalization.
- def content_encoding
- v = @meta['content-encoding']
- if v && %r{\A#{RE_LWS}?#{RE_TOKEN}#{RE_LWS}?(?:,#{RE_LWS}?#{RE_TOKEN}#{RE_LWS}?)*}o =~ v
- v.scan(RE_TOKEN).map {|content_coding| content_coding.downcase}
- else
- []
- end
- end
- end
-
- # Mixin for HTTP and FTP URIs.
- module OpenRead
- # OpenURI::OpenRead#open provides `open' for URI::HTTP and URI::FTP.
- #
- # OpenURI::OpenRead#open takes optional 3 arguments as:
- #
- # OpenURI::OpenRead#open([mode [, perm]] [, options]) [{|io| ... }]
- #
- # OpenURI::OpenRead#open returns an IO-like object if block is not given.
- # Otherwise it yields the IO object and return the value of the block.
- # The IO object is extended with OpenURI::Meta.
- #
- # +mode+ and +perm+ are the same as Kernel#open.
- #
- # However, +mode+ must be read mode because OpenURI::OpenRead#open doesn't
- # support write mode (yet).
- # Also +perm+ is ignored because it is meaningful only for file creation.
- #
- # +options+ must be a hash.
- #
- # Each option with a string key specifies an extra header field for HTTP.
- # I.e., it is ignored for FTP without HTTP proxy.
- #
- # The hash may include other options, where keys are symbols:
- #
- # [:proxy]
- # Synopsis:
- # :proxy => "http://proxy.foo.com:8000/"
- # :proxy => URI.parse("http://proxy.foo.com:8000/")
- # :proxy => true
- # :proxy => false
- # :proxy => nil
- #
- # If :proxy option is specified, the value should be String, URI,
- # boolean or nil.
- #
- # When String or URI is given, it is treated as proxy URI.
- #
- # When true is given or the option itself is not specified,
- # environment variable `scheme_proxy' is examined.
- # `scheme' is replaced by `http', `https' or `ftp'.
- #
- # When false or nil is given, the environment variables are ignored and
- # connection will be made to a server directly.
- #
- # [:proxy_http_basic_authentication]
- # Synopsis:
- # :proxy_http_basic_authentication =>
- # ["http://proxy.foo.com:8000/", "proxy-user", "proxy-password"]
- # :proxy_http_basic_authentication =>
- # [URI.parse("http://proxy.foo.com:8000/"),
- # "proxy-user", "proxy-password"]
- #
- # If :proxy option is specified, the value should be an Array with 3
- # elements. It should contain a proxy URI, a proxy user name and a proxy
- # password. The proxy URI should be a String, an URI or nil. The proxy
- # user name and password should be a String.
- #
- # If nil is given for the proxy URI, this option is just ignored.
- #
- # If :proxy and :proxy_http_basic_authentication is specified,
- # ArgumentError is raised.
- #
- # [:http_basic_authentication]
- # Synopsis:
- # :http_basic_authentication=>[user, password]
- #
- # If :http_basic_authentication is specified,
- # the value should be an array which contains 2 strings:
- # username and password.
- # It is used for HTTP Basic authentication defined by RFC 2617.
- #
- # [:content_length_proc]
- # Synopsis:
- # :content_length_proc => lambda {|content_length| ... }
- #
- # If :content_length_proc option is specified, the option value procedure
- # is called before actual transfer is started.
- # It takes one argument, which is expected content length in bytes.
- #
- # If two or more transfer is done by HTTP redirection, the procedure
- # is called only one for a last transfer.
- #
- # When expected content length is unknown, the procedure is called with
- # nil. This happens when the HTTP response has no Content-Length header.
- #
- # [:progress_proc]
- # Synopsis:
- # :progress_proc => lambda {|size| ...}
- #
- # If :progress_proc option is specified, the proc is called with one
- # argument each time when `open' gets content fragment from network.
- # The argument +size+ is the accumulated transferred size in bytes.
- #
- # If two or more transfer is done by HTTP redirection, the procedure
- # is called only one for a last transfer.
- #
- # :progress_proc and :content_length_proc are intended to be used for
- # progress bar.
- # For example, it can be implemented as follows using Ruby/ProgressBar.
- #
- # pbar = nil
- # open("http://...",
- # :content_length_proc => lambda {|t|
- # if t && 0 < t
- # pbar = ProgressBar.new("...", t)
- # pbar.file_transfer_mode
- # end
- # },
- # :progress_proc => lambda {|s|
- # pbar.set s if pbar
- # }) {|f| ... }
- #
- # [:read_timeout]
- # Synopsis:
- # :read_timeout=>nil (no timeout)
- # :read_timeout=>10 (10 second)
- #
- # :read_timeout option specifies a timeout of read for http connections.
- #
- # [:ssl_ca_cert]
- # Synopsis:
- # :ssl_ca_cert=>filename
- #
- # :ssl_ca_cert is used to specify CA certificate for SSL.
- # If it is given, default certificates are not used.
- #
- # [:ssl_verify_mode]
- # Synopsis:
- # :ssl_verify_mode=>mode
- #
- # :ssl_verify_mode is used to specify openssl verify mode.
- #
- # [:ftp_active_mode]
- # Synopsis:
- # :ftp_active_mode=>bool
- #
- # <tt>:ftp_active_mode => true</tt> is used to make ftp active mode.
- # Ruby 1.9 uses passive mode by default.
- # Note that the active mode is default in Ruby 1.8 or prior.
- #
- # [:redirect]
- # Synopsis:
- # :redirect=>bool
- #
- # +:redirect+ is true by default. <tt>:redirect => false</tt> is used to
- # disable all HTTP redirects.
- #
- # OpenURI::HTTPRedirect exception raised on redirection.
- # Using +true+ also means that redirections between http and ftp are
- # permitted.
- #
- def open(*rest, &block)
- OpenURI.open_uri(self, *rest, &block)
- end
-
- # OpenURI::OpenRead#read([options]) reads a content referenced by self and
- # returns the content as string.
- # The string is extended with OpenURI::Meta.
- # The argument +options+ is same as OpenURI::OpenRead#open.
- def read(options={})
- self.open(options) {|f|
- str = f.read
- Meta.init str, f
- str
- }
- end
- end
-end
-
-module URI
- class Generic
- # returns a proxy URI.
- # The proxy URI is obtained from environment variables such as http_proxy,
- # ftp_proxy, no_proxy, etc.
- # If there is no proper proxy, nil is returned.
- #
- # Note that capitalized variables (HTTP_PROXY, FTP_PROXY, NO_PROXY, etc.)
- # are examined too.
- #
- # But http_proxy and HTTP_PROXY is treated specially under CGI environment.
- # It's because HTTP_PROXY may be set by Proxy: header.
- # So HTTP_PROXY is not used.
- # http_proxy is not used too if the variable is case insensitive.
- # CGI_HTTP_PROXY can be used instead.
- def find_proxy
- name = self.scheme.downcase + '_proxy'
- proxy_uri = nil
- if name == 'http_proxy' && ENV.include?('REQUEST_METHOD') # CGI?
- # HTTP_PROXY conflicts with *_proxy for proxy settings and
- # HTTP_* for header information in CGI.
- # So it should be careful to use it.
- pairs = ENV.reject {|k, v| /\Ahttp_proxy\z/i !~ k }
- case pairs.length
- when 0 # no proxy setting anyway.
- proxy_uri = nil
- when 1
- k, _ = pairs.shift
- if k == 'http_proxy' && ENV[k.upcase] == nil
- # http_proxy is safe to use because ENV is case sensitive.
- proxy_uri = ENV[name]
- else
- proxy_uri = nil
- end
- else # http_proxy is safe to use because ENV is case sensitive.
- proxy_uri = ENV.to_hash[name]
- end
- if !proxy_uri
- # Use CGI_HTTP_PROXY. cf. libwww-perl.
- proxy_uri = ENV["CGI_#{name.upcase}"]
- end
- elsif name == 'http_proxy'
- unless proxy_uri = ENV[name]
- if proxy_uri = ENV[name.upcase]
- warn 'The environment variable HTTP_PROXY is discouraged. Use http_proxy.'
- end
- end
- else
- proxy_uri = ENV[name] || ENV[name.upcase]
- end
-
- if proxy_uri && self.hostname
- require 'socket'
- begin
- addr = IPSocket.getaddress(self.hostname)
- proxy_uri = nil if /\A127\.|\A::1\z/ =~ addr
- rescue SocketError
- end
- end
-
- if proxy_uri
- proxy_uri = URI.parse(proxy_uri)
- name = 'no_proxy'
- if no_proxy = ENV[name] || ENV[name.upcase]
- no_proxy.scan(/([^:,]*)(?::(\d+))?/) {|host, port|
- if /(\A|\.)#{Regexp.quote host}\z/i =~ self.host &&
- (!port || self.port == port.to_i)
- proxy_uri = nil
- break
- end
- }
- end
- proxy_uri
- else
- nil
- end
- end
- end
-
- class HTTP
- def buffer_open(buf, proxy, options) # :nodoc:
- OpenURI.open_http(buf, self, proxy, options)
- end
-
- include OpenURI::OpenRead
- end
-
- class FTP
- def buffer_open(buf, proxy, options) # :nodoc:
- if proxy
- OpenURI.open_http(buf, self, proxy, options)
- return
- end
- require 'net/ftp'
-
- path = self.path
- path = path.sub(%r{\A/}, '%2F') # re-encode the beginning slash because uri library decodes it.
- directories = path.split(%r{/}, -1)
- directories.each {|d|
- d.gsub!(/%([0-9A-Fa-f][0-9A-Fa-f])/) { [$1].pack("H2") }
- }
- unless filename = directories.pop
- raise ArgumentError, "no filename: #{self.inspect}"
- end
- directories.each {|d|
- if /[\r\n]/ =~ d
- raise ArgumentError, "invalid directory: #{d.inspect}"
- end
- }
- if /[\r\n]/ =~ filename
- raise ArgumentError, "invalid filename: #{filename.inspect}"
- end
- typecode = self.typecode
- if typecode && /\A[aid]\z/ !~ typecode
- raise ArgumentError, "invalid typecode: #{typecode.inspect}"
- end
-
- # The access sequence is defined by RFC 1738
- ftp = Net::FTP.new
- ftp.connect(self.hostname, self.port)
- ftp.passive = true if !options[:ftp_active_mode]
- # todo: extract user/passwd from .netrc.
- user = 'anonymous'
- passwd = nil
- user, passwd = self.userinfo.split(/:/) if self.userinfo
- ftp.login(user, passwd)
- directories.each {|cwd|
- ftp.voidcmd("CWD #{cwd}")
- }
- if typecode
- # xxx: typecode D is not handled.
- ftp.voidcmd("TYPE #{typecode.upcase}")
- end
- if options[:content_length_proc]
- options[:content_length_proc].call(ftp.size(filename))
- end
- ftp.retrbinary("RETR #{filename}", 4096) { |str|
- buf << str
- options[:progress_proc].call(buf.size) if options[:progress_proc]
- }
- ftp.close
- buf.io.rewind
- end
-
- include OpenURI::OpenRead
- end
-end
diff --git a/ruby_1_9_3/lib/open3.rb b/ruby_1_9_3/lib/open3.rb
deleted file mode 100644
index 03a7937c09..0000000000
--- a/ruby_1_9_3/lib/open3.rb
+++ /dev/null
@@ -1,729 +0,0 @@
-#
-# = open3.rb: Popen, but with stderr, too
-#
-# Author:: Yukihiro Matsumoto
-# Documentation:: Konrad Meyer
-#
-# Open3 gives you access to stdin, stdout, and stderr when running other
-# programs.
-#
-
-#
-# Open3 grants you access to stdin, stdout, stderr and a thread to wait the
-# child process when running another program.
-# You can specify various attributes, redirections, current directory, etc., of
-# the program as Process.spawn.
-#
-# - Open3.popen3 : pipes for stdin, stdout, stderr
-# - Open3.popen2 : pipes for stdin, stdout
-# - Open3.popen2e : pipes for stdin, merged stdout and stderr
-# - Open3.capture3 : give a string for stdin. get strings for stdout, stderr
-# - Open3.capture2 : give a string for stdin. get a string for stdout
-# - Open3.capture2e : give a string for stdin. get a string for merged stdout and stderr
-# - Open3.pipeline_rw : pipes for first stdin and last stdout of a pipeline
-# - Open3.pipeline_r : pipe for last stdout of a pipeline
-# - Open3.pipeline_w : pipe for first stdin of a pipeline
-# - Open3.pipeline_start : a pipeline
-# - Open3.pipeline : run a pipline and wait
-#
-
-module Open3
-
- # Open stdin, stdout, and stderr streams and start external executable.
- # In addition, a thread for waiting the started process is noticed.
- # The thread has a pid method and thread variable :pid which is the pid of
- # the started process.
- #
- # Block form:
- #
- # Open3.popen3([env,] cmd... [, opts]) {|stdin, stdout, stderr, wait_thr|
- # pid = wait_thr.pid # pid of the started process.
- # ...
- # exit_status = wait_thr.value # Process::Status object returned.
- # }
- #
- # Non-block form:
- #
- # stdin, stdout, stderr, wait_thr = Open3.popen3([env,] cmd... [, opts])
- # pid = wait_thr[:pid] # pid of the started process.
- # ...
- # stdin.close # stdin, stdout and stderr should be closed explicitly in this form.
- # stdout.close
- # stderr.close
- # exit_status = wait_thr.value # Process::Status object returned.
- #
- # The parameters +cmd...+ is passed to Process.spawn.
- # So a commandline string and list of argument strings can be accepted as follows.
- #
- # Open3.popen3("echo a") {|i, o, e, t| ... }
- # Open3.popen3("echo", "a") {|i, o, e, t| ... }
- # Open3.popen3(["echo", "argv0"], "a") {|i, o, e, t| ... }
- #
- # If the last parameter, opts, is a Hash, it is recognized as an option for Process.spawn.
- #
- # Open3.popen3("pwd", :chdir=>"/") {|i,o,e,t|
- # p o.read.chomp #=> "/"
- # }
- #
- # wait_thr.value waits the termination of the process.
- # The block form also waits the process when it returns.
- #
- # Closing stdin, stdout and stderr does not wait the process.
- #
- def popen3(*cmd, &block)
- if Hash === cmd.last
- opts = cmd.pop.dup
- else
- opts = {}
- end
-
- in_r, in_w = IO.pipe
- opts[:in] = in_r
- in_w.sync = true
-
- out_r, out_w = IO.pipe
- opts[:out] = out_w
-
- err_r, err_w = IO.pipe
- opts[:err] = err_w
-
- popen_run(cmd, opts, [in_r, out_w, err_w], [in_w, out_r, err_r], &block)
- end
- module_function :popen3
-
- # Open3.popen2 is similer to Open3.popen3 except it doesn't make a pipe for
- # the standard error stream.
- #
- # Block form:
- #
- # Open3.popen2([env,] cmd... [, opts]) {|stdin, stdout, wait_thr|
- # pid = wait_thr.pid # pid of the started process.
- # ...
- # exit_status = wait_thr.value # Process::Status object returned.
- # }
- #
- # Non-block form:
- #
- # stdin, stdout, wait_thr = Open3.popen2([env,] cmd... [, opts])
- # ...
- # stdin.close # stdin and stdout should be closed explicitly in this form.
- # stdout.close
- #
- # See Process.spawn for the optional hash arguments _env_ and _opts_.
- #
- # Example:
- #
- # Open3.popen2("wc -c") {|i,o,t|
- # i.print "answer to life the universe and everything"
- # i.close
- # p o.gets #=> "42\n"
- # }
- #
- # Open3.popen2("bc -q") {|i,o,t|
- # i.puts "obase=13"
- # i.puts "6 * 9"
- # p o.gets #=> "42\n"
- # }
- #
- # Open3.popen2("dc") {|i,o,t|
- # i.print "42P"
- # i.close
- # p o.read #=> "*"
- # }
- #
- def popen2(*cmd, &block)
- if Hash === cmd.last
- opts = cmd.pop.dup
- else
- opts = {}
- end
-
- in_r, in_w = IO.pipe
- opts[:in] = in_r
- in_w.sync = true
-
- out_r, out_w = IO.pipe
- opts[:out] = out_w
-
- popen_run(cmd, opts, [in_r, out_w], [in_w, out_r], &block)
- end
- module_function :popen2
-
- # Open3.popen2e is similer to Open3.popen3 except it merges
- # the standard output stream and the standard error stream.
- #
- # Block form:
- #
- # Open3.popen2e([env,] cmd... [, opts]) {|stdin, stdout_and_stderr, wait_thr|
- # pid = wait_thr.pid # pid of the started process.
- # ...
- # exit_status = wait_thr.value # Process::Status object returned.
- # }
- #
- # Non-block form:
- #
- # stdin, stdout_and_stderr, wait_thr = Open3.popen2e([env,] cmd... [, opts])
- # ...
- # stdin.close # stdin and stdout_and_stderr should be closed explicitly in this form.
- # stdout_and_stderr.close
- #
- # See Process.spawn for the optional hash arguments _env_ and _opts_.
- #
- # Example:
- # # check gcc warnings
- # source = "foo.c"
- # Open3.popen2e("gcc", "-Wall", source) {|i,oe,t|
- # oe.each {|line|
- # if /warning/ =~ line
- # ...
- # end
- # }
- # }
- #
- def popen2e(*cmd, &block)
- if Hash === cmd.last
- opts = cmd.pop.dup
- else
- opts = {}
- end
-
- in_r, in_w = IO.pipe
- opts[:in] = in_r
- in_w.sync = true
-
- out_r, out_w = IO.pipe
- opts[[:out, :err]] = out_w
-
- popen_run(cmd, opts, [in_r, out_w], [in_w, out_r], &block)
- end
- module_function :popen2e
-
- def popen_run(cmd, opts, child_io, parent_io) # :nodoc:
- pid = spawn(*cmd, opts)
- wait_thr = Process.detach(pid)
- child_io.each {|io| io.close }
- result = [*parent_io, wait_thr]
- if defined? yield
- begin
- return yield(*result)
- ensure
- parent_io.each{|io| io.close unless io.closed?}
- wait_thr.join
- end
- end
- result
- end
- module_function :popen_run
- class << self
- private :popen_run
- end
-
- # Open3.capture3 captures the standard output and the standard error of a command.
- #
- # stdout_str, stderr_str, status = Open3.capture3([env,] cmd... [, opts])
- #
- # The arguments env, cmd and opts are passed to Open3.popen3 except
- # opts[:stdin_data] and opts[:binmode]. See Process.spawn.
- #
- # If opts[:stdin_data] is specified, it is sent to the command's standard input.
- #
- # If opts[:binmode] is true, internal pipes are set to binary mode.
- #
- # Example:
- #
- # # dot is a command of graphviz.
- # graph = <<'End'
- # digraph g {
- # a -> b
- # }
- # End
- # layouted_graph, dot_log = Open3.capture3("dot -v", :stdin_data=>graph)
- #
- # o, e, s = Open3.capture3("echo a; sort >&2", :stdin_data=>"foo\nbar\nbaz\n")
- # p o #=> "a\n"
- # p e #=> "bar\nbaz\nfoo\n"
- # p s #=> #<Process::Status: pid 32682 exit 0>
- #
- # # generate a thumnail image using the convert command of ImageMagick.
- # # However, if the image stored really in a file,
- # # system("convert", "-thumbnail", "80", "png:#{filename}", "png:-") is better
- # # because memory consumption.
- # # But if the image is stored in a DB or generated by gnuplot Open3.capture2 example,
- # # Open3.capture3 is considerable.
- # #
- # image = File.read("/usr/share/openclipart/png/animals/mammals/sheep-md-v0.1.png", :binmode=>true)
- # thumnail, err, s = Open3.capture3("convert -thumbnail 80 png:- png:-", :stdin_data=>image, :binmode=>true)
- # if s.success?
- # STDOUT.binmode; print thumnail
- # end
- #
- def capture3(*cmd, &block)
- if Hash === cmd.last
- opts = cmd.pop.dup
- else
- opts = {}
- end
-
- stdin_data = opts.delete(:stdin_data) || ''
- binmode = opts.delete(:binmode)
-
- popen3(*cmd, opts) {|i, o, e, t|
- if binmode
- i.binmode
- o.binmode
- e.binmode
- end
- out_reader = Thread.new { o.read }
- err_reader = Thread.new { e.read }
- i.write stdin_data
- i.close
- [out_reader.value, err_reader.value, t.value]
- }
- end
- module_function :capture3
-
- # Open3.capture2 captures the standard output of a command.
- #
- # stdout_str, status = Open3.capture2([env,] cmd... [, opts])
- #
- # The arguments env, cmd and opts are passed to Open3.popen3 except
- # opts[:stdin_data] and opts[:binmode]. See Process.spawn.
- #
- # If opts[:stdin_data] is specified, it is sent to the command's standard input.
- #
- # If opts[:binmode] is true, internal pipes are set to binary mode.
- #
- # Example:
- #
- # # factor is a command for integer factorization.
- # o, s = Open3.capture2("factor", :stdin_data=>"42")
- # p o #=> "42: 2 3 7\n"
- #
- # # generate x**2 graph in png using gnuplot.
- # gnuplot_commands = <<"End"
- # set terminal png
- # plot x**2, "-" with lines
- # 1 14
- # 2 1
- # 3 8
- # 4 5
- # e
- # End
- # image, s = Open3.capture2("gnuplot", :stdin_data=>gnuplot_commands, :binmode=>true)
- #
- def capture2(*cmd, &block)
- if Hash === cmd.last
- opts = cmd.pop.dup
- else
- opts = {}
- end
-
- stdin_data = opts.delete(:stdin_data) || ''
- binmode = opts.delete(:binmode)
-
- popen2(*cmd, opts) {|i, o, t|
- if binmode
- i.binmode
- o.binmode
- end
- out_reader = Thread.new { o.read }
- i.write stdin_data
- i.close
- [out_reader.value, t.value]
- }
- end
- module_function :capture2
-
- # Open3.capture2e captures the standard output and the standard error of a command.
- #
- # stdout_and_stderr_str, status = Open3.capture2e([env,] cmd... [, opts])
- #
- # The arguments env, cmd and opts are passed to Open3.popen3 except
- # opts[:stdin_data] and opts[:binmode]. See Process.spawn.
- #
- # If opts[:stdin_data] is specified, it is sent to the command's standard input.
- #
- # If opts[:binmode] is true, internal pipes are set to binary mode.
- #
- # Example:
- #
- # # capture make log
- # make_log, s = Open3.capture2e("make")
- #
- def capture2e(*cmd, &block)
- if Hash === cmd.last
- opts = cmd.pop.dup
- else
- opts = {}
- end
-
- stdin_data = opts.delete(:stdin_data) || ''
- binmode = opts.delete(:binmode)
-
- popen2e(*cmd, opts) {|i, oe, t|
- if binmode
- i.binmode
- oe.binmode
- end
- outerr_reader = Thread.new { oe.read }
- i.write stdin_data
- i.close
- [outerr_reader.value, t.value]
- }
- end
- module_function :capture2e
-
- # Open3.pipeline_rw starts a list of commands as a pipeline with pipes
- # which connects stdin of the first command and stdout of the last command.
- #
- # Open3.pipeline_rw(cmd1, cmd2, ... [, opts]) {|first_stdin, last_stdout, wait_threads|
- # ...
- # }
- #
- # first_stdin, last_stdout, wait_threads = Open3.pipeline_rw(cmd1, cmd2, ... [, opts])
- # ...
- # first_stdin.close
- # last_stdout.close
- #
- # Each cmd is a string or an array.
- # If it is an array, the elements are passed to Process.spawn.
- #
- # cmd:
- # commandline command line string which is passed to a shell
- # [env, commandline, opts] command line string which is passed to a shell
- # [env, cmdname, arg1, ..., opts] command name and one or more arguments (no shell)
- # [env, [cmdname, argv0], arg1, ..., opts] command name and arguments including argv[0] (no shell)
- #
- # Note that env and opts are optional, as Process.spawn.
- #
- # The option to pass Process.spawn is constructed by merging
- # +opts+, the last hash element of the array and
- # specification for the pipe between each commands.
- #
- # Example:
- #
- # Open3.pipeline_rw("tr -dc A-Za-z", "wc -c") {|i,o,ts|
- # i.puts "All persons more than a mile high to leave the court."
- # i.close
- # p o.gets #=> "42\n"
- # }
- #
- # Open3.pipeline_rw("sort", "cat -n") {|stdin, stdout, wait_thrs|
- # stdin.puts "foo"
- # stdin.puts "bar"
- # stdin.puts "baz"
- # stdin.close # send EOF to sort.
- # p stdout.read #=> " 1\tbar\n 2\tbaz\n 3\tfoo\n"
- # }
- def pipeline_rw(*cmds, &block)
- if Hash === cmds.last
- opts = cmds.pop.dup
- else
- opts = {}
- end
-
- in_r, in_w = IO.pipe
- opts[:in] = in_r
- in_w.sync = true
-
- out_r, out_w = IO.pipe
- opts[:out] = out_w
-
- pipeline_run(cmds, opts, [in_r, out_w], [in_w, out_r], &block)
- end
- module_function :pipeline_rw
-
- # Open3.pipeline_r starts a list of commands as a pipeline with a pipe
- # which connects stdout of the last command.
- #
- # Open3.pipeline_r(cmd1, cmd2, ... [, opts]) {|last_stdout, wait_threads|
- # ...
- # }
- #
- # last_stdout, wait_threads = Open3.pipeline_r(cmd1, cmd2, ... [, opts])
- # ...
- # last_stdout.close
- #
- # Each cmd is a string or an array.
- # If it is an array, the elements are passed to Process.spawn.
- #
- # cmd:
- # commandline command line string which is passed to a shell
- # [env, commandline, opts] command line string which is passed to a shell
- # [env, cmdname, arg1, ..., opts] command name and one or more arguments (no shell)
- # [env, [cmdname, argv0], arg1, ..., opts] command name and arguments including argv[0] (no shell)
- #
- # Note that env and opts are optional, as Process.spawn.
- #
- # Example:
- #
- # Open3.pipeline_r("zcat /var/log/apache2/access.log.*.gz",
- # [{"LANG"=>"C"}, "grep", "GET /favicon.ico"],
- # "logresolve") {|o, ts|
- # o.each_line {|line|
- # ...
- # }
- # }
- #
- # Open3.pipeline_r("yes", "head -10") {|o, ts|
- # p o.read #=> "y\ny\ny\ny\ny\ny\ny\ny\ny\ny\n"
- # p ts[0].value #=> #<Process::Status: pid 24910 SIGPIPE (signal 13)>
- # p ts[1].value #=> #<Process::Status: pid 24913 exit 0>
- # }
- #
- def pipeline_r(*cmds, &block)
- if Hash === cmds.last
- opts = cmds.pop.dup
- else
- opts = {}
- end
-
- out_r, out_w = IO.pipe
- opts[:out] = out_w
-
- pipeline_run(cmds, opts, [out_w], [out_r], &block)
- end
- module_function :pipeline_r
-
- # Open3.pipeline_w starts a list of commands as a pipeline with a pipe
- # which connects stdin of the first command.
- #
- # Open3.pipeline_w(cmd1, cmd2, ... [, opts]) {|first_stdin, wait_threads|
- # ...
- # }
- #
- # first_stdin, wait_threads = Open3.pipeline_w(cmd1, cmd2, ... [, opts])
- # ...
- # first_stdin.close
- #
- # Each cmd is a string or an array.
- # If it is an array, the elements are passed to Process.spawn.
- #
- # cmd:
- # commandline command line string which is passed to a shell
- # [env, commandline, opts] command line string which is passed to a shell
- # [env, cmdname, arg1, ..., opts] command name and one or more arguments (no shell)
- # [env, [cmdname, argv0], arg1, ..., opts] command name and arguments including argv[0] (no shell)
- #
- # Note that env and opts are optional, as Process.spawn.
- #
- # Example:
- #
- # Open3.pipeline_w("bzip2 -c", :out=>"/tmp/hello.bz2") {|i, ts|
- # i.puts "hello"
- # }
- #
- def pipeline_w(*cmds, &block)
- if Hash === cmds.last
- opts = cmds.pop.dup
- else
- opts = {}
- end
-
- in_r, in_w = IO.pipe
- opts[:in] = in_r
- in_w.sync = true
-
- pipeline_run(cmds, opts, [in_r], [in_w], &block)
- end
- module_function :pipeline_w
-
- # Open3.pipeline_start starts a list of commands as a pipeline.
- # No pipe made for stdin of the first command and
- # stdout of the last command.
- #
- # Open3.pipeline_start(cmd1, cmd2, ... [, opts]) {|wait_threads|
- # ...
- # }
- #
- # wait_threads = Open3.pipeline_start(cmd1, cmd2, ... [, opts])
- # ...
- #
- # Each cmd is a string or an array.
- # If it is an array, the elements are passed to Process.spawn.
- #
- # cmd:
- # commandline command line string which is passed to a shell
- # [env, commandline, opts] command line string which is passed to a shell
- # [env, cmdname, arg1, ..., opts] command name and one or more arguments (no shell)
- # [env, [cmdname, argv0], arg1, ..., opts] command name and arguments including argv[0] (no shell)
- #
- # Note that env and opts are optional, as Process.spawn.
- #
- # Example:
- #
- # # run xeyes in 10 seconds.
- # Open3.pipeline_start("xeyes") {|ts|
- # sleep 10
- # t = ts[0]
- # Process.kill("TERM", t.pid)
- # p t.value #=> #<Process::Status: pid 911 SIGTERM (signal 15)>
- # }
- #
- # # convert pdf to ps and send it to a printer.
- # # collect error message of pdftops and lpr.
- # pdf_file = "paper.pdf"
- # printer = "printer-name"
- # err_r, err_w = IO.pipe
- # Open3.pipeline_start(["pdftops", pdf_file, "-"],
- # ["lpr", "-P#{printer}"],
- # :err=>err_w) {|ts|
- # err_w.close
- # p err_r.read # error messages of pdftops and lpr.
- # }
- #
- def pipeline_start(*cmds, &block)
- if Hash === cmds.last
- opts = cmds.pop.dup
- else
- opts = {}
- end
-
- if block
- pipeline_run(cmds, opts, [], [], &block)
- else
- ts, = pipeline_run(cmds, opts, [], [])
- ts
- end
- end
- module_function :pipeline_start
-
- # Open3.pipeline starts a list of commands as a pipeline.
- # It waits the finish of the commands.
- # No pipe made for stdin of the first command and
- # stdout of the last command.
- #
- # status_list = Open3.pipeline(cmd1, cmd2, ... [, opts])
- #
- # Each cmd is a string or an array.
- # If it is an array, the elements are passed to Process.spawn.
- #
- # cmd:
- # commandline command line string which is passed to a shell
- # [env, commandline, opts] command line string which is passed to a shell
- # [env, cmdname, arg1, ..., opts] command name and one or more arguments (no shell)
- # [env, [cmdname, argv0], arg1, ..., opts] command name and arguments including argv[0] (no shell)
- #
- # Note that env and opts are optional, as Process.spawn.
- #
- # Example:
- #
- # fname = "/usr/share/man/man1/ruby.1.gz"
- # p Open3.pipeline(["zcat", fname], "nroff -man", "less")
- # #=> [#<Process::Status: pid 11817 exit 0>,
- # # #<Process::Status: pid 11820 exit 0>,
- # # #<Process::Status: pid 11828 exit 0>]
- #
- # fname = "/usr/share/man/man1/ls.1.gz"
- # Open3.pipeline(["zcat", fname], "nroff -man", "colcrt")
- #
- # # convert PDF to PS and send to a printer by lpr
- # pdf_file = "paper.pdf"
- # printer = "printer-name"
- # Open3.pipeline(["pdftops", pdf_file, "-"],
- # ["lpr", "-P#{printer}"])
- #
- # # count lines
- # Open3.pipeline("sort", "uniq -c", :in=>"names.txt", :out=>"count")
- #
- # # cyclic pipeline
- # r,w = IO.pipe
- # w.print "ibase=14\n10\n"
- # Open3.pipeline("bc", "tee /dev/tty", :in=>r, :out=>w)
- # #=> 14
- # # 18
- # # 22
- # # 30
- # # 42
- # # 58
- # # 78
- # # 106
- # # 202
- #
- def pipeline(*cmds)
- if Hash === cmds.last
- opts = cmds.pop.dup
- else
- opts = {}
- end
-
- pipeline_run(cmds, opts, [], []) {|ts|
- ts.map {|t| t.value }
- }
- end
- module_function :pipeline
-
- def pipeline_run(cmds, pipeline_opts, child_io, parent_io, &block) # :nodoc:
- if cmds.empty?
- raise ArgumentError, "no commands"
- end
-
- opts_base = pipeline_opts.dup
- opts_base.delete :in
- opts_base.delete :out
-
- wait_thrs = []
- r = nil
- cmds.each_with_index {|cmd, i|
- cmd_opts = opts_base.dup
- if String === cmd
- cmd = [cmd]
- else
- cmd_opts.update cmd.pop if Hash === cmd.last
- end
- if i == 0
- if !cmd_opts.include?(:in)
- if pipeline_opts.include?(:in)
- cmd_opts[:in] = pipeline_opts[:in]
- end
- end
- else
- cmd_opts[:in] = r
- end
- if i != cmds.length - 1
- r2, w2 = IO.pipe
- cmd_opts[:out] = w2
- else
- if !cmd_opts.include?(:out)
- if pipeline_opts.include?(:out)
- cmd_opts[:out] = pipeline_opts[:out]
- end
- end
- end
- pid = spawn(*cmd, cmd_opts)
- wait_thrs << Process.detach(pid)
- r.close if r
- w2.close if w2
- r = r2
- }
- result = parent_io + [wait_thrs]
- child_io.each {|io| io.close }
- if defined? yield
- begin
- return yield(*result)
- ensure
- parent_io.each{|io| io.close unless io.closed?}
- wait_thrs.each {|t| t.join }
- end
- end
- result
- end
- module_function :pipeline_run
- class << self
- private :pipeline_run
- end
-
-end
-
-if $0 == __FILE__
- a = Open3.popen3("nroff -man")
- Thread.start do
- while line = gets
- a[0].print line
- end
- a[0].close
- end
- while line = a[1].gets
- print ":", line
- end
-end
diff --git a/ruby_1_9_3/lib/optparse.rb b/ruby_1_9_3/lib/optparse.rb
deleted file mode 100644
index dcb67604e2..0000000000
--- a/ruby_1_9_3/lib/optparse.rb
+++ /dev/null
@@ -1,1937 +0,0 @@
-#
-# optparse.rb - command-line option analysis with the OptionParser class.
-#
-# Author:: Nobu Nakada
-# Documentation:: Nobu Nakada and Gavin Sinclair.
-#
-# See OptionParser for documentation.
-#
-
-
-# == Developer Documentation (not for RDoc output)
-#
-# === Class tree
-#
-# - OptionParser:: front end
-# - OptionParser::Switch:: each switches
-# - OptionParser::List:: options list
-# - OptionParser::ParseError:: errors on parsing
-# - OptionParser::AmbiguousOption
-# - OptionParser::NeedlessArgument
-# - OptionParser::MissingArgument
-# - OptionParser::InvalidOption
-# - OptionParser::InvalidArgument
-# - OptionParser::AmbiguousArgument
-#
-# === Object relationship diagram
-#
-# +--------------+
-# | OptionParser |<>-----+
-# +--------------+ | +--------+
-# | ,-| Switch |
-# on_head -------->+---------------+ / +--------+
-# accept/reject -->| List |<|>-
-# | |<|>- +----------+
-# on ------------->+---------------+ `-| argument |
-# : : | class |
-# +---------------+ |==========|
-# on_tail -------->| | |pattern |
-# +---------------+ |----------|
-# OptionParser.accept ->| DefaultList | |converter |
-# reject |(shared between| +----------+
-# | all instances)|
-# +---------------+
-#
-# == OptionParser
-#
-# === Introduction
-#
-# OptionParser is a class for command-line option analysis. It is much more
-# advanced, yet also easier to use, than GetoptLong, and is a more Ruby-oriented
-# solution.
-#
-# === Features
-#
-# 1. The argument specification and the code to handle it are written in the
-# same place.
-# 2. It can output an option summary; you don't need to maintain this string
-# separately.
-# 3. Optional and mandatory arguments are specified very gracefully.
-# 4. Arguments can be automatically converted to a specified class.
-# 5. Arguments can be restricted to a certain set.
-#
-# All of these features are demonstrated in the examples below. See
-# #make_switch for full documentation.
-#
-# === Minimal example
-#
-# require 'optparse'
-#
-# options = {}
-# OptionParser.new do |opts|
-# opts.banner = "Usage: example.rb [options]"
-#
-# opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
-# options[:verbose] = v
-# end
-# end.parse!
-#
-# p options
-# p ARGV
-#
-# === Complete example
-#
-# The following example is a complete Ruby program. You can run it and see the
-# effect of specifying various options. This is probably the best way to learn
-# the features of +optparse+.
-#
-# require 'optparse'
-# require 'optparse/time'
-# require 'ostruct'
-# require 'pp'
-#
-# class OptparseExample
-#
-# CODES = %w[iso-2022-jp shift_jis euc-jp utf8 binary]
-# CODE_ALIASES = { "jis" => "iso-2022-jp", "sjis" => "shift_jis" }
-#
-# #
-# # Return a structure describing the options.
-# #
-# def self.parse(args)
-# # The options specified on the command line will be collected in *options*.
-# # We set default values here.
-# options = OpenStruct.new
-# options.library = []
-# options.inplace = false
-# options.encoding = "utf8"
-# options.transfer_type = :auto
-# options.verbose = false
-#
-# opts = OptionParser.new do |opts|
-# opts.banner = "Usage: example.rb [options]"
-#
-# opts.separator ""
-# opts.separator "Specific options:"
-#
-# # Mandatory argument.
-# opts.on("-r", "--require LIBRARY",
-# "Require the LIBRARY before executing your script") do |lib|
-# options.library << lib
-# end
-#
-# # Optional argument; multi-line description.
-# opts.on("-i", "--inplace [EXTENSION]",
-# "Edit ARGV files in place",
-# " (make backup if EXTENSION supplied)") do |ext|
-# options.inplace = true
-# options.extension = ext || ''
-# options.extension.sub!(/\A\.?(?=.)/, ".") # Ensure extension begins with dot.
-# end
-#
-# # Cast 'delay' argument to a Float.
-# opts.on("--delay N", Float, "Delay N seconds before executing") do |n|
-# options.delay = n
-# end
-#
-# # Cast 'time' argument to a Time object.
-# opts.on("-t", "--time [TIME]", Time, "Begin execution at given time") do |time|
-# options.time = time
-# end
-#
-# # Cast to octal integer.
-# opts.on("-F", "--irs [OCTAL]", OptionParser::OctalInteger,
-# "Specify record separator (default \\0)") do |rs|
-# options.record_separator = rs
-# end
-#
-# # List of arguments.
-# opts.on("--list x,y,z", Array, "Example 'list' of arguments") do |list|
-# options.list = list
-# end
-#
-# # Keyword completion. We are specifying a specific set of arguments (CODES
-# # and CODE_ALIASES - notice the latter is a Hash), and the user may provide
-# # the shortest unambiguous text.
-# code_list = (CODE_ALIASES.keys + CODES).join(',')
-# opts.on("--code CODE", CODES, CODE_ALIASES, "Select encoding",
-# " (#{code_list})") do |encoding|
-# options.encoding = encoding
-# end
-#
-# # Optional argument with keyword completion.
-# opts.on("--type [TYPE]", [:text, :binary, :auto],
-# "Select transfer type (text, binary, auto)") do |t|
-# options.transfer_type = t
-# end
-#
-# # Boolean switch.
-# opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
-# options.verbose = v
-# end
-#
-# opts.separator ""
-# opts.separator "Common options:"
-#
-# # No argument, shows at tail. This will print an options summary.
-# # Try it and see!
-# opts.on_tail("-h", "--help", "Show this message") do
-# puts opts
-# exit
-# end
-#
-# # Another typical switch to print the version.
-# opts.on_tail("--version", "Show version") do
-# puts OptionParser::Version.join('.')
-# exit
-# end
-# end
-#
-# opts.parse!(args)
-# options
-# end # parse()
-#
-# end # class OptparseExample
-#
-# options = OptparseExample.parse(ARGV)
-# pp options
-#
-# === Shell Completion
-#
-# For modern shells (e.g. bash, zsh, etc.), you can use shell
-# completion for command line options.
-#
-# === Further documentation
-#
-# The above examples should be enough to learn how to use this class. If you
-# have any questions, email me (gsinclair@soyabean.com.au) and I will update
-# this document.
-#
-class OptionParser
- # :stopdoc:
- RCSID = %w$Id$[1..-1].each {|s| s.freeze}.freeze
- Version = (RCSID[1].split('.').collect {|s| s.to_i}.extend(Comparable).freeze if RCSID[1])
- LastModified = (Time.gm(*RCSID[2, 2].join('-').scan(/\d+/).collect {|s| s.to_i}) if RCSID[2])
- Release = RCSID[2]
-
- NoArgument = [NO_ARGUMENT = :NONE, nil].freeze
- RequiredArgument = [REQUIRED_ARGUMENT = :REQUIRED, true].freeze
- OptionalArgument = [OPTIONAL_ARGUMENT = :OPTIONAL, false].freeze
- # :startdoc:
-
- #
- # Keyword completion module. This allows partial arguments to be specified
- # and resolved against a list of acceptable values.
- #
- module Completion
- def self.regexp(key, icase)
- Regexp.new('\A' + Regexp.quote(key).gsub(/\w+\b/, '\&\w*'), icase)
- end
-
- def self.candidate(key, icase = false, pat = nil, &block)
- pat ||= Completion.regexp(key, icase)
- candidates = []
- block.call do |k, *v|
- (if Regexp === k
- kn = nil
- k === key
- else
- kn = defined?(k.id2name) ? k.id2name : k
- pat === kn
- end) or next
- v << k if v.empty?
- candidates << [k, v, kn]
- end
- candidates
- end
-
- def candidate(key, icase = false, pat = nil)
- Completion.candidate(key, icase, pat, &method(:each))
- end
-
- public
- def complete(key, icase = false, pat = nil)
- candidates = candidate(key, icase, pat, &method(:each)).sort_by {|k, v, kn| kn.size}
- if candidates.size == 1
- canon, sw, * = candidates[0]
- elsif candidates.size > 1
- canon, sw, cn = candidates.shift
- candidates.each do |k, v, kn|
- next if sw == v
- if String === cn and String === kn
- if cn.rindex(kn, 0)
- canon, sw, cn = k, v, kn
- next
- elsif kn.rindex(cn, 0)
- next
- end
- end
- throw :ambiguous, key
- end
- end
- if canon
- block_given? or return key, *sw
- yield(key, *sw)
- end
- end
-
- def convert(opt = nil, val = nil, *)
- val
- end
- end
-
-
- #
- # Map from option/keyword string to object with completion.
- #
- class OptionMap < Hash
- include Completion
- end
-
-
- #
- # Individual switch class. Not important to the user.
- #
- # Defined within Switch are several Switch-derived classes: NoArgument,
- # RequiredArgument, etc.
- #
- class Switch
- attr_reader :pattern, :conv, :short, :long, :arg, :desc, :block
-
- #
- # Guesses argument style from +arg+. Returns corresponding
- # OptionParser::Switch class (OptionalArgument, etc.).
- #
- def self.guess(arg)
- case arg
- when ""
- t = self
- when /\A=?\[/
- t = Switch::OptionalArgument
- when /\A\s+\[/
- t = Switch::PlacedArgument
- else
- t = Switch::RequiredArgument
- end
- self >= t or incompatible_argument_styles(arg, t)
- t
- end
-
- def self.incompatible_argument_styles(arg, t)
- raise(ArgumentError, "#{arg}: incompatible argument styles\n #{self}, #{t}",
- ParseError.filter_backtrace(caller(2)))
- end
-
- def self.pattern
- NilClass
- end
-
- def initialize(pattern = nil, conv = nil,
- short = nil, long = nil, arg = nil,
- desc = ([] if short or long), block = Proc.new)
- raise if Array === pattern
- @pattern, @conv, @short, @long, @arg, @desc, @block =
- pattern, conv, short, long, arg, desc, block
- end
-
- #
- # Parses +arg+ and returns rest of +arg+ and matched portion to the
- # argument pattern. Yields when the pattern doesn't match substring.
- #
- def parse_arg(arg)
- pattern or return nil, [arg]
- unless m = pattern.match(arg)
- yield(InvalidArgument, arg)
- return arg, []
- end
- if String === m
- m = [s = m]
- else
- m = m.to_a
- s = m[0]
- return nil, m unless String === s
- end
- raise InvalidArgument, arg unless arg.rindex(s, 0)
- return nil, m if s.length == arg.length
- yield(InvalidArgument, arg) # didn't match whole arg
- return arg[s.length..-1], m
- end
- private :parse_arg
-
- #
- # Parses argument, converts and returns +arg+, +block+ and result of
- # conversion. Yields at semi-error condition instead of raising an
- # exception.
- #
- def conv_arg(arg, val = [])
- if conv
- val = conv.call(*val)
- else
- val = proc {|v| v}.call(*val)
- end
- return arg, block, val
- end
- private :conv_arg
-
- #
- # Produces the summary text. Each line of the summary is yielded to the
- # block (without newline).
- #
- # +sdone+:: Already summarized short style options keyed hash.
- # +ldone+:: Already summarized long style options keyed hash.
- # +width+:: Width of left side (option part). In other words, the right
- # side (description part) starts after +width+ columns.
- # +max+:: Maximum width of left side -> the options are filled within
- # +max+ columns.
- # +indent+:: Prefix string indents all summarized lines.
- #
- def summarize(sdone = [], ldone = [], width = 1, max = width - 1, indent = "")
- sopts, lopts = [], [], nil
- @short.each {|s| sdone.fetch(s) {sopts << s}; sdone[s] = true} if @short
- @long.each {|s| ldone.fetch(s) {lopts << s}; ldone[s] = true} if @long
- return if sopts.empty? and lopts.empty? # completely hidden
-
- left = [sopts.join(', ')]
- right = desc.dup
-
- while s = lopts.shift
- l = left[-1].length + s.length
- l += arg.length if left.size == 1 && arg
- l < max or sopts.empty? or left << ''
- left[-1] << if left[-1].empty? then ' ' * 4 else ', ' end << s
- end
-
- if arg
- left[0] << (left[1] ? arg.sub(/\A(\[?)=/, '\1') + ',' : arg)
- end
- mlen = left.collect {|ss| ss.length}.max.to_i
- while mlen > width and l = left.shift
- mlen = left.collect {|ss| ss.length}.max.to_i if l.length == mlen
- if l.length < width and (r = right[0]) and !r.empty?
- l = l.to_s.ljust(width) + ' ' + r
- right.shift
- end
- yield(indent + l)
- end
-
- while begin l = left.shift; r = right.shift; l or r end
- l = l.to_s.ljust(width) + ' ' + r if r and !r.empty?
- yield(indent + l)
- end
-
- self
- end
-
- def add_banner(to) # :nodoc:
- unless @short or @long
- s = desc.join
- to << " [" + s + "]..." unless s.empty?
- end
- to
- end
-
- def match_nonswitch?(str) # :nodoc:
- @pattern =~ str unless @short or @long
- end
-
- #
- # Main name of the switch.
- #
- def switch_name
- (long.first || short.first).sub(/\A-+(?:\[no-\])?/, '')
- end
-
- def compsys(sdone, ldone) # :nodoc:
- sopts, lopts = [], []
- @short.each {|s| sdone.fetch(s) {sopts << s}; sdone[s] = true} if @short
- @long.each {|s| ldone.fetch(s) {lopts << s}; ldone[s] = true} if @long
- return if sopts.empty? and lopts.empty? # completely hidden
-
- (sopts+lopts).each do |opt|
- # "(-x -c -r)-l[left justify]" \
- if opt =~ /^--\[no-\](.+)$/
- o = $1
- yield("--#{o}", desc.join(""))
- yield("--no-#{o}", desc.join(""))
- else
- yield("#{opt}", desc.join(""))
- end
- end
- end
-
- #
- # Switch that takes no arguments.
- #
- class NoArgument < self
-
- #
- # Raises an exception if any arguments given.
- #
- def parse(arg, argv)
- yield(NeedlessArgument, arg) if arg
- conv_arg(arg)
- end
-
- def self.incompatible_argument_styles(*)
- end
-
- def self.pattern
- Object
- end
- end
-
- #
- # Switch that takes an argument.
- #
- class RequiredArgument < self
-
- #
- # Raises an exception if argument is not present.
- #
- def parse(arg, argv)
- unless arg
- raise MissingArgument if argv.empty?
- arg = argv.shift
- end
- conv_arg(*parse_arg(arg, &method(:raise)))
- end
- end
-
- #
- # Switch that can omit argument.
- #
- class OptionalArgument < self
-
- #
- # Parses argument if given, or uses default value.
- #
- def parse(arg, argv, &error)
- if arg
- conv_arg(*parse_arg(arg, &error))
- else
- conv_arg(arg)
- end
- end
- end
-
- #
- # Switch that takes an argument, which does not begin with '-'.
- #
- class PlacedArgument < self
-
- #
- # Returns nil if argument is not present or begins with '-'.
- #
- def parse(arg, argv, &error)
- if !(val = arg) and (argv.empty? or /\A-/ =~ (val = argv[0]))
- return nil, block, nil
- end
- opt = (val = parse_arg(val, &error))[1]
- val = conv_arg(*val)
- if opt and !arg
- argv.shift
- else
- val[0] = nil
- end
- val
- end
- end
- end
-
- #
- # Simple option list providing mapping from short and/or long option
- # string to OptionParser::Switch and mapping from acceptable argument to
- # matching pattern and converter pair. Also provides summary feature.
- #
- class List
- # Map from acceptable argument types to pattern and converter pairs.
- attr_reader :atype
-
- # Map from short style option switches to actual switch objects.
- attr_reader :short
-
- # Map from long style option switches to actual switch objects.
- attr_reader :long
-
- # List of all switches and summary string.
- attr_reader :list
-
- #
- # Just initializes all instance variables.
- #
- def initialize
- @atype = {}
- @short = OptionMap.new
- @long = OptionMap.new
- @list = []
- end
-
- #
- # See OptionParser.accept.
- #
- def accept(t, pat = /.*/m, &block)
- if pat
- pat.respond_to?(:match) or
- raise TypeError, "has no `match'", ParseError.filter_backtrace(caller(2))
- else
- pat = t if t.respond_to?(:match)
- end
- unless block
- block = pat.method(:convert).to_proc if pat.respond_to?(:convert)
- end
- @atype[t] = [pat, block]
- end
-
- #
- # See OptionParser.reject.
- #
- def reject(t)
- @atype.delete(t)
- end
-
- #
- # Adds +sw+ according to +sopts+, +lopts+ and +nlopts+.
- #
- # +sw+:: OptionParser::Switch instance to be added.
- # +sopts+:: Short style option list.
- # +lopts+:: Long style option list.
- # +nlopts+:: Negated long style options list.
- #
- def update(sw, sopts, lopts, nsw = nil, nlopts = nil)
- sopts.each {|o| @short[o] = sw} if sopts
- lopts.each {|o| @long[o] = sw} if lopts
- nlopts.each {|o| @long[o] = nsw} if nsw and nlopts
- used = @short.invert.update(@long.invert)
- @list.delete_if {|o| Switch === o and !used[o]}
- end
- private :update
-
- #
- # Inserts +switch+ at the head of the list, and associates short, long
- # and negated long options. Arguments are:
- #
- # +switch+:: OptionParser::Switch instance to be inserted.
- # +short_opts+:: List of short style options.
- # +long_opts+:: List of long style options.
- # +nolong_opts+:: List of long style options with "no-" prefix.
- #
- # prepend(switch, short_opts, long_opts, nolong_opts)
- #
- def prepend(*args)
- update(*args)
- @list.unshift(args[0])
- end
-
- #
- # Appends +switch+ at the tail of the list, and associates short, long
- # and negated long options. Arguments are:
- #
- # +switch+:: OptionParser::Switch instance to be inserted.
- # +short_opts+:: List of short style options.
- # +long_opts+:: List of long style options.
- # +nolong_opts+:: List of long style options with "no-" prefix.
- #
- # append(switch, short_opts, long_opts, nolong_opts)
- #
- def append(*args)
- update(*args)
- @list.push(args[0])
- end
-
- #
- # Searches +key+ in +id+ list. The result is returned or yielded if a
- # block is given. If it isn't found, nil is returned.
- #
- def search(id, key)
- if list = __send__(id)
- val = list.fetch(key) {return nil}
- block_given? ? yield(val) : val
- end
- end
-
- #
- # Searches list +id+ for +opt+ and the optional patterns for completion
- # +pat+. If +icase+ is true, the search is case insensitive. The result
- # is returned or yielded if a block is given. If it isn't found, nil is
- # returned.
- #
- def complete(id, opt, icase = false, *pat, &block)
- __send__(id).complete(opt, icase, *pat, &block)
- end
-
- #
- # Iterates over each option, passing the option to the +block+.
- #
- def each_option(&block)
- list.each(&block)
- end
-
- #
- # Creates the summary table, passing each line to the +block+ (without
- # newline). The arguments +args+ are passed along to the summarize
- # method which is called on every option.
- #
- def summarize(*args, &block)
- sum = []
- list.reverse_each do |opt|
- if opt.respond_to?(:summarize) # perhaps OptionParser::Switch
- s = []
- opt.summarize(*args) {|l| s << l}
- sum.concat(s.reverse)
- elsif !opt or opt.empty?
- sum << ""
- elsif opt.respond_to?(:each_line)
- sum.concat([*opt.each_line].reverse)
- else
- sum.concat([*opt.each].reverse)
- end
- end
- sum.reverse_each(&block)
- end
-
- def add_banner(to) # :nodoc:
- list.each do |opt|
- if opt.respond_to?(:add_banner)
- opt.add_banner(to)
- end
- end
- to
- end
-
- def compsys(*args, &block) # :nodoc:
- list.each do |opt|
- if opt.respond_to?(:compsys)
- opt.compsys(*args, &block)
- end
- end
- end
- end
-
- #
- # Hash with completion search feature. See OptionParser::Completion.
- #
- class CompletingHash < Hash
- include Completion
-
- #
- # Completion for hash key.
- #
- def match(key)
- *values = fetch(key) {
- raise AmbiguousArgument, catch(:ambiguous) {return complete(key)}
- }
- return key, *values
- end
- end
-
- # :stopdoc:
-
- #
- # Enumeration of acceptable argument styles. Possible values are:
- #
- # NO_ARGUMENT:: The switch takes no arguments. (:NONE)
- # REQUIRED_ARGUMENT:: The switch requires an argument. (:REQUIRED)
- # OPTIONAL_ARGUMENT:: The switch requires an optional argument. (:OPTIONAL)
- #
- # Use like --switch=argument (long style) or -Xargument (short style). For
- # short style, only portion matched to argument pattern is dealed as
- # argument.
- #
- ArgumentStyle = {}
- NoArgument.each {|el| ArgumentStyle[el] = Switch::NoArgument}
- RequiredArgument.each {|el| ArgumentStyle[el] = Switch::RequiredArgument}
- OptionalArgument.each {|el| ArgumentStyle[el] = Switch::OptionalArgument}
- ArgumentStyle.freeze
-
- #
- # Switches common used such as '--', and also provides default
- # argument classes
- #
- DefaultList = List.new
- DefaultList.short['-'] = Switch::NoArgument.new {}
- DefaultList.long[''] = Switch::NoArgument.new {throw :terminate}
-
-
- COMPSYS_HEADER = <<'XXX' # :nodoc:
-
-typeset -A opt_args
-local context state line
-
-_arguments -s -S \
-XXX
-
- def compsys(to, name = File.basename($0)) # :nodoc:
- to << "#compdef #{name}\n"
- to << COMPSYS_HEADER
- visit(:compsys, {}, {}) {|o, d|
- to << %Q[ "#{o}[#{d.gsub(/[\"\[\]]/, '\\\\\&')}]" \\\n]
- }
- to << " '*:file:_files' && return 0\n"
- end
-
- #
- # Default options for ARGV, which never appear in option summary.
- #
- Officious = {}
-
- #
- # --help
- # Shows option summary.
- #
- Officious['help'] = proc do |parser|
- Switch::NoArgument.new do |arg|
- puts parser.help
- exit
- end
- end
-
- #
- # --*-completion-bash=WORD
- # Shows candidates for command line completion.
- #
- Officious['*-completion-bash'] = proc do |parser|
- Switch::RequiredArgument.new do |arg|
- puts parser.candidate(arg)
- exit
- end
- end
-
- #
- # --*-completion-zsh[=NAME:FILE]
- # Creates zsh completion file.
- #
- Officious['*-completion-zsh'] = proc do |parser|
- Switch::OptionalArgument.new do |arg|
- parser.compsys(STDOUT, arg)
- exit
- end
- end
-
- #
- # --version
- # Shows version string if Version is defined.
- #
- Officious['version'] = proc do |parser|
- Switch::OptionalArgument.new do |pkg|
- if pkg
- begin
- require 'optparse/version'
- rescue LoadError
- else
- show_version(*pkg.split(/,/)) or
- abort("#{parser.program_name}: no version found in package #{pkg}")
- exit
- end
- end
- v = parser.ver or abort("#{parser.program_name}: version unknown")
- puts v
- exit
- end
- end
-
- # :startdoc:
-
- #
- # Class methods
- #
-
- #
- # Initializes a new instance and evaluates the optional block in context
- # of the instance. Arguments +args+ are passed to #new, see there for
- # description of parameters.
- #
- # This method is *deprecated*, its behavior corresponds to the older #new
- # method.
- #
- def self.with(*args, &block)
- opts = new(*args)
- opts.instance_eval(&block)
- opts
- end
-
- #
- # Returns an incremented value of +default+ according to +arg+.
- #
- def self.inc(arg, default = nil)
- case arg
- when Integer
- arg.nonzero?
- when nil
- default.to_i + 1
- end
- end
- def inc(*args)
- self.class.inc(*args)
- end
-
- #
- # Initializes the instance and yields itself if called with a block.
- #
- # +banner+:: Banner message.
- # +width+:: Summary width.
- # +indent+:: Summary indent.
- #
- def initialize(banner = nil, width = 32, indent = ' ' * 4)
- @stack = [DefaultList, List.new, List.new]
- @program_name = nil
- @banner = banner
- @summary_width = width
- @summary_indent = indent
- @default_argv = ARGV
- add_officious
- yield self if block_given?
- end
-
- def add_officious # :nodoc:
- list = base()
- Officious.each do |opt, block|
- list.long[opt] ||= block.call(self)
- end
- end
-
- #
- # Terminates option parsing. Optional parameter +arg+ is a string pushed
- # back to be the first non-option argument.
- #
- def terminate(arg = nil)
- self.class.terminate(arg)
- end
- def self.terminate(arg = nil)
- throw :terminate, arg
- end
-
- @stack = [DefaultList]
- def self.top() DefaultList end
-
- #
- # Directs to accept specified class +t+. The argument string is passed to
- # the block in which it should be converted to the desired class.
- #
- # +t+:: Argument class specifier, any object including Class.
- # +pat+:: Pattern for argument, defaults to +t+ if it responds to match.
- #
- # accept(t, pat, &block)
- #
- def accept(*args, &blk) top.accept(*args, &blk) end
- #
- # See #accept.
- #
- def self.accept(*args, &blk) top.accept(*args, &blk) end
-
- #
- # Directs to reject specified class argument.
- #
- # +t+:: Argument class specifier, any object including Class.
- #
- # reject(t)
- #
- def reject(*args, &blk) top.reject(*args, &blk) end
- #
- # See #reject.
- #
- def self.reject(*args, &blk) top.reject(*args, &blk) end
-
- #
- # Instance methods
- #
-
- # Heading banner preceding summary.
- attr_writer :banner
-
- # Program name to be emitted in error message and default banner,
- # defaults to $0.
- attr_writer :program_name
-
- # Width for option list portion of summary. Must be Numeric.
- attr_accessor :summary_width
-
- # Indentation for summary. Must be String (or have + String method).
- attr_accessor :summary_indent
-
- # Strings to be parsed in default.
- attr_accessor :default_argv
-
- #
- # Heading banner preceding summary.
- #
- def banner
- unless @banner
- @banner = "Usage: #{program_name} [options]"
- visit(:add_banner, @banner)
- end
- @banner
- end
-
- #
- # Program name to be emitted in error message and default banner, defaults
- # to $0.
- #
- def program_name
- @program_name || File.basename($0, '.*')
- end
-
- # for experimental cascading :-)
- alias set_banner banner=
- alias set_program_name program_name=
- alias set_summary_width summary_width=
- alias set_summary_indent summary_indent=
-
- # Version
- attr_writer :version
- # Release code
- attr_writer :release
-
- #
- # Version
- #
- def version
- @version || (defined?(::Version) && ::Version)
- end
-
- #
- # Release code
- #
- def release
- @release || (defined?(::Release) && ::Release) || (defined?(::RELEASE) && ::RELEASE)
- end
-
- #
- # Returns version string from program_name, version and release.
- #
- def ver
- if v = version
- str = "#{program_name} #{[v].join('.')}"
- str << " (#{v})" if v = release
- str
- end
- end
-
- def warn(mesg = $!)
- super("#{program_name}: #{mesg}")
- end
-
- def abort(mesg = $!)
- super("#{program_name}: #{mesg}")
- end
-
- #
- # Subject of #on / #on_head, #accept / #reject
- #
- def top
- @stack[-1]
- end
-
- #
- # Subject of #on_tail.
- #
- def base
- @stack[1]
- end
-
- #
- # Pushes a new List.
- #
- def new
- @stack.push(List.new)
- if block_given?
- yield self
- else
- self
- end
- end
-
- #
- # Removes the last List.
- #
- def remove
- @stack.pop
- end
-
- #
- # Puts option summary into +to+ and returns +to+. Yields each line if
- # a block is given.
- #
- # +to+:: Output destination, which must have method <<. Defaults to [].
- # +width+:: Width of left side, defaults to @summary_width.
- # +max+:: Maximum length allowed for left side, defaults to +width+ - 1.
- # +indent+:: Indentation, defaults to @summary_indent.
- #
- def summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent, &blk)
- blk ||= proc {|l| to << (l.index($/, -1) ? l : l + $/)}
- visit(:summarize, {}, {}, width, max, indent, &blk)
- to
- end
-
- #
- # Returns option summary string.
- #
- def help; summarize("#{banner}".sub(/\n?\z/, "\n")) end
- alias to_s help
-
- #
- # Returns option summary list.
- #
- def to_a; summarize("#{banner}".split(/^/)) end
-
- #
- # Checks if an argument is given twice, in which case an ArgumentError is
- # raised. Called from OptionParser#switch only.
- #
- # +obj+:: New argument.
- # +prv+:: Previously specified argument.
- # +msg+:: Exception message.
- #
- def notwice(obj, prv, msg)
- unless !prv or prv == obj
- raise(ArgumentError, "argument #{msg} given twice: #{obj}",
- ParseError.filter_backtrace(caller(2)))
- end
- obj
- end
- private :notwice
-
- SPLAT_PROC = proc {|*a| a.length <= 1 ? a.first : a}
- #
- # Creates an OptionParser::Switch from the parameters. The parsed argument
- # value is passed to the given block, where it can be processed.
- #
- # See at the beginning of OptionParser for some full examples.
- #
- # +opts+ can include the following elements:
- #
- # [Argument style:]
- # One of the following:
- # :NONE, :REQUIRED, :OPTIONAL
- #
- # [Argument pattern:]
- # Acceptable option argument format, must be pre-defined with
- # OptionParser.accept or OptionParser#accept, or Regexp. This can appear
- # once or assigned as String if not present, otherwise causes an
- # ArgumentError. Examples:
- # Float, Time, Array
- #
- # [Possible argument values:]
- # Hash or Array.
- # [:text, :binary, :auto]
- # %w[iso-2022-jp shift_jis euc-jp utf8 binary]
- # { "jis" => "iso-2022-jp", "sjis" => "shift_jis" }
- #
- # [Long style switch:]
- # Specifies a long style switch which takes a mandatory, optional or no
- # argument. It's a string of the following form:
- # "--switch=MANDATORY" or "--switch MANDATORY"
- # "--switch[=OPTIONAL]"
- # "--switch"
- #
- # [Short style switch:]
- # Specifies short style switch which takes a mandatory, optional or no
- # argument. It's a string of the following form:
- # "-xMANDATORY"
- # "-x[OPTIONAL]"
- # "-x"
- # There is also a special form which matches character range (not full
- # set of regular expression):
- # "-[a-z]MANDATORY"
- # "-[a-z][OPTIONAL]"
- # "-[a-z]"
- #
- # [Argument style and description:]
- # Instead of specifying mandatory or optional arguments directly in the
- # switch parameter, this separate parameter can be used.
- # "=MANDATORY"
- # "=[OPTIONAL]"
- #
- # [Description:]
- # Description string for the option.
- # "Run verbosely"
- #
- # [Handler:]
- # Handler for the parsed argument value. Either give a block or pass a
- # Proc or Method as an argument.
- #
- def make_switch(opts, block = nil)
- short, long, nolong, style, pattern, conv, not_pattern, not_conv, not_style = [], [], []
- ldesc, sdesc, desc, arg = [], [], []
- default_style = Switch::NoArgument
- default_pattern = nil
- klass = nil
- q, a = nil
-
- opts.each do |o|
- # argument class
- next if search(:atype, o) do |pat, c|
- klass = notwice(o, klass, 'type')
- if not_style and not_style != Switch::NoArgument
- not_pattern, not_conv = pat, c
- else
- default_pattern, conv = pat, c
- end
- end
-
- # directly specified pattern(any object possible to match)
- if (!(String === o || Symbol === o)) and o.respond_to?(:match)
- pattern = notwice(o, pattern, 'pattern')
- if pattern.respond_to?(:convert)
- conv = pattern.method(:convert).to_proc
- else
- conv = SPLAT_PROC
- end
- next
- end
-
- # anything others
- case o
- when Proc, Method
- block = notwice(o, block, 'block')
- when Array, Hash
- case pattern
- when CompletingHash
- when nil
- pattern = CompletingHash.new
- conv = pattern.method(:convert).to_proc if pattern.respond_to?(:convert)
- else
- raise ArgumentError, "argument pattern given twice"
- end
- o.each {|pat, *v| pattern[pat] = v.fetch(0) {pat}}
- when Module
- raise ArgumentError, "unsupported argument type: #{o}", ParseError.filter_backtrace(caller(4))
- when *ArgumentStyle.keys
- style = notwice(ArgumentStyle[o], style, 'style')
- when /^--no-([^\[\]=\s]*)(.+)?/
- q, a = $1, $2
- o = notwice(a ? Object : TrueClass, klass, 'type')
- not_pattern, not_conv = search(:atype, o) unless not_style
- not_style = (not_style || default_style).guess(arg = a) if a
- default_style = Switch::NoArgument
- default_pattern, conv = search(:atype, FalseClass) unless default_pattern
- ldesc << "--no-#{q}"
- long << 'no-' + (q = q.downcase)
- nolong << q
- when /^--\[no-\]([^\[\]=\s]*)(.+)?/
- q, a = $1, $2
- o = notwice(a ? Object : TrueClass, klass, 'type')
- if a
- default_style = default_style.guess(arg = a)
- default_pattern, conv = search(:atype, o) unless default_pattern
- end
- ldesc << "--[no-]#{q}"
- long << (o = q.downcase)
- not_pattern, not_conv = search(:atype, FalseClass) unless not_style
- not_style = Switch::NoArgument
- nolong << 'no-' + o
- when /^--([^\[\]=\s]*)(.+)?/
- q, a = $1, $2
- if a
- o = notwice(NilClass, klass, 'type')
- default_style = default_style.guess(arg = a)
- default_pattern, conv = search(:atype, o) unless default_pattern
- end
- ldesc << "--#{q}"
- long << (o = q.downcase)
- when /^-(\[\^?\]?(?:[^\\\]]|\\.)*\])(.+)?/
- q, a = $1, $2
- o = notwice(Object, klass, 'type')
- if a
- default_style = default_style.guess(arg = a)
- default_pattern, conv = search(:atype, o) unless default_pattern
- end
- sdesc << "-#{q}"
- short << Regexp.new(q)
- when /^-(.)(.+)?/
- q, a = $1, $2
- if a
- o = notwice(NilClass, klass, 'type')
- default_style = default_style.guess(arg = a)
- default_pattern, conv = search(:atype, o) unless default_pattern
- end
- sdesc << "-#{q}"
- short << q
- when /^=/
- style = notwice(default_style.guess(arg = o), style, 'style')
- default_pattern, conv = search(:atype, Object) unless default_pattern
- else
- desc.push(o)
- end
- end
-
- default_pattern, conv = search(:atype, default_style.pattern) unless default_pattern
- if !(short.empty? and long.empty?)
- s = (style || default_style).new(pattern || default_pattern,
- conv, sdesc, ldesc, arg, desc, block)
- elsif !block
- if style or pattern
- raise ArgumentError, "no switch given", ParseError.filter_backtrace(caller)
- end
- s = desc
- else
- short << pattern
- s = (style || default_style).new(pattern,
- conv, nil, nil, arg, desc, block)
- end
- return s, short, long,
- (not_style.new(not_pattern, not_conv, sdesc, ldesc, nil, desc, block) if not_style),
- nolong
- end
-
- def define(*opts, &block)
- top.append(*(sw = make_switch(opts, block)))
- sw[0]
- end
-
- #
- # Add option switch and handler. See #make_switch for an explanation of
- # parameters.
- #
- def on(*opts, &block)
- define(*opts, &block)
- self
- end
- alias def_option define
-
- def define_head(*opts, &block)
- top.prepend(*(sw = make_switch(opts, block)))
- sw[0]
- end
-
- #
- # Add option switch like with #on, but at head of summary.
- #
- def on_head(*opts, &block)
- define_head(*opts, &block)
- self
- end
- alias def_head_option define_head
-
- def define_tail(*opts, &block)
- base.append(*(sw = make_switch(opts, block)))
- sw[0]
- end
-
- #
- # Add option switch like with #on, but at tail of summary.
- #
- def on_tail(*opts, &block)
- define_tail(*opts, &block)
- self
- end
- alias def_tail_option define_tail
-
- #
- # Add separator in summary.
- #
- def separator(string)
- top.append(string, nil, nil)
- end
-
- #
- # Parses command line arguments +argv+ in order. When a block is given,
- # each non-option argument is yielded.
- #
- # Returns the rest of +argv+ left unparsed.
- #
- def order(*argv, &block)
- argv = argv[0].dup if argv.size == 1 and Array === argv[0]
- order!(argv, &block)
- end
-
- #
- # Same as #order, but removes switches destructively.
- #
- def order!(argv = default_argv, &nonopt)
- parse_in_order(argv, &nonopt)
- end
-
- def parse_in_order(argv = default_argv, setter = nil, &nonopt) # :nodoc:
- opt, arg, val, rest = nil
- nonopt ||= proc {|a| throw :terminate, a}
- argv.unshift(arg) if arg = catch(:terminate) {
- while arg = argv.shift
- case arg
- # long option
- when /\A--([^=]*)(?:=(.*))?/m
- opt, rest = $1, $2
- begin
- sw, = complete(:long, opt, true)
- rescue ParseError
- raise $!.set_option(arg, true)
- end
- begin
- opt, cb, val = sw.parse(rest, argv) {|*exc| raise(*exc)}
- val = cb.call(val) if cb
- setter.call(sw.switch_name, val) if setter
- rescue ParseError
- raise $!.set_option(arg, rest)
- end
-
- # short option
- when /\A-(.)((=).*|.+)?/m
- opt, has_arg, eq, val, rest = $1, $3, $3, $2, $2
- begin
- sw, = search(:short, opt)
- unless sw
- begin
- sw, = complete(:short, opt)
- # short option matched.
- val = arg.sub(/\A-/, '')
- has_arg = true
- rescue InvalidOption
- # if no short options match, try completion with long
- # options.
- sw, = complete(:long, opt)
- eq ||= !rest
- end
- end
- rescue ParseError
- raise $!.set_option(arg, true)
- end
- begin
- opt, cb, val = sw.parse(val, argv) {|*exc| raise(*exc) if eq}
- raise InvalidOption, arg if has_arg and !eq and arg == "-#{opt}"
- argv.unshift(opt) if opt and (!rest or (opt = opt.sub(/\A-*/, '-')) != '-')
- val = cb.call(val) if cb
- setter.call(sw.switch_name, val) if setter
- rescue ParseError
- raise $!.set_option(arg, arg.length > 2)
- end
-
- # non-option argument
- else
- catch(:prune) do
- visit(:each_option) do |sw0|
- sw = sw0
- sw.block.call(arg) if Switch === sw and sw.match_nonswitch?(arg)
- end
- nonopt.call(arg)
- end
- end
- end
-
- nil
- }
-
- visit(:search, :short, nil) {|sw| sw.block.call(*argv) if !sw.pattern}
-
- argv
- end
- private :parse_in_order
-
- #
- # Parses command line arguments +argv+ in permutation mode and returns
- # list of non-option arguments.
- #
- def permute(*argv)
- argv = argv[0].dup if argv.size == 1 and Array === argv[0]
- permute!(argv)
- end
-
- #
- # Same as #permute, but removes switches destructively.
- #
- def permute!(argv = default_argv)
- nonopts = []
- order!(argv, &nonopts.method(:<<))
- argv[0, 0] = nonopts
- argv
- end
-
- #
- # Parses command line arguments +argv+ in order when environment variable
- # POSIXLY_CORRECT is set, and in permutation mode otherwise.
- #
- def parse(*argv)
- argv = argv[0].dup if argv.size == 1 and Array === argv[0]
- parse!(argv)
- end
-
- #
- # Same as #parse, but removes switches destructively.
- #
- def parse!(argv = default_argv)
- if ENV.include?('POSIXLY_CORRECT')
- order!(argv)
- else
- permute!(argv)
- end
- end
-
- #
- # Wrapper method for getopts.rb.
- #
- # params = ARGV.getopts("ab:", "foo", "bar:")
- # # params[:a] = true # -a
- # # params[:b] = "1" # -b1
- # # params[:foo] = "1" # --foo
- # # params[:bar] = "x" # --bar x
- #
- def getopts(*args)
- argv = Array === args.first ? args.shift : default_argv
- single_options, *long_options = *args
-
- result = {}
-
- single_options.scan(/(.)(:)?/) do |opt, val|
- if val
- result[opt] = nil
- define("-#{opt} VAL")
- else
- result[opt] = false
- define("-#{opt}")
- end
- end if single_options
-
- long_options.each do |arg|
- opt, val = arg.split(':', 2)
- if val
- result[opt] = val.empty? ? nil : val
- define("--#{opt} VAL")
- else
- result[opt] = false
- define("--#{opt}")
- end
- end
-
- parse_in_order(argv, result.method(:[]=))
- result
- end
-
- #
- # See #getopts.
- #
- def self.getopts(*args)
- new.getopts(*args)
- end
-
- #
- # Traverses @stack, sending each element method +id+ with +args+ and
- # +block+.
- #
- def visit(id, *args, &block)
- @stack.reverse_each do |el|
- el.send(id, *args, &block)
- end
- nil
- end
- private :visit
-
- #
- # Searches +key+ in @stack for +id+ hash and returns or yields the result.
- #
- def search(id, key)
- block_given = block_given?
- visit(:search, id, key) do |k|
- return block_given ? yield(k) : k
- end
- end
- private :search
-
- #
- # Completes shortened long style option switch and returns pair of
- # canonical switch and switch descriptor OptionParser::Switch.
- #
- # +id+:: Searching table.
- # +opt+:: Searching key.
- # +icase+:: Search case insensitive if true.
- # +pat+:: Optional pattern for completion.
- #
- def complete(typ, opt, icase = false, *pat)
- if pat.empty?
- search(typ, opt) {|sw| return [sw, opt]} # exact match or...
- end
- raise AmbiguousOption, catch(:ambiguous) {
- visit(:complete, typ, opt, icase, *pat) {|o, *sw| return sw}
- raise InvalidOption, opt
- }
- end
- private :complete
-
- def candidate(word)
- list = []
- case word
- when /\A--/
- word, arg = word.split(/=/, 2)
- argpat = Completion.regexp(arg, false) if arg and !arg.empty?
- long = true
- when /\A-(!-)/
- short = true
- when /\A-/
- long = short = true
- end
- pat = Completion.regexp(word, true)
- visit(:each_option) do |opt|
- next unless Switch === opt
- opts = (long ? opt.long : []) + (short ? opt.short : [])
- opts = Completion.candidate(word, true, pat, &opts.method(:each)).map(&:first) if pat
- if /\A=/ =~ opt.arg
- opts.map! {|sw| sw + "="}
- if arg and CompletingHash === opt.pattern
- if opts = opt.pattern.candidate(arg, false, argpat)
- opts.map!(&:last)
- end
- end
- end
- list.concat(opts)
- end
- list
- end
-
- #
- # Loads options from file names as +filename+. Does nothing when the file
- # is not present. Returns whether successfully loaded.
- #
- # +filename+ defaults to basename of the program without suffix in a
- # directory ~/.options.
- #
- def load(filename = nil)
- begin
- filename ||= File.expand_path(File.basename($0, '.*'), '~/.options')
- rescue
- return false
- end
- begin
- parse(*IO.readlines(filename).each {|s| s.chomp!})
- true
- rescue Errno::ENOENT, Errno::ENOTDIR
- false
- end
- end
-
- #
- # Parses environment variable +env+ or its uppercase with splitting like a
- # shell.
- #
- # +env+ defaults to the basename of the program.
- #
- def environment(env = File.basename($0, '.*'))
- env = ENV[env] || ENV[env.upcase] or return
- require 'shellwords'
- parse(*Shellwords.shellwords(env))
- end
-
- #
- # Acceptable argument classes
- #
-
- #
- # Any string and no conversion. This is fall-back.
- #
- accept(Object) {|s,|s or s.nil?}
-
- accept(NilClass) {|s,|s}
-
- #
- # Any non-empty string, and no conversion.
- #
- accept(String, /.+/m) {|s,*|s}
-
- #
- # Ruby/C-like integer, octal for 0-7 sequence, binary for 0b, hexadecimal
- # for 0x, and decimal for others; with optional sign prefix. Converts to
- # Integer.
- #
- decimal = '\d+(?:_\d+)*'
- binary = 'b[01]+(?:_[01]+)*'
- hex = 'x[\da-f]+(?:_[\da-f]+)*'
- octal = "0(?:[0-7]*(?:_[0-7]+)*|#{binary}|#{hex})"
- integer = "#{octal}|#{decimal}"
- accept(Integer, %r"\A[-+]?(?:#{integer})"io) {|s,| Integer(s) if s}
-
- #
- # Float number format, and converts to Float.
- #
- float = "(?:#{decimal}(?:\\.(?:#{decimal})?)?|\\.#{decimal})(?:E[-+]?#{decimal})?"
- floatpat = %r"\A[-+]?#{float}"io
- accept(Float, floatpat) {|s,| s.to_f if s}
-
- #
- # Generic numeric format, converts to Integer for integer format, Float
- # for float format, and Rational for rational format.
- #
- real = "[-+]?(?:#{octal}|#{float})"
- accept(Numeric, /\A(#{real})(?:\/(#{real}))?/io) {|s, d, n|
- if n
- Rational(d, n)
- elsif s
- eval(s)
- end
- }
-
- #
- # Decimal integer format, to be converted to Integer.
- #
- DecimalInteger = /\A[-+]?#{decimal}/io
- accept(DecimalInteger) {|s,| s.to_i if s}
-
- #
- # Ruby/C like octal/hexadecimal/binary integer format, to be converted to
- # Integer.
- #
- OctalInteger = /\A[-+]?(?:[0-7]+(?:_[0-7]+)*|0(?:#{binary}|#{hex}))/io
- accept(OctalInteger) {|s,| s.oct if s}
-
- #
- # Decimal integer/float number format, to be converted to Integer for
- # integer format, Float for float format.
- #
- DecimalNumeric = floatpat # decimal integer is allowed as float also.
- accept(DecimalNumeric) {|s,| eval(s) if s}
-
- #
- # Boolean switch, which means whether it is present or not, whether it is
- # absent or not with prefix no-, or it takes an argument
- # yes/no/true/false/+/-.
- #
- yesno = CompletingHash.new
- %w[- no false].each {|el| yesno[el] = false}
- %w[+ yes true].each {|el| yesno[el] = true}
- yesno['nil'] = false # should be nil?
- accept(TrueClass, yesno) {|arg, val| val == nil or val}
- #
- # Similar to TrueClass, but defaults to false.
- #
- accept(FalseClass, yesno) {|arg, val| val != nil and val}
-
- #
- # List of strings separated by ",".
- #
- accept(Array) do |s,|
- if s
- s = s.split(',').collect {|ss| ss unless ss.empty?}
- end
- s
- end
-
- #
- # Regular expression with options.
- #
- accept(Regexp, %r"\A/((?:\\.|[^\\])*)/([[:alpha:]]+)?\z|.*") do |all, s, o|
- f = 0
- if o
- f |= Regexp::IGNORECASE if /i/ =~ o
- f |= Regexp::MULTILINE if /m/ =~ o
- f |= Regexp::EXTENDED if /x/ =~ o
- k = o.delete("imx")
- k = nil if k.empty?
- end
- Regexp.new(s || all, f, k)
- end
-
- #
- # Exceptions
- #
-
- #
- # Base class of exceptions from OptionParser.
- #
- class ParseError < RuntimeError
- # Reason which caused the error.
- Reason = 'parse error'.freeze
-
- def initialize(*args)
- @args = args
- @reason = nil
- end
-
- attr_reader :args
- attr_writer :reason
-
- #
- # Pushes back erred argument(s) to +argv+.
- #
- def recover(argv)
- argv[0, 0] = @args
- argv
- end
-
- def self.filter_backtrace(array)
- unless $DEBUG
- array.delete_if(&%r"\A#{Regexp.quote(__FILE__)}:"o.method(:=~))
- end
- array
- end
-
- def set_backtrace(array)
- super(self.class.filter_backtrace(array))
- end
-
- def set_option(opt, eq)
- if eq
- @args[0] = opt
- else
- @args.unshift(opt)
- end
- self
- end
-
- #
- # Returns error reason. Override this for I18N.
- #
- def reason
- @reason || self.class::Reason
- end
-
- def inspect
- "#<#{self.class.to_s}: #{args.join(' ')}>"
- end
-
- #
- # Default stringizing method to emit standard error message.
- #
- def message
- reason + ': ' + args.join(' ')
- end
-
- alias to_s message
- end
-
- #
- # Raises when ambiguously completable string is encountered.
- #
- class AmbiguousOption < ParseError
- const_set(:Reason, 'ambiguous option'.freeze)
- end
-
- #
- # Raises when there is an argument for a switch which takes no argument.
- #
- class NeedlessArgument < ParseError
- const_set(:Reason, 'needless argument'.freeze)
- end
-
- #
- # Raises when a switch with mandatory argument has no argument.
- #
- class MissingArgument < ParseError
- const_set(:Reason, 'missing argument'.freeze)
- end
-
- #
- # Raises when switch is undefined.
- #
- class InvalidOption < ParseError
- const_set(:Reason, 'invalid option'.freeze)
- end
-
- #
- # Raises when the given argument does not match required format.
- #
- class InvalidArgument < ParseError
- const_set(:Reason, 'invalid argument'.freeze)
- end
-
- #
- # Raises when the given argument word can't be completed uniquely.
- #
- class AmbiguousArgument < InvalidArgument
- const_set(:Reason, 'ambiguous argument'.freeze)
- end
-
- #
- # Miscellaneous
- #
-
- #
- # Extends command line arguments array (ARGV) to parse itself.
- #
- module Arguable
-
- #
- # Sets OptionParser object, when +opt+ is +false+ or +nil+, methods
- # OptionParser::Arguable#options and OptionParser::Arguable#options= are
- # undefined. Thus, there is no ways to access the OptionParser object
- # via the receiver object.
- #
- def options=(opt)
- unless @optparse = opt
- class << self
- undef_method(:options)
- undef_method(:options=)
- end
- end
- end
-
- #
- # Actual OptionParser object, automatically created if nonexistent.
- #
- # If called with a block, yields the OptionParser object and returns the
- # result of the block. If an OptionParser::ParseError exception occurs
- # in the block, it is rescued, a error message printed to STDERR and
- # +nil+ returned.
- #
- def options
- @optparse ||= OptionParser.new
- @optparse.default_argv = self
- block_given? or return @optparse
- begin
- yield @optparse
- rescue ParseError
- @optparse.warn $!
- nil
- end
- end
-
- #
- # Parses +self+ destructively in order and returns +self+ containing the
- # rest arguments left unparsed.
- #
- def order!(&blk) options.order!(self, &blk) end
-
- #
- # Parses +self+ destructively in permutation mode and returns +self+
- # containing the rest arguments left unparsed.
- #
- def permute!() options.permute!(self) end
-
- #
- # Parses +self+ destructively and returns +self+ containing the
- # rest arguments left unparsed.
- #
- def parse!() options.parse!(self) end
-
- #
- # Substitution of getopts is possible as follows. Also see
- # OptionParser#getopts.
- #
- # def getopts(*args)
- # ($OPT = ARGV.getopts(*args)).each do |opt, val|
- # eval "$OPT_#{opt.gsub(/[^A-Za-z0-9_]/, '_')} = val"
- # end
- # rescue OptionParser::ParseError
- # end
- #
- def getopts(*args)
- options.getopts(self, *args)
- end
-
- #
- # Initializes instance variable.
- #
- def self.extend_object(obj)
- super
- obj.instance_eval {@optparse = nil}
- end
- def initialize(*args)
- super
- @optparse = nil
- end
- end
-
- #
- # Acceptable argument classes. Now contains DecimalInteger, OctalInteger
- # and DecimalNumeric. See Acceptable argument classes (in source code).
- #
- module Acceptables
- const_set(:DecimalInteger, OptionParser::DecimalInteger)
- const_set(:OctalInteger, OptionParser::OctalInteger)
- const_set(:DecimalNumeric, OptionParser::DecimalNumeric)
- end
-end
-
-# ARGV is arguable by OptionParser
-ARGV.extend(OptionParser::Arguable)
-
-if $0 == __FILE__
- Version = OptionParser::Version
- ARGV.options {|q|
- q.parse!.empty? or print "what's #{ARGV.join(' ')}?\n"
- } or abort(ARGV.options.to_s)
-end
diff --git a/ruby_1_9_3/lib/optparse/date.rb b/ruby_1_9_3/lib/optparse/date.rb
deleted file mode 100644
index d680559f37..0000000000
--- a/ruby_1_9_3/lib/optparse/date.rb
+++ /dev/null
@@ -1,17 +0,0 @@
-require 'optparse'
-require 'date'
-
-OptionParser.accept(DateTime) do |s,|
- begin
- DateTime.parse(s) if s
- rescue ArgumentError
- raise OptionParser::InvalidArgument, s
- end
-end
-OptionParser.accept(Date) do |s,|
- begin
- Date.parse(s) if s
- rescue ArgumentError
- raise OptionParser::InvalidArgument, s
- end
-end
diff --git a/ruby_1_9_3/lib/optparse/shellwords.rb b/ruby_1_9_3/lib/optparse/shellwords.rb
deleted file mode 100644
index 0422d7c887..0000000000
--- a/ruby_1_9_3/lib/optparse/shellwords.rb
+++ /dev/null
@@ -1,6 +0,0 @@
-# -*- ruby -*-
-
-require 'shellwords'
-require 'optparse'
-
-OptionParser.accept(Shellwords) {|s,| Shellwords.shellwords(s)}
diff --git a/ruby_1_9_3/lib/optparse/time.rb b/ruby_1_9_3/lib/optparse/time.rb
deleted file mode 100644
index 402cadcf16..0000000000
--- a/ruby_1_9_3/lib/optparse/time.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-require 'optparse'
-require 'time'
-
-OptionParser.accept(Time) do |s,|
- begin
- (Time.httpdate(s) rescue Time.parse(s)) if s
- rescue
- raise OptionParser::InvalidArgument, s
- end
-end
diff --git a/ruby_1_9_3/lib/optparse/uri.rb b/ruby_1_9_3/lib/optparse/uri.rb
deleted file mode 100644
index 024dc69eac..0000000000
--- a/ruby_1_9_3/lib/optparse/uri.rb
+++ /dev/null
@@ -1,6 +0,0 @@
-# -*- ruby -*-
-
-require 'optparse'
-require 'uri'
-
-OptionParser.accept(URI) {|s,| URI.parse(s) if s}
diff --git a/ruby_1_9_3/lib/optparse/version.rb b/ruby_1_9_3/lib/optparse/version.rb
deleted file mode 100644
index 76ed564287..0000000000
--- a/ruby_1_9_3/lib/optparse/version.rb
+++ /dev/null
@@ -1,70 +0,0 @@
-# OptionParser internal utility
-
-class << OptionParser
- def show_version(*pkgs)
- progname = ARGV.options.program_name
- result = false
- show = proc do |klass, cname, version|
- str = "#{progname}"
- unless klass == ::Object and cname == :VERSION
- version = version.join(".") if Array === version
- str << ": #{klass}" unless klass == Object
- str << " version #{version}"
- end
- [:Release, :RELEASE].find do |rel|
- if klass.const_defined?(rel)
- str << " (#{klass.const_get(rel)})"
- end
- end
- puts str
- result = true
- end
- if pkgs.size == 1 and pkgs[0] == "all"
- self.search_const(::Object, /\AV(?:ERSION|ersion)\z/) do |klass, cname, version|
- unless cname[1] == ?e and klass.const_defined?(:Version)
- show.call(klass, cname.intern, version)
- end
- end
- else
- pkgs.each do |pkg|
- begin
- pkg = pkg.split(/::|\//).inject(::Object) {|m, c| m.const_get(c)}
- v = case
- when pkg.const_defined?(:Version)
- pkg.const_get(n = :Version)
- when pkg.const_defined?(:VERSION)
- pkg.const_get(n = :VERSION)
- else
- n = nil
- "unknown"
- end
- show.call(pkg, n, v)
- rescue NameError
- end
- end
- end
- result
- end
-
- def each_const(path, base = ::Object)
- path.split(/::|\//).inject(base) do |klass, name|
- raise NameError, path unless Module === klass
- klass.constants.grep(/#{name}/i) do |c|
- klass.const_defined?(c) or next
- c = klass.const_get(c)
- end
- end
- end
-
- def search_const(klass, name)
- klasses = [klass]
- while klass = klasses.shift
- klass.constants.each do |cname|
- klass.const_defined?(cname) or next
- const = klass.const_get(cname)
- yield klass, cname, const if name === cname
- klasses << const if Module === const and const != ::Object
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/ostruct.rb b/ruby_1_9_3/lib/ostruct.rb
deleted file mode 100644
index a4c0d55d09..0000000000
--- a/ruby_1_9_3/lib/ostruct.rb
+++ /dev/null
@@ -1,236 +0,0 @@
-#
-# = ostruct.rb: OpenStruct implementation
-#
-# Author:: Yukihiro Matsumoto
-# Documentation:: Gavin Sinclair
-#
-# OpenStruct allows the creation of data objects with arbitrary attributes.
-# See OpenStruct for an example.
-#
-
-#
-# An OpenStruct is a data structure, similar to a Hash, that allows the
-# definition of arbitrary attributes with their accompanying values. This is
-# accomplished by using Ruby's metaprogramming to define methods on the class
-# itself.
-#
-# == Examples:
-#
-# require 'ostruct'
-#
-# person = OpenStruct.new
-# person.name = "John Smith"
-# person.age = 70
-# person.pension = 300
-#
-# puts person.name # -> "John Smith"
-# puts person.age # -> 70
-# puts person.address # -> nil
-#
-# An OpenStruct employs a Hash internally to store the methods and values and
-# can even be initialized with one:
-#
-# australia = OpenStruct.new(:country => "Australia", :population => 20_000_000)
-# p australia # -> <OpenStruct country="Australia" population=20000000>
-#
-# Hash keys with spaces or characters that would normally not be able to use for
-# method calls (e.g. ()[]*) will not be immediately available on the
-# OpenStruct object as a method for retrieval or assignment, but can be still be
-# reached through the Object#send method.
-#
-# measurements = OpenStruct.new("length (in inches)" => 24)
-# measurements.send("length (in inches)") # -> 24
-#
-# data_point = OpenStruct.new(:queued? => true)
-# data_point.queued? # -> true
-# data_point.send("queued?=",false)
-# data_point.queued? # -> false
-#
-# Removing the presence of a method requires the execution the delete_field
-# method as setting the property value to +nil+ will not remove the method.
-#
-# first_pet = OpenStruct.new(:name => 'Rowdy', :owner => 'John Smith')
-# first_pet.owner = nil
-# second_pet = OpenStruct.new(:name => 'Rowdy')
-#
-# first_pet == second_pet # -> false
-#
-# first_pet.delete_field(:owner)
-# first_pet == second_pet # -> true
-#
-#
-# == Implementation:
-#
-# An OpenStruct utilizes Ruby's method lookup structure to and find and define
-# the necessary methods for properties. This is accomplished through the method
-# method_missing and define_method.
-#
-# This should be a consideration if there is a concern about the performance of
-# the objects that are created, as there is much more overhead in the setting
-# of these properties compared to using a Hash or a Struct.
-#
-class OpenStruct
- #
- # Creates a new OpenStruct object. By default, the resulting OpenStruct
- # object will have no attributes.
- #
- # The optional +hash+, if given, will generate attributes and values.
- # For example:
- #
- # require 'ostruct'
- # hash = { "country" => "Australia", :population => 20_000_000 }
- # data = OpenStruct.new(hash)
- #
- # p data # -> <OpenStruct country="Australia" population=20000000>
- #
- def initialize(hash=nil)
- @table = {}
- if hash
- for k,v in hash
- @table[k.to_sym] = v
- new_ostruct_member(k)
- end
- end
- end
-
- # Duplicate an OpenStruct object members.
- def initialize_copy(orig)
- super
- @table = @table.dup
- end
-
- #
- # Provides marshalling support for use by the Marshal library. Returning the
- # underlying Hash table that contains the functions defined as the keys and
- # the values assigned to them.
- #
- # require 'ostruct'
- #
- # person = OpenStruct.new
- # person.name = 'John Smith'
- # person.age = 70
- #
- # person.marshal_dump # => { :name => 'John Smith', :age => 70 }
- #
- def marshal_dump
- @table
- end
-
- #
- # Provides marshalling support for use by the Marshal library. Accepting
- # a Hash of keys and values which will be used to populate the internal table
- #
- # require 'ostruct'
- #
- # event = OpenStruct.new
- # hash = { 'time' => Time.now, 'title' => 'Birthday Party' }
- # event.marshal_load(hash)
- # event.title # => 'Birthday Party'
- #
- def marshal_load(x)
- @table = x
- @table.each_key{|key| new_ostruct_member(key)}
- end
-
- #
- # #modifiable is used internally to check if the OpenStruct is able to be
- # modified before granting access to the internal Hash table to be modified.
- #
- def modifiable
- begin
- @modifiable = true
- rescue
- raise TypeError, "can't modify frozen #{self.class}", caller(3)
- end
- @table
- end
- protected :modifiable
-
- #
- # new_ostruct_member is used internally to defined properties on the
- # OpenStruct. It does this by using the metaprogramming function
- # define_method for both the getter method and the setter method.
- #
- def new_ostruct_member(name)
- name = name.to_sym
- unless self.respond_to?(name)
- class << self; self; end.class_eval do
- define_method(name) { @table[name] }
- define_method("#{name}=") { |x| modifiable[name] = x }
- end
- end
- name
- end
-
- def method_missing(mid, *args) # :nodoc:
- mname = mid.id2name
- len = args.length
- if mname.chomp!('=') && mid != :[]=
- if len != 1
- raise ArgumentError, "wrong number of arguments (#{len} for 1)", caller(1)
- end
- modifiable[new_ostruct_member(mname)] = args[0]
- elsif len == 0 && mid != :[]
- @table[mid]
- else
- raise NoMethodError, "undefined method `#{mid}' for #{self}", caller(1)
- end
- end
-
- #
- # Remove the named field from the object. Returns the value that the field
- # contained if it was defined.
- #
- # require 'ostruct'
- #
- # person = OpenStruct.new('name' => 'John Smith', 'age' => 70)
- #
- # person.delete_field('name') # => 'John Smith'
- #
- def delete_field(name)
- sym = name.to_sym
- singleton_class.__send__(:remove_method, sym, "#{name}=")
- @table.delete sym
- end
-
- InspectKey = :__inspect_key__ # :nodoc:
-
- #
- # Returns a string containing a detailed summary of the keys and values.
- #
- def inspect
- str = "#<#{self.class}"
-
- ids = (Thread.current[InspectKey] ||= [])
- if ids.include?(object_id)
- return str << ' ...>'
- end
-
- ids << object_id
- begin
- first = true
- for k,v in @table
- str << "," unless first
- first = false
- str << " #{k}=#{v.inspect}"
- end
- return str << '>'
- ensure
- ids.pop
- end
- end
- alias :to_s :inspect
-
- attr_reader :table # :nodoc:
- protected :table
-
- #
- # Compares this object and +other+ for equality. An OpenStruct is equal to
- # +other+ when +other+ is an OpenStruct and the two object's Hash tables are
- # equal.
- #
- def ==(other)
- return false unless(other.kind_of?(OpenStruct))
- return @table == other.table
- end
-end
diff --git a/ruby_1_9_3/lib/pp.rb b/ruby_1_9_3/lib/pp.rb
deleted file mode 100644
index 56d726dc7d..0000000000
--- a/ruby_1_9_3/lib/pp.rb
+++ /dev/null
@@ -1,524 +0,0 @@
-# == Pretty-printer for Ruby objects.
-#
-# = Which seems better?
-#
-# non-pretty-printed output by #p is:
-# #<PP:0x81fedf0 @genspace=#<Proc:0x81feda0>, @group_queue=#<PrettyPrint::GroupQueue:0x81fed3c @queue=[[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], []]>, @buffer=[], @newline="\n", @group_stack=[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], @buffer_width=0, @indent=0, @maxwidth=79, @output_width=2, @output=#<IO:0x8114ee4>>
-#
-# pretty-printed output by #pp is:
-# #<PP:0x81fedf0
-# @buffer=[],
-# @buffer_width=0,
-# @genspace=#<Proc:0x81feda0>,
-# @group_queue=
-# #<PrettyPrint::GroupQueue:0x81fed3c
-# @queue=
-# [[#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>],
-# []]>,
-# @group_stack=
-# [#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>],
-# @indent=0,
-# @maxwidth=79,
-# @newline="\n",
-# @output=#<IO:0x8114ee4>,
-# @output_width=2>
-#
-# I like the latter. If you do too, this library is for you.
-#
-# = Usage
-#
-# pp(obj)
-#
-# output +obj+ to +$>+ in pretty printed format.
-#
-# It returns +nil+.
-#
-# = Output Customization
-# To define your customized pretty printing function for your classes,
-# redefine a method #pretty_print(+pp+) in the class.
-# It takes an argument +pp+ which is an instance of the class PP.
-# The method should use PP#text, PP#breakable, PP#nest, PP#group and
-# PP#pp to print the object.
-#
-# = Author
-# Tanaka Akira <akr@m17n.org>
-
-require 'prettyprint'
-
-module Kernel
- # returns a pretty printed object as a string.
- def pretty_inspect
- PP.pp(self, '')
- end
-
- private
- # prints arguments in pretty form.
- #
- # pp returns argument(s).
- def pp(*objs) # :doc:
- objs.each {|obj|
- PP.pp(obj)
- }
- objs.size <= 1 ? objs.first : objs
- end
- module_function :pp
-end
-
-class PP < PrettyPrint
- # Outputs +obj+ to +out+ in pretty printed format of
- # +width+ columns in width.
- #
- # If +out+ is omitted, +$>+ is assumed.
- # If +width+ is omitted, 79 is assumed.
- #
- # PP.pp returns +out+.
- def PP.pp(obj, out=$>, width=79)
- q = PP.new(out, width)
- q.guard_inspect_key {q.pp obj}
- q.flush
- #$pp = q
- out << "\n"
- end
-
- # Outputs +obj+ to +out+ like PP.pp but with no indent and
- # newline.
- #
- # PP.singleline_pp returns +out+.
- def PP.singleline_pp(obj, out=$>)
- q = SingleLine.new(out)
- q.guard_inspect_key {q.pp obj}
- q.flush
- out
- end
-
- # :stopdoc:
- def PP.mcall(obj, mod, meth, *args, &block)
- mod.instance_method(meth).bind(obj).call(*args, &block)
- end
- # :startdoc:
-
- @sharing_detection = false
- class << self
- # Returns the sharing detection flag as a boolean value.
- # It is false by default.
- attr_accessor :sharing_detection
- end
-
- module PPMethods
- def guard_inspect_key
- if Thread.current[:__recursive_key__] == nil
- Thread.current[:__recursive_key__] = {}.untrust
- end
-
- if Thread.current[:__recursive_key__][:inspect] == nil
- Thread.current[:__recursive_key__][:inspect] = {}.untrust
- end
-
- save = Thread.current[:__recursive_key__][:inspect]
-
- begin
- Thread.current[:__recursive_key__][:inspect] = {}.untrust
- yield
- ensure
- Thread.current[:__recursive_key__][:inspect] = save
- end
- end
-
- def check_inspect_key(id)
- Thread.current[:__recursive_key__] &&
- Thread.current[:__recursive_key__][:inspect] &&
- Thread.current[:__recursive_key__][:inspect].include?(id)
- end
- def push_inspect_key(id)
- Thread.current[:__recursive_key__][:inspect][id] = true
- end
- def pop_inspect_key(id)
- Thread.current[:__recursive_key__][:inspect].delete id
- end
-
- # Adds +obj+ to the pretty printing buffer
- # using Object#pretty_print or Object#pretty_print_cycle.
- #
- # Object#pretty_print_cycle is used when +obj+ is already
- # printed, a.k.a the object reference chain has a cycle.
- def pp(obj)
- id = obj.object_id
-
- if check_inspect_key(id)
- group {obj.pretty_print_cycle self}
- return
- end
-
- begin
- push_inspect_key(id)
- group {obj.pretty_print self}
- ensure
- pop_inspect_key(id) unless PP.sharing_detection
- end
- end
-
- # A convenience method which is same as follows:
- #
- # group(1, '#<' + obj.class.name, '>') { ... }
- def object_group(obj, &block) # :yield:
- group(1, '#<' + obj.class.name, '>', &block)
- end
-
- PointerMask = (1 << ([""].pack("p").size * 8)) - 1
-
- case Object.new.inspect
- when /\A\#<Object:0x([0-9a-f]+)>\z/
- PointerFormat = "%0#{$1.length}x"
- else
- PointerFormat = "%x"
- end
-
- def object_address_group(obj, &block)
- id = PointerFormat % (obj.object_id * 2 & PointerMask)
- group(1, "\#<#{obj.class}:0x#{id}", '>', &block)
- end
-
- # A convenience method which is same as follows:
- #
- # text ','
- # breakable
- def comma_breakable
- text ','
- breakable
- end
-
- # Adds a separated list.
- # The list is separated by comma with breakable space, by default.
- #
- # #seplist iterates the +list+ using +iter_method+.
- # It yields each object to the block given for #seplist.
- # The procedure +separator_proc+ is called between each yields.
- #
- # If the iteration is zero times, +separator_proc+ is not called at all.
- #
- # If +separator_proc+ is nil or not given,
- # +lambda { comma_breakable }+ is used.
- # If +iter_method+ is not given, :each is used.
- #
- # For example, following 3 code fragments has similar effect.
- #
- # q.seplist([1,2,3]) {|v| xxx v }
- #
- # q.seplist([1,2,3], lambda { q.comma_breakable }, :each) {|v| xxx v }
- #
- # xxx 1
- # q.comma_breakable
- # xxx 2
- # q.comma_breakable
- # xxx 3
- def seplist(list, sep=nil, iter_method=:each) # :yield: element
- sep ||= lambda { comma_breakable }
- first = true
- list.__send__(iter_method) {|*v|
- if first
- first = false
- else
- sep.call
- end
- yield(*v)
- }
- end
-
- def pp_object(obj)
- object_address_group(obj) {
- seplist(obj.pretty_print_instance_variables, lambda { text ',' }) {|v|
- breakable
- v = v.to_s if Symbol === v
- text v
- text '='
- group(1) {
- breakable ''
- pp(obj.instance_eval(v))
- }
- }
- }
- end
-
- def pp_hash(obj)
- group(1, '{', '}') {
- seplist(obj, nil, :each_pair) {|k, v|
- group {
- pp k
- text '=>'
- group(1) {
- breakable ''
- pp v
- }
- }
- }
- }
- end
- end
-
- include PPMethods
-
- class SingleLine < PrettyPrint::SingleLine
- include PPMethods
- end
-
- module ObjectMixin
- # 1. specific pretty_print
- # 2. specific inspect
- # 3. specific to_s
- # 4. generic pretty_print
-
- # A default pretty printing method for general objects.
- # It calls #pretty_print_instance_variables to list instance variables.
- #
- # If +self+ has a customized (redefined) #inspect method,
- # the result of self.inspect is used but it obviously has no
- # line break hints.
- #
- # This module provides predefined #pretty_print methods for some of
- # the most commonly used built-in classes for convenience.
- def pretty_print(q)
- method_method = Object.instance_method(:method).bind(self)
- begin
- inspect_method = method_method.call(:inspect)
- rescue NameError
- end
- begin
- to_s_method = method_method.call(:to_s)
- rescue NameError
- end
- if inspect_method && /\(Kernel\)#/ !~ inspect_method.inspect
- q.text self.inspect
- elsif !inspect_method && self.respond_to?(:inspect)
- q.text self.inspect
- elsif to_s_method && /\(Kernel\)#/ !~ to_s_method.inspect
- q.text self.to_s
- elsif !to_s_method && self.respond_to?(:to_s)
- q.text self.to_s
- else
- q.pp_object(self)
- end
- end
-
- # A default pretty printing method for general objects that are
- # detected as part of a cycle.
- def pretty_print_cycle(q)
- q.object_address_group(self) {
- q.breakable
- q.text '...'
- }
- end
-
- # Returns a sorted array of instance variable names.
- #
- # This method should return an array of names of instance variables as symbols or strings as:
- # +[:@a, :@b]+.
- def pretty_print_instance_variables
- instance_variables.sort
- end
-
- # Is #inspect implementation using #pretty_print.
- # If you implement #pretty_print, it can be used as follows.
- #
- # alias inspect pretty_print_inspect
- #
- # However, doing this requires that every class that #inspect is called on
- # implement #pretty_print, or a RuntimeError will be raised.
- def pretty_print_inspect
- if /\(PP::ObjectMixin\)#/ =~ Object.instance_method(:method).bind(self).call(:pretty_print).inspect
- raise "pretty_print is not overridden for #{self.class}"
- end
- PP.singleline_pp(self, '')
- end
- end
-end
-
-class Array
- def pretty_print(q)
- q.group(1, '[', ']') {
- q.seplist(self) {|v|
- q.pp v
- }
- }
- end
-
- def pretty_print_cycle(q)
- q.text(empty? ? '[]' : '[...]')
- end
-end
-
-class Hash
- def pretty_print(q)
- q.pp_hash self
- end
-
- def pretty_print_cycle(q)
- q.text(empty? ? '{}' : '{...}')
- end
-end
-
-class << ENV
- def pretty_print(q)
- h = {}
- ENV.keys.sort.each {|k|
- h[k] = ENV[k]
- }
- q.pp_hash h
- end
-end
-
-class Struct
- def pretty_print(q)
- q.group(1, sprintf("#<struct %s", PP.mcall(self, Kernel, :class).name), '>') {
- q.seplist(PP.mcall(self, Struct, :members), lambda { q.text "," }) {|member|
- q.breakable
- q.text member.to_s
- q.text '='
- q.group(1) {
- q.breakable ''
- q.pp self[member]
- }
- }
- }
- end
-
- def pretty_print_cycle(q)
- q.text sprintf("#<struct %s:...>", PP.mcall(self, Kernel, :class).name)
- end
-end
-
-class Range
- def pretty_print(q)
- q.pp self.begin
- q.breakable ''
- q.text(self.exclude_end? ? '...' : '..')
- q.breakable ''
- q.pp self.end
- end
-end
-
-class File < IO
- class Stat
- def pretty_print(q)
- require 'etc.so'
- q.object_group(self) {
- q.breakable
- q.text sprintf("dev=0x%x", self.dev); q.comma_breakable
- q.text "ino="; q.pp self.ino; q.comma_breakable
- q.group {
- m = self.mode
- q.text sprintf("mode=0%o", m)
- q.breakable
- q.text sprintf("(%s %c%c%c%c%c%c%c%c%c)",
- self.ftype,
- (m & 0400 == 0 ? ?- : ?r),
- (m & 0200 == 0 ? ?- : ?w),
- (m & 0100 == 0 ? (m & 04000 == 0 ? ?- : ?S) :
- (m & 04000 == 0 ? ?x : ?s)),
- (m & 0040 == 0 ? ?- : ?r),
- (m & 0020 == 0 ? ?- : ?w),
- (m & 0010 == 0 ? (m & 02000 == 0 ? ?- : ?S) :
- (m & 02000 == 0 ? ?x : ?s)),
- (m & 0004 == 0 ? ?- : ?r),
- (m & 0002 == 0 ? ?- : ?w),
- (m & 0001 == 0 ? (m & 01000 == 0 ? ?- : ?T) :
- (m & 01000 == 0 ? ?x : ?t)))
- }
- q.comma_breakable
- q.text "nlink="; q.pp self.nlink; q.comma_breakable
- q.group {
- q.text "uid="; q.pp self.uid
- begin
- pw = Etc.getpwuid(self.uid)
- rescue ArgumentError
- end
- if pw
- q.breakable; q.text "(#{pw.name})"
- end
- }
- q.comma_breakable
- q.group {
- q.text "gid="; q.pp self.gid
- begin
- gr = Etc.getgrgid(self.gid)
- rescue ArgumentError
- end
- if gr
- q.breakable; q.text "(#{gr.name})"
- end
- }
- q.comma_breakable
- q.group {
- q.text sprintf("rdev=0x%x", self.rdev)
- q.breakable
- q.text sprintf('(%d, %d)', self.rdev_major, self.rdev_minor)
- }
- q.comma_breakable
- q.text "size="; q.pp self.size; q.comma_breakable
- q.text "blksize="; q.pp self.blksize; q.comma_breakable
- q.text "blocks="; q.pp self.blocks; q.comma_breakable
- q.group {
- t = self.atime
- q.text "atime="; q.pp t
- q.breakable; q.text "(#{t.tv_sec})"
- }
- q.comma_breakable
- q.group {
- t = self.mtime
- q.text "mtime="; q.pp t
- q.breakable; q.text "(#{t.tv_sec})"
- }
- q.comma_breakable
- q.group {
- t = self.ctime
- q.text "ctime="; q.pp t
- q.breakable; q.text "(#{t.tv_sec})"
- }
- }
- end
- end
-end
-
-class MatchData
- def pretty_print(q)
- nc = []
- self.regexp.named_captures.each {|name, indexes|
- indexes.each {|i| nc[i] = name }
- }
- q.object_group(self) {
- q.breakable
- q.seplist(0...self.size, lambda { q.breakable }) {|i|
- if i == 0
- q.pp self[i]
- else
- if nc[i]
- q.text nc[i]
- else
- q.pp i
- end
- q.text ':'
- q.pp self[i]
- end
- }
- }
- end
-end
-
-class Object < BasicObject
- include PP::ObjectMixin
-end
-
-[Numeric, Symbol, FalseClass, TrueClass, NilClass, Module].each {|c|
- c.class_eval {
- def pretty_print_cycle(q)
- q.text inspect
- end
- }
-}
-
-[Numeric, FalseClass, TrueClass, Module].each {|c|
- c.class_eval {
- def pretty_print(q)
- q.text inspect
- end
- }
-}
diff --git a/ruby_1_9_3/lib/prettyprint.rb b/ruby_1_9_3/lib/prettyprint.rb
deleted file mode 100644
index 9a90713a4d..0000000000
--- a/ruby_1_9_3/lib/prettyprint.rb
+++ /dev/null
@@ -1,395 +0,0 @@
-# This class implements a pretty printing algorithm. It finds line breaks and
-# nice indentations for grouped structure.
-#
-# By default, the class assumes that primitive elements are strings and each
-# byte in the strings have single column in width. But it can be used for
-# other situations by giving suitable arguments for some methods:
-# * newline object and space generation block for PrettyPrint.new
-# * optional width argument for PrettyPrint#text
-# * PrettyPrint#breakable
-#
-# There are several candidate uses:
-# * text formatting using proportional fonts
-# * multibyte characters which has columns different to number of bytes
-# * non-string formatting
-#
-# == Bugs
-# * Box based formatting?
-# * Other (better) model/algorithm?
-#
-# == References
-# Christian Lindig, Strictly Pretty, March 2000,
-# http://www.st.cs.uni-sb.de/~lindig/papers/#pretty
-#
-# Philip Wadler, A prettier printer, March 1998,
-# http://homepages.inf.ed.ac.uk/wadler/topics/language-design.html#prettier
-#
-# == Author
-# Tanaka Akira <akr@m17n.org>
-#
-class PrettyPrint
-
- # This is a convenience method which is same as follows:
- #
- # begin
- # q = PrettyPrint.new(output, maxwidth, newline, &genspace)
- # ...
- # q.flush
- # output
- # end
- #
- def PrettyPrint.format(output='', maxwidth=79, newline="\n", genspace=lambda {|n| ' ' * n})
- q = PrettyPrint.new(output, maxwidth, newline, &genspace)
- yield q
- q.flush
- output
- end
-
- # This is similar to PrettyPrint::format but the result has no breaks.
- #
- # +maxwidth+, +newline+ and +genspace+ are ignored.
- #
- # The invocation of +breakable+ in the block doesn't break a line and is
- # treated as just an invocation of +text+.
- #
- def PrettyPrint.singleline_format(output='', maxwidth=nil, newline=nil, genspace=nil)
- q = SingleLine.new(output)
- yield q
- output
- end
-
- # Creates a buffer for pretty printing.
- #
- # +output+ is an output target. If it is not specified, '' is assumed. It
- # should have a << method which accepts the first argument +obj+ of
- # PrettyPrint#text, the first argument +sep+ of PrettyPrint#breakable, the
- # first argument +newline+ of PrettyPrint.new, and the result of a given
- # block for PrettyPrint.new.
- #
- # +maxwidth+ specifies maximum line length. If it is not specified, 79 is
- # assumed. However actual outputs may overflow +maxwidth+ if long
- # non-breakable texts are provided.
- #
- # +newline+ is used for line breaks. "\n" is used if it is not specified.
- #
- # The block is used to generate spaces. {|width| ' ' * width} is used if it
- # is not given.
- #
- def initialize(output='', maxwidth=79, newline="\n", &genspace)
- @output = output
- @maxwidth = maxwidth
- @newline = newline
- @genspace = genspace || lambda {|n| ' ' * n}
-
- @output_width = 0
- @buffer_width = 0
- @buffer = []
-
- root_group = Group.new(0)
- @group_stack = [root_group]
- @group_queue = GroupQueue.new(root_group)
- @indent = 0
- end
- attr_reader :output, :maxwidth, :newline, :genspace
- attr_reader :indent, :group_queue
-
- # Returns the group most recently added to the stack.
- def current_group
- @group_stack.last
- end
-
- # first? is a predicate to test the call is a first call to first? with
- # current group.
- #
- # It is useful to format comma separated values as:
- #
- # q.group(1, '[', ']') {
- # xxx.each {|yyy|
- # unless q.first?
- # q.text ','
- # q.breakable
- # end
- # ... pretty printing yyy ...
- # }
- # }
- #
- # first? is obsoleted in 1.8.2.
- #
- def first?
- warn "PrettyPrint#first? is obsoleted at 1.8.2."
- current_group.first?
- end
-
- # Breaks the buffer into lines that are shorter than #maxwidth
- def break_outmost_groups
- while @maxwidth < @output_width + @buffer_width
- return unless group = @group_queue.deq
- until group.breakables.empty?
- data = @buffer.shift
- @output_width = data.output(@output, @output_width)
- @buffer_width -= data.width
- end
- while !@buffer.empty? && Text === @buffer.first
- text = @buffer.shift
- @output_width = text.output(@output, @output_width)
- @buffer_width -= text.width
- end
- end
- end
-
- # This adds +obj+ as a text of +width+ columns in width.
- #
- # If +width+ is not specified, obj.length is used.
- #
- def text(obj, width=obj.length)
- if @buffer.empty?
- @output << obj
- @output_width += width
- else
- text = @buffer.last
- unless Text === text
- text = Text.new
- @buffer << text
- end
- text.add(obj, width)
- @buffer_width += width
- break_outmost_groups
- end
- end
-
- # This is similar to #breakable except
- # the decision to break or not is determined individually.
- #
- # Two #fill_breakable under a group may cause 4 results:
- # (break,break), (break,non-break), (non-break,break), (non-break,non-break).
- # This is different to #breakable because two #breakable under a group
- # may cause 2 results:
- # (break,break), (non-break,non-break).
- #
- # The text sep+ is inserted if a line is not broken at this point.
- #
- # If +sep+ is not specified, " " is used.
- #
- # If +width+ is not specified, +sep.length+ is used. You will have to
- # specify this when +sep+ is a multibyte character, for example.
- #
- def fill_breakable(sep=' ', width=sep.length)
- group { breakable sep, width }
- end
-
- # This says "you can break a line here if necessary", and a +width+\-column
- # text +sep+ is inserted if a line is not broken at the point.
- #
- # If +sep+ is not specified, " " is used.
- #
- # If +width+ is not specified, +sep.length+ is used. You will have to
- # specify this when +sep+ is a multibyte character, for example.
- #
- def breakable(sep=' ', width=sep.length)
- group = @group_stack.last
- if group.break?
- flush
- @output << @newline
- @output << @genspace.call(@indent)
- @output_width = @indent
- @buffer_width = 0
- else
- @buffer << Breakable.new(sep, width, self)
- @buffer_width += width
- break_outmost_groups
- end
- end
-
- # Groups line break hints added in the block. The line break hints are all
- # to be used or not.
- #
- # If +indent+ is specified, the method call is regarded as nested by
- # nest(indent) { ... }.
- #
- # If +open_obj+ is specified, <tt>text open_obj, open_width</tt> is called
- # before grouping. If +close_obj+ is specified, <tt>text close_obj,
- # close_width</tt> is called after grouping.
- #
- def group(indent=0, open_obj='', close_obj='', open_width=open_obj.length, close_width=close_obj.length)
- text open_obj, open_width
- group_sub {
- nest(indent) {
- yield
- }
- }
- text close_obj, close_width
- end
-
- def group_sub
- group = Group.new(@group_stack.last.depth + 1)
- @group_stack.push group
- @group_queue.enq group
- begin
- yield
- ensure
- @group_stack.pop
- if group.breakables.empty?
- @group_queue.delete group
- end
- end
- end
-
- # Increases left margin after newline with +indent+ for line breaks added in
- # the block.
- #
- def nest(indent)
- @indent += indent
- begin
- yield
- ensure
- @indent -= indent
- end
- end
-
- # outputs buffered data.
- #
- def flush
- @buffer.each {|data|
- @output_width = data.output(@output, @output_width)
- }
- @buffer.clear
- @buffer_width = 0
- end
-
- class Text
- def initialize
- @objs = []
- @width = 0
- end
- attr_reader :width
-
- def output(out, output_width)
- @objs.each {|obj| out << obj}
- output_width + @width
- end
-
- def add(obj, width)
- @objs << obj
- @width += width
- end
- end
-
- class Breakable
- def initialize(sep, width, q)
- @obj = sep
- @width = width
- @pp = q
- @indent = q.indent
- @group = q.current_group
- @group.breakables.push self
- end
- attr_reader :obj, :width, :indent
-
- def output(out, output_width)
- @group.breakables.shift
- if @group.break?
- out << @pp.newline
- out << @pp.genspace.call(@indent)
- @indent
- else
- @pp.group_queue.delete @group if @group.breakables.empty?
- out << @obj
- output_width + @width
- end
- end
- end
-
- class Group
- def initialize(depth)
- @depth = depth
- @breakables = []
- @break = false
- end
- attr_reader :depth, :breakables
-
- def break
- @break = true
- end
-
- def break?
- @break
- end
-
- def first?
- if defined? @first
- false
- else
- @first = false
- true
- end
- end
- end
-
- class GroupQueue
- def initialize(*groups)
- @queue = []
- groups.each {|g| enq g}
- end
-
- def enq(group)
- depth = group.depth
- @queue << [] until depth < @queue.length
- @queue[depth] << group
- end
-
- def deq
- @queue.each {|gs|
- (gs.length-1).downto(0) {|i|
- unless gs[i].breakables.empty?
- group = gs.slice!(i, 1).first
- group.break
- return group
- end
- }
- gs.each {|group| group.break}
- gs.clear
- }
- return nil
- end
-
- def delete(group)
- @queue[group.depth].delete(group)
- end
- end
-
- class SingleLine
- def initialize(output, maxwidth=nil, newline=nil)
- @output = output
- @first = [true]
- end
-
- def text(obj, width=nil)
- @output << obj
- end
-
- def breakable(sep=' ', width=nil)
- @output << sep
- end
-
- def nest(indent)
- yield
- end
-
- def group(indent=nil, open_obj='', close_obj='', open_width=nil, close_width=nil)
- @first.push true
- @output << open_obj
- yield
- @output << close_obj
- @first.pop
- end
-
- def flush
- end
-
- def first?
- result = @first[-1]
- @first[-1] = false
- result
- end
- end
-end
diff --git a/ruby_1_9_3/lib/prime.rb b/ruby_1_9_3/lib/prime.rb
deleted file mode 100644
index 4a20d93fb7..0000000000
--- a/ruby_1_9_3/lib/prime.rb
+++ /dev/null
@@ -1,509 +0,0 @@
-#
-# = prime.rb
-#
-# Prime numbers and factorization library.
-#
-# Copyright::
-# Copyright (c) 1998-2008 Keiju ISHITSUKA(SHL Japan Inc.)
-# Copyright (c) 2008 Yuki Sonoda (Yugui) <yugui@yugui.jp>
-#
-# Documentation::
-# Yuki Sonoda
-#
-
-require "singleton"
-require "forwardable"
-
-class Integer
- # Re-composes a prime factorization and returns the product.
- #
- # See Prime#int_from_prime_division for more details.
- def Integer.from_prime_division(pd)
- Prime.int_from_prime_division(pd)
- end
-
- # Returns the factorization of +self+.
- #
- # See Prime#prime_division for more details.
- def prime_division(generator = Prime::Generator23.new)
- Prime.prime_division(self, generator)
- end
-
- # Returns true if +self+ is a prime number, false for a composite.
- def prime?
- Prime.prime?(self)
- end
-
- # Iterates the given block over all prime numbers.
- #
- # See +Prime+#each for more details.
- def Integer.each_prime(ubound, &block) # :yields: prime
- Prime.each(ubound, &block)
- end
-end
-
-#
-# The set of all prime numbers.
-#
-# == Example
-#
-# Prime.each(100) do |prime|
-# p prime #=> 2, 3, 5, 7, 11, ...., 97
-# end
-#
-# Prime is Enumerable:
-#
-# Prime.first 5 # => [2, 3, 5, 7, 11]
-#
-# == Retrieving the instance
-#
-# +Prime+.new is obsolete. Now +Prime+ has the default instance and you can
-# access it as +Prime+.instance.
-#
-# For convenience, each instance method of +Prime+.instance can be accessed
-# as a class method of +Prime+.
-#
-# e.g.
-# Prime.instance.prime?(2) #=> true
-# Prime.prime?(2) #=> true
-#
-# == Generators
-#
-# A "generator" provides an implementation of enumerating pseudo-prime
-# numbers and it remembers the position of enumeration and upper bound.
-# Futhermore, it is a external iterator of prime enumeration which is
-# compatible to an Enumerator.
-#
-# +Prime+::+PseudoPrimeGenerator+ is the base class for generators.
-# There are few implementations of generator.
-#
-# [+Prime+::+EratosthenesGenerator+]
-# Uses eratosthenes's sieve.
-# [+Prime+::+TrialDivisionGenerator+]
-# Uses the trial division method.
-# [+Prime+::+Generator23+]
-# Generates all positive integers which is not divided by 2 nor 3.
-# This sequence is very bad as a pseudo-prime sequence. But this
-# is faster and uses much less memory than other generators. So,
-# it is suitable for factorizing an integer which is not large but
-# has many prime factors. e.g. for Prime#prime? .
-
-class Prime
- include Enumerable
- @the_instance = Prime.new
-
- # obsolete. Use +Prime+::+instance+ or class methods of +Prime+.
- def initialize
- @generator = EratosthenesGenerator.new
- extend OldCompatibility
- warn "Prime::new is obsolete. use Prime::instance or class methods of Prime."
- end
-
- class << self
- extend Forwardable
- include Enumerable
- # Returns the default instance of Prime.
- def instance; @the_instance end
-
- def method_added(method) # :nodoc:
- (class<< self;self;end).def_delegator :instance, method
- end
- end
-
- # Iterates the given block over all prime numbers.
- #
- # == Parameters
- #
- # +ubound+::
- # Optional. An arbitrary positive number.
- # The upper bound of enumeration. The method enumerates
- # prime numbers infinitely if +ubound+ is nil.
- # +generator+::
- # Optional. An implementation of pseudo-prime generator.
- #
- # == Return value
- #
- # An evaluated value of the given block at the last time.
- # Or an enumerator which is compatible to an +Enumerator+
- # if no block given.
- #
- # == Description
- #
- # Calls +block+ once for each prime number, passing the prime as
- # a parameter.
- #
- # +ubound+::
- # Upper bound of prime numbers. The iterator stops after
- # yields all prime numbers p <= +ubound+.
- #
- # == Note
- #
- # +Prime+.+new+ returns a object extended by +Prime+::+OldCompatibility+
- # in order to compatibility to Ruby 1.8, and +Prime+#each is overwritten
- # by +Prime+::+OldCompatibility+#+each+.
- #
- # +Prime+.+new+ is now obsolete. Use +Prime+.+instance+.+each+ or simply
- # +Prime+.+each+.
- def each(ubound = nil, generator = EratosthenesGenerator.new, &block)
- generator.upper_bound = ubound
- generator.each(&block)
- end
-
-
- # Returns true if +value+ is prime, false for a composite.
- #
- # == Parameters
- #
- # +value+:: an arbitrary integer to be checked.
- # +generator+:: optional. A pseudo-prime generator.
- def prime?(value, generator = Prime::Generator23.new)
- value = -value if value < 0
- return false if value < 2
- for num in generator
- q,r = value.divmod num
- return true if q < num
- return false if r == 0
- end
- end
-
- # Re-composes a prime factorization and returns the product.
- #
- # == Parameters
- # +pd+:: Array of pairs of integers. The each internal
- # pair consists of a prime number -- a prime factor --
- # and a natural number -- an exponent.
- #
- # == Example
- # For <tt>[[p_1, e_1], [p_2, e_2], ...., [p_n, e_n]]</tt>, it returns:
- #
- # p_1**e_1 * p_2**e_2 * .... * p_n**e_n.
- #
- # Prime.int_from_prime_division([[2,2], [3,1]]) #=> 12
- def int_from_prime_division(pd)
- pd.inject(1){|value, (prime, index)|
- value *= prime**index
- }
- end
-
- # Returns the factorization of +value+.
- #
- # == Parameters
- # +value+:: An arbitrary integer.
- # +generator+:: Optional. A pseudo-prime generator.
- # +generator+.succ must return the next
- # pseudo-prime number in the ascendent
- # order. It must generate all prime numbers,
- # but may generate non prime numbers.
- #
- # === Exceptions
- # +ZeroDivisionError+:: when +value+ is zero.
- #
- # == Example
- # For an arbitrary integer:
- #
- # n = p_1**e_1 * p_2**e_2 * .... * p_n**e_n,
- #
- # prime_division(n) returns:
- #
- # [[p_1, e_1], [p_2, e_2], ...., [p_n, e_n]].
- #
- # Prime.prime_division(12) #=> [[2,2], [3,1]]
- #
- def prime_division(value, generator= Prime::Generator23.new)
- raise ZeroDivisionError if value == 0
- if value < 0
- value = -value
- pv = [[-1, 1]]
- else
- pv = []
- end
- for prime in generator
- count = 0
- while (value1, mod = value.divmod(prime)
- mod) == 0
- value = value1
- count += 1
- end
- if count != 0
- pv.push [prime, count]
- end
- break if value1 <= prime
- end
- if value > 1
- pv.push [value, 1]
- end
- return pv
- end
-
- # An abstract class for enumerating pseudo-prime numbers.
- #
- # Concrete subclasses should override succ, next, rewind.
- class PseudoPrimeGenerator
- include Enumerable
-
- def initialize(ubound = nil)
- @ubound = ubound
- end
-
- def upper_bound=(ubound)
- @ubound = ubound
- end
- def upper_bound
- @ubound
- end
-
- # returns the next pseudo-prime number, and move the internal
- # position forward.
- #
- # +PseudoPrimeGenerator+#succ raises +NotImplementedError+.
- def succ
- raise NotImplementedError, "need to define `succ'"
- end
-
- # alias of +succ+.
- def next
- raise NotImplementedError, "need to define `next'"
- end
-
- # Rewinds the internal position for enumeration.
- #
- # See +Enumerator+#rewind.
- def rewind
- raise NotImplementedError, "need to define `rewind'"
- end
-
- # Iterates the given block for each prime numbers.
- def each(&block)
- return self.dup unless block
- if @ubound
- last_value = nil
- loop do
- prime = succ
- break last_value if prime > @ubound
- last_value = block.call(prime)
- end
- else
- loop do
- block.call(succ)
- end
- end
- end
-
- # see +Enumerator+#with_index.
- alias with_index each_with_index
-
- # see +Enumerator+#with_object.
- def with_object(obj)
- return enum_for(:with_object) unless block_given?
- each do |prime|
- yield prime, obj
- end
- end
- end
-
- # An implementation of +PseudoPrimeGenerator+.
- #
- # Uses +EratosthenesSieve+.
- class EratosthenesGenerator < PseudoPrimeGenerator
- def initialize
- @last_prime = nil
- super
- end
-
- def succ
- @last_prime = @last_prime ? EratosthenesSieve.instance.next_to(@last_prime) : 2
- end
- def rewind
- initialize
- end
- alias next succ
- end
-
- # An implementation of +PseudoPrimeGenerator+ which uses
- # a prime table generated by trial division.
- class TrialDivisionGenerator<PseudoPrimeGenerator
- def initialize
- @index = -1
- super
- end
-
- def succ
- TrialDivision.instance[@index += 1]
- end
- def rewind
- initialize
- end
- alias next succ
- end
-
- # Generates all integer which are greater than 2 and
- # are not divided by 2 nor 3.
- #
- # This is a pseudo-prime generator, suitable on
- # checking primality of a integer by brute force
- # method.
- class Generator23<PseudoPrimeGenerator
- def initialize
- @prime = 1
- @step = nil
- super
- end
-
- def succ
- loop do
- if (@step)
- @prime += @step
- @step = 6 - @step
- else
- case @prime
- when 1; @prime = 2
- when 2; @prime = 3
- when 3; @prime = 5; @step = 2
- end
- end
- return @prime
- end
- end
- alias next succ
- def rewind
- initialize
- end
- end
-
- # Internal use. An implementation of prime table by trial division method.
- class TrialDivision
- include Singleton
-
- def initialize # :nodoc:
- # These are included as class variables to cache them for later uses. If memory
- # usage is a problem, they can be put in Prime#initialize as instance variables.
-
- # There must be no primes between @primes[-1] and @next_to_check.
- @primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
- # @next_to_check % 6 must be 1.
- @next_to_check = 103 # @primes[-1] - @primes[-1] % 6 + 7
- @ulticheck_index = 3 # @primes.index(@primes.reverse.find {|n|
- # n < Math.sqrt(@@next_to_check) })
- @ulticheck_next_squared = 121 # @primes[@ulticheck_index + 1] ** 2
- end
-
- # Returns the cached prime numbers.
- def cache
- return @primes
- end
- alias primes cache
- alias primes_so_far cache
-
- # Returns the +index+th prime number.
- #
- # +index+ is a 0-based index.
- def [](index)
- while index >= @primes.length
- # Only check for prime factors up to the square root of the potential primes,
- # but without the performance hit of an actual square root calculation.
- if @next_to_check + 4 > @ulticheck_next_squared
- @ulticheck_index += 1
- @ulticheck_next_squared = @primes.at(@ulticheck_index + 1) ** 2
- end
- # Only check numbers congruent to one and five, modulo six. All others
-
- # are divisible by two or three. This also allows us to skip checking against
- # two and three.
- @primes.push @next_to_check if @primes[2..@ulticheck_index].find {|prime| @next_to_check % prime == 0 }.nil?
- @next_to_check += 4
- @primes.push @next_to_check if @primes[2..@ulticheck_index].find {|prime| @next_to_check % prime == 0 }.nil?
- @next_to_check += 2
- end
- return @primes[index]
- end
- end
-
- # Internal use. An implementation of eratosthenes's sieve
- class EratosthenesSieve
- include Singleton
-
- BITS_PER_ENTRY = 16 # each entry is a set of 16-bits in a Fixnum
- NUMS_PER_ENTRY = BITS_PER_ENTRY * 2 # twiced because even numbers are omitted
- ENTRIES_PER_TABLE = 8
- NUMS_PER_TABLE = NUMS_PER_ENTRY * ENTRIES_PER_TABLE
- FILLED_ENTRY = (1 << NUMS_PER_ENTRY) - 1
-
- def initialize # :nodoc:
- # bitmap for odd prime numbers less than 256.
- # For an arbitrary odd number n, @tables[i][j][k] is
- # * 1 if n is prime,
- # * 0 if n is composite,
- # where i,j,k = indices(n)
- @tables = [[0xcb6e, 0x64b4, 0x129a, 0x816d, 0x4c32, 0x864a, 0x820d, 0x2196].freeze]
- end
-
- # returns the least odd prime number which is greater than +n+.
- def next_to(n)
- n = (n-1).div(2)*2+3 # the next odd number to given n
- table_index, integer_index, bit_index = indices(n)
- loop do
- extend_table until @tables.length > table_index
- for j in integer_index...ENTRIES_PER_TABLE
- if !@tables[table_index][j].zero?
- for k in bit_index...BITS_PER_ENTRY
- return NUMS_PER_TABLE*table_index + NUMS_PER_ENTRY*j + 2*k+1 if !@tables[table_index][j][k].zero?
- end
- end
- bit_index = 0
- end
- table_index += 1; integer_index = 0
- end
- end
-
- private
- # for an odd number +n+, returns (i, j, k) such that @tables[i][j][k] represents primarity of the number
- def indices(n)
- # binary digits of n: |0|1|2|3|4|5|6|7|8|9|10|11|....
- # indices: |-| k | j | i
- # because of NUMS_PER_ENTRY, NUMS_PER_TABLE
-
- k = (n & 0b00011111) >> 1
- j = (n & 0b11100000) >> 5
- i = n >> 8
- return i, j, k
- end
-
- def extend_table
- lbound = NUMS_PER_TABLE * @tables.length
- ubound = lbound + NUMS_PER_TABLE
- new_table = [FILLED_ENTRY] * ENTRIES_PER_TABLE # which represents primarity in lbound...ubound
- (3..Integer(Math.sqrt(ubound))).step(2) do |p|
- i, j, k = indices(p)
- next if @tables[i][j][k].zero?
-
- start = (lbound.div(p)+1)*p # least multiple of p which is >= lbound
- start += p if start.even?
- (start...ubound).step(2*p) do |n|
- _, j, k = indices(n)
- new_table[j] &= FILLED_ENTRY^(1<<k)
- end
- end
- @tables << new_table.freeze
- end
- end
-
- # Provides a +Prime+ object with compatibility to Ruby 1.8 when instantiated via +Prime+.+new+.
- module OldCompatibility
- # Returns the next prime number and forwards internal pointer.
- def succ
- @generator.succ
- end
- alias next succ
-
- # Overwrites Prime#each.
- #
- # Iterates the given block over all prime numbers. Note that enumeration
- # starts from the current position of internal pointer, not rewound.
- def each(&block)
- return @generator.dup unless block_given?
- loop do
- yield succ
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/profile.rb b/ruby_1_9_3/lib/profile.rb
deleted file mode 100644
index 2aeecce908..0000000000
--- a/ruby_1_9_3/lib/profile.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-require 'profiler'
-
-RubyVM::InstructionSequence.compile_option = {
- :trace_instruction => true,
- :specialized_instruction => false
-}
-END {
- Profiler__::print_profile(STDERR)
-}
-Profiler__::start_profile
diff --git a/ruby_1_9_3/lib/profiler.rb b/ruby_1_9_3/lib/profiler.rb
deleted file mode 100644
index a4b8889093..0000000000
--- a/ruby_1_9_3/lib/profiler.rb
+++ /dev/null
@@ -1,59 +0,0 @@
-module Profiler__
- # internal values
- @@start = @@stack = @@map = nil
- PROFILE_PROC = proc{|event, file, line, id, binding, klass|
- case event
- when "call", "c-call"
- now = Process.times[0]
- @@stack.push [now, 0.0]
- when "return", "c-return"
- now = Process.times[0]
- key = [klass, id]
- if tick = @@stack.pop
- data = (@@map[key] ||= [0, 0.0, 0.0, key])
- data[0] += 1
- cost = now - tick[0]
- data[1] += cost
- data[2] += cost - tick[1]
- @@stack[-1][1] += cost if @@stack[-1]
- end
- end
- }
-module_function
- def start_profile
- @@start = Process.times[0]
- @@stack = []
- @@map = {}
- set_trace_func PROFILE_PROC
- end
- def stop_profile
- set_trace_func nil
- end
- def print_profile(f)
- stop_profile
- total = Process.times[0] - @@start
- if total == 0 then total = 0.01 end
- data = @@map.values
- data = data.sort_by{|x| -x[2]}
- sum = 0
- f.printf " %% cumulative self self total\n"
- f.printf " time seconds seconds calls ms/call ms/call name\n"
- for d in data
- sum += d[2]
- f.printf "%6.2f %8.2f %8.2f %8d ", d[2]/total*100, sum, d[2], d[0]
- f.printf "%8.2f %8.2f %s\n", d[2]*1000/d[0], d[1]*1000/d[0], get_name(*d[3])
- end
- f.printf "%6.2f %8.2f %8.2f %8d ", 0.0, total, 0.0, 1 # ???
- f.printf "%8.2f %8.2f %s\n", 0.0, total*1000, "#toplevel" # ???
- end
- def get_name(klass, id)
- name = klass.to_s || ""
- if klass.kind_of? Class
- name += "#"
- else
- name += "."
- end
- name + id.id2name
- end
- private :get_name
-end
diff --git a/ruby_1_9_3/lib/pstore.rb b/ruby_1_9_3/lib/pstore.rb
deleted file mode 100644
index 429d7e5c7d..0000000000
--- a/ruby_1_9_3/lib/pstore.rb
+++ /dev/null
@@ -1,532 +0,0 @@
-# = PStore -- Transactional File Storage for Ruby Objects
-#
-# pstore.rb -
-# originally by matz
-# documentation by Kev Jackson and James Edward Gray II
-# improved by Hongli Lai
-#
-# See PStore for documentation.
-
-
-require "fileutils"
-require "digest/md5"
-require "thread"
-
-#
-# PStore implements a file based persistence mechanism based on a Hash. User
-# code can store hierarchies of Ruby objects (values) into the data store file
-# by name (keys). An object hierarchy may be just a single object. User code
-# may later read values back from the data store or even update data, as needed.
-#
-# The transactional behavior ensures that any changes succeed or fail together.
-# This can be used to ensure that the data store is not left in a transitory
-# state, where some values were updated but others were not.
-#
-# Behind the scenes, Ruby objects are stored to the data store file with
-# Marshal. That carries the usual limitations. Proc objects cannot be
-# marshalled, for example.
-#
-# == Usage example:
-#
-# require "pstore"
-#
-# # a mock wiki object...
-# class WikiPage
-# def initialize( page_name, author, contents )
-# @page_name = page_name
-# @revisions = Array.new
-#
-# add_revision(author, contents)
-# end
-#
-# attr_reader :page_name
-#
-# def add_revision( author, contents )
-# @revisions << { :created => Time.now,
-# :author => author,
-# :contents => contents }
-# end
-#
-# def wiki_page_references
-# [@page_name] + @revisions.last[:contents].scan(/\b(?:[A-Z]+[a-z]+){2,}/)
-# end
-#
-# # ...
-# end
-#
-# # create a new page...
-# home_page = WikiPage.new( "HomePage", "James Edward Gray II",
-# "A page about the JoysOfDocumentation..." )
-#
-# # then we want to update page data and the index together, or not at all...
-# wiki = PStore.new("wiki_pages.pstore")
-# wiki.transaction do # begin transaction; do all of this or none of it
-# # store page...
-# wiki[home_page.page_name] = home_page
-# # ensure that an index has been created...
-# wiki[:wiki_index] ||= Array.new
-# # update wiki index...
-# wiki[:wiki_index].push(*home_page.wiki_page_references)
-# end # commit changes to wiki data store file
-#
-# ### Some time later... ###
-#
-# # read wiki data...
-# wiki.transaction(true) do # begin read-only transaction, no changes allowed
-# wiki.roots.each do |data_root_name|
-# p data_root_name
-# p wiki[data_root_name]
-# end
-# end
-#
-# == Transaction modes
-#
-# By default, file integrity is only ensured as long as the operating system
-# (and the underlying hardware) doesn't raise any unexpected I/O errors. If an
-# I/O error occurs while PStore is writing to its file, then the file will
-# become corrupted.
-#
-# You can prevent this by setting <em>pstore.ultra_safe = true</em>.
-# However, this results in a minor performance loss, and only works on platforms
-# that support atomic file renames. Please consult the documentation for
-# +ultra_safe+ for details.
-#
-# Needless to say, if you're storing valuable data with PStore, then you should
-# backup the PStore files from time to time.
-class PStore
- RDWR_ACCESS = {mode: IO::RDWR | IO::CREAT | IO::BINARY, encoding: Encoding::ASCII_8BIT}.freeze
- RD_ACCESS = {mode: IO::RDONLY | IO::BINARY, encoding: Encoding::ASCII_8BIT}.freeze
- WR_ACCESS = {mode: IO::WRONLY | IO::CREAT | IO::TRUNC | IO::BINARY, encoding: Encoding::ASCII_8BIT}.freeze
-
- # The error type thrown by all PStore methods.
- class Error < StandardError
- end
-
- # Whether PStore should do its best to prevent file corruptions, even when under
- # unlikely-to-occur error conditions such as out-of-space conditions and other
- # unusual OS filesystem errors. Setting this flag comes at the price in the form
- # of a performance loss.
- #
- # This flag only has effect on platforms on which file renames are atomic (e.g.
- # all POSIX platforms: Linux, MacOS X, FreeBSD, etc). The default value is false.
- attr_accessor :ultra_safe
-
- #
- # To construct a PStore object, pass in the _file_ path where you would like
- # the data to be stored.
- #
- # PStore objects are always reentrant. But if _thread_safe_ is set to true,
- # then it will become thread-safe at the cost of a minor performance hit.
- #
- def initialize(file, thread_safe = false)
- dir = File::dirname(file)
- unless File::directory? dir
- raise PStore::Error, format("directory %s does not exist", dir)
- end
- if File::exist? file and not File::readable? file
- raise PStore::Error, format("file %s not readable", file)
- end
- @filename = file
- @abort = false
- @ultra_safe = false
- @thread_safe = thread_safe
- @lock = Mutex.new
- end
-
- # Raises PStore::Error if the calling code is not in a PStore#transaction.
- def in_transaction
- raise PStore::Error, "not in transaction" unless @lock.locked?
- end
- #
- # Raises PStore::Error if the calling code is not in a PStore#transaction or
- # if the code is in a read-only PStore#transaction.
- #
- def in_transaction_wr()
- in_transaction()
- raise PStore::Error, "in read-only transaction" if @rdonly
- end
- private :in_transaction, :in_transaction_wr
-
- #
- # Retrieves a value from the PStore file data, by _name_. The hierarchy of
- # Ruby objects stored under that root _name_ will be returned.
- #
- # *WARNING*: This method is only valid in a PStore#transaction. It will
- # raise PStore::Error if called at any other time.
- #
- def [](name)
- in_transaction
- @table[name]
- end
- #
- # This method is just like PStore#[], save that you may also provide a
- # _default_ value for the object. In the event the specified _name_ is not
- # found in the data store, your _default_ will be returned instead. If you do
- # not specify a default, PStore::Error will be raised if the object is not
- # found.
- #
- # *WARNING*: This method is only valid in a PStore#transaction. It will
- # raise PStore::Error if called at any other time.
- #
- def fetch(name, default=PStore::Error)
- in_transaction
- unless @table.key? name
- if default == PStore::Error
- raise PStore::Error, format("undefined root name `%s'", name)
- else
- return default
- end
- end
- @table[name]
- end
- #
- # Stores an individual Ruby object or a hierarchy of Ruby objects in the data
- # store file under the root _name_. Assigning to a _name_ already in the data
- # store clobbers the old data.
- #
- # == Example:
- #
- # require "pstore"
- #
- # store = PStore.new("data_file.pstore")
- # store.transaction do # begin transaction
- # # load some data into the store...
- # store[:single_object] = "My data..."
- # store[:obj_heirarchy] = { "Kev Jackson" => ["rational.rb", "pstore.rb"],
- # "James Gray" => ["erb.rb", "pstore.rb"] }
- # end # commit changes to data store file
- #
- # *WARNING*: This method is only valid in a PStore#transaction and it cannot
- # be read-only. It will raise PStore::Error if called at any other time.
- #
- def []=(name, value)
- in_transaction_wr()
- @table[name] = value
- end
- #
- # Removes an object hierarchy from the data store, by _name_.
- #
- # *WARNING*: This method is only valid in a PStore#transaction and it cannot
- # be read-only. It will raise PStore::Error if called at any other time.
- #
- def delete(name)
- in_transaction_wr()
- @table.delete name
- end
-
- #
- # Returns the names of all object hierarchies currently in the store.
- #
- # *WARNING*: This method is only valid in a PStore#transaction. It will
- # raise PStore::Error if called at any other time.
- #
- def roots
- in_transaction
- @table.keys
- end
- #
- # Returns true if the supplied _name_ is currently in the data store.
- #
- # *WARNING*: This method is only valid in a PStore#transaction. It will
- # raise PStore::Error if called at any other time.
- #
- def root?(name)
- in_transaction
- @table.key? name
- end
- # Returns the path to the data store file.
- def path
- @filename
- end
-
- #
- # Ends the current PStore#transaction, committing any changes to the data
- # store immediately.
- #
- # == Example:
- #
- # require "pstore"
- #
- # store = PStore.new("data_file.pstore")
- # store.transaction do # begin transaction
- # # load some data into the store...
- # store[:one] = 1
- # store[:two] = 2
- #
- # store.commit # end transaction here, committing changes
- #
- # store[:three] = 3 # this change is never reached
- # end
- #
- # *WARNING*: This method is only valid in a PStore#transaction. It will
- # raise PStore::Error if called at any other time.
- #
- def commit
- in_transaction
- @abort = false
- throw :pstore_abort_transaction
- end
- #
- # Ends the current PStore#transaction, discarding any changes to the data
- # store.
- #
- # == Example:
- #
- # require "pstore"
- #
- # store = PStore.new("data_file.pstore")
- # store.transaction do # begin transaction
- # store[:one] = 1 # this change is not applied, see below...
- # store[:two] = 2 # this change is not applied, see below...
- #
- # store.abort # end transaction here, discard all changes
- #
- # store[:three] = 3 # this change is never reached
- # end
- #
- # *WARNING*: This method is only valid in a PStore#transaction. It will
- # raise PStore::Error if called at any other time.
- #
- def abort
- in_transaction
- @abort = true
- throw :pstore_abort_transaction
- end
-
- #
- # Opens a new transaction for the data store. Code executed inside a block
- # passed to this method may read and write data to and from the data store
- # file.
- #
- # At the end of the block, changes are committed to the data store
- # automatically. You may exit the transaction early with a call to either
- # PStore#commit or PStore#abort. See those methods for details about how
- # changes are handled. Raising an uncaught Exception in the block is
- # equivalent to calling PStore#abort.
- #
- # If _read_only_ is set to +true+, you will only be allowed to read from the
- # data store during the transaction and any attempts to change the data will
- # raise a PStore::Error.
- #
- # Note that PStore does not support nested transactions.
- #
- def transaction(read_only = false, &block) # :yields: pstore
- value = nil
- raise PStore::Error, "nested transaction" if !@thread_safe && @lock.locked?
- @lock.synchronize do
- @rdonly = read_only
- @abort = false
- file = open_and_lock_file(@filename, read_only)
- if file
- begin
- @table, checksum, original_data_size = load_data(file, read_only)
-
- catch(:pstore_abort_transaction) do
- value = yield(self)
- end
-
- if !@abort && !read_only
- save_data(checksum, original_data_size, file)
- end
- ensure
- file.close if !file.closed?
- end
- else
- # This can only occur if read_only == true.
- @table = {}
- catch(:pstore_abort_transaction) do
- value = yield(self)
- end
- end
- end
- value
- rescue ThreadError
- raise PStore::Error, "nested transaction"
- end
-
- private
- # Constant for relieving Ruby's garbage collector.
- EMPTY_STRING = ""
- EMPTY_MARSHAL_DATA = Marshal.dump({})
- EMPTY_MARSHAL_CHECKSUM = Digest::MD5.digest(EMPTY_MARSHAL_DATA)
-
- #
- # Open the specified filename (either in read-only mode or in
- # read-write mode) and lock it for reading or writing.
- #
- # The opened File object will be returned. If _read_only_ is true,
- # and the file does not exist, then nil will be returned.
- #
- # All exceptions are propagated.
- #
- def open_and_lock_file(filename, read_only)
- if read_only
- begin
- file = File.new(filename, RD_ACCESS)
- begin
- file.flock(File::LOCK_SH)
- return file
- rescue
- file.close
- raise
- end
- rescue Errno::ENOENT
- return nil
- end
- else
- file = File.new(filename, RDWR_ACCESS)
- file.flock(File::LOCK_EX)
- return file
- end
- end
-
- # Load the given PStore file.
- # If +read_only+ is true, the unmarshalled Hash will be returned.
- # If +read_only+ is false, a 3-tuple will be returned: the unmarshalled
- # Hash, an MD5 checksum of the data, and the size of the data.
- def load_data(file, read_only)
- if read_only
- begin
- table = load(file)
- if !table.is_a?(Hash)
- raise Error, "PStore file seems to be corrupted."
- end
- rescue EOFError
- # This seems to be a newly-created file.
- table = {}
- end
- table
- else
- data = file.read
- if data.empty?
- # This seems to be a newly-created file.
- table = {}
- checksum = empty_marshal_checksum
- size = empty_marshal_data.size
- else
- table = load(data)
- checksum = Digest::MD5.digest(data)
- size = data.size
- if !table.is_a?(Hash)
- raise Error, "PStore file seems to be corrupted."
- end
- end
- data.replace(EMPTY_STRING)
- [table, checksum, size]
- end
- end
-
- def on_windows?
- is_windows = RUBY_PLATFORM =~ /mswin/ ||
- RUBY_PLATFORM =~ /mingw/ ||
- RUBY_PLATFORM =~ /bccwin/ ||
- RUBY_PLATFORM =~ /wince/
- self.class.__send__(:define_method, :on_windows?) do
- is_windows
- end
- is_windows
- end
-
- # Check whether Marshal.dump supports the 'canonical' option. This option
- # makes sure that Marshal.dump always dumps data structures in the same order.
- # This is important because otherwise, the checksums that we generate may differ.
- def marshal_dump_supports_canonical_option?
- begin
- Marshal.dump(nil, -1, true)
- result = true
- rescue
- result = false
- end
- self.class.instance_method(:marshal_dump_supports_canonical_option?)
- self.class.__send__(:define_method, :marshal_dump_supports_canonical_option?) do
- result
- end
- result
- end
-
- def save_data(original_checksum, original_file_size, file)
- # We only want to save the new data if the size or checksum has changed.
- # This results in less filesystem calls, which is good for performance.
- if marshal_dump_supports_canonical_option?
- new_data = Marshal.dump(@table, -1, true)
- else
- new_data = dump(@table)
- end
- new_checksum = Digest::MD5.digest(new_data)
-
- if new_data.size != original_file_size || new_checksum != original_checksum
- if @ultra_safe && !on_windows?
- # Windows doesn't support atomic file renames.
- save_data_with_atomic_file_rename_strategy(new_data, file)
- else
- save_data_with_fast_strategy(new_data, file)
- end
- end
-
- new_data.replace(EMPTY_STRING)
- end
-
- def save_data_with_atomic_file_rename_strategy(data, file)
- temp_filename = "#{@filename}.tmp.#{Process.pid}.#{rand 1000000}"
- temp_file = File.new(temp_filename, WR_ACCESS)
- begin
- temp_file.flock(File::LOCK_EX)
- temp_file.write(data)
- temp_file.flush
- File.rename(temp_filename, @filename)
- rescue
- File.unlink(temp_file) rescue nil
- raise
- ensure
- temp_file.close
- end
- end
-
- def save_data_with_fast_strategy(data, file)
- file.rewind
- file.truncate(0)
- file.write(data)
- end
-
-
- # This method is just a wrapped around Marshal.dump
- # to allow subclass overriding used in YAML::Store.
- def dump(table) # :nodoc:
- Marshal::dump(table)
- end
-
- # This method is just a wrapped around Marshal.load.
- # to allow subclass overriding used in YAML::Store.
- def load(content) # :nodoc:
- Marshal::load(content)
- end
-
- def empty_marshal_data
- EMPTY_MARSHAL_DATA
- end
- def empty_marshal_checksum
- EMPTY_MARSHAL_CHECKSUM
- end
-end
-
-# :enddoc:
-
-if __FILE__ == $0
- db = PStore.new("/tmp/foo")
- db.transaction do
- p db.roots
- ary = db["root"] = [1,2,3,4]
- ary[1] = [1,1.5]
- end
-
- 1000.times do
- db.transaction do
- db["root"][0] += 1
- p db["root"][0]
- end
- end
-
- db.transaction(true) do
- p db["root"]
- end
-end
diff --git a/ruby_1_9_3/lib/racc/parser.rb b/ruby_1_9_3/lib/racc/parser.rb
deleted file mode 100644
index 737b0fda5d..0000000000
--- a/ruby_1_9_3/lib/racc/parser.rb
+++ /dev/null
@@ -1,443 +0,0 @@
-#
-# $originalId: parser.rb,v 1.8 2006/07/06 11:42:07 aamine Exp $
-#
-# Copyright (c) 1999-2006 Minero Aoki
-#
-# This program is free software.
-# You can distribute/modify this program under the same terms of ruby.
-#
-# As a special exception, when this code is copied by Racc
-# into a Racc output file, you may use that output file
-# without restriction.
-#
-
-unless defined?(NotImplementedError)
- NotImplementedError = NotImplementError
-end
-
-module Racc
- class ParseError < StandardError; end
-end
-unless defined?(::ParseError)
- ParseError = Racc::ParseError
-end
-
-module Racc
-
- unless defined?(Racc_No_Extentions)
- Racc_No_Extentions = false
- end
-
- class Parser
-
- Racc_Runtime_Version = '1.4.6'
- Racc_Runtime_Revision = %w$originalRevision: 1.8 $[1]
-
- Racc_Runtime_Core_Version_R = '1.4.6'
- Racc_Runtime_Core_Revision_R = %w$originalRevision: 1.8 $[1]
- begin
- require 'racc/cparse'
- # Racc_Runtime_Core_Version_C = (defined in extention)
- Racc_Runtime_Core_Revision_C = Racc_Runtime_Core_Id_C.split[2]
- unless new.respond_to?(:_racc_do_parse_c, true)
- raise LoadError, 'old cparse.so'
- end
- if Racc_No_Extentions
- raise LoadError, 'selecting ruby version of racc runtime core'
- end
-
- Racc_Main_Parsing_Routine = :_racc_do_parse_c
- Racc_YY_Parse_Method = :_racc_yyparse_c
- Racc_Runtime_Core_Version = Racc_Runtime_Core_Version_C
- Racc_Runtime_Core_Revision = Racc_Runtime_Core_Revision_C
- Racc_Runtime_Type = 'c'
- rescue LoadError
- Racc_Main_Parsing_Routine = :_racc_do_parse_rb
- Racc_YY_Parse_Method = :_racc_yyparse_rb
- Racc_Runtime_Core_Version = Racc_Runtime_Core_Version_R
- Racc_Runtime_Core_Revision = Racc_Runtime_Core_Revision_R
- Racc_Runtime_Type = 'ruby'
- end
-
- def Parser.racc_runtime_type
- Racc_Runtime_Type
- end
-
- private
-
- def _racc_setup
- @yydebug = false unless self.class::Racc_debug_parser
- @yydebug = false unless defined?(@yydebug)
- if @yydebug
- @racc_debug_out = $stderr unless defined?(@racc_debug_out)
- @racc_debug_out ||= $stderr
- end
- arg = self.class::Racc_arg
- arg[13] = true if arg.size < 14
- arg
- end
-
- def _racc_init_sysvars
- @racc_state = [0]
- @racc_tstack = []
- @racc_vstack = []
-
- @racc_t = nil
- @racc_val = nil
-
- @racc_read_next = true
-
- @racc_user_yyerror = false
- @racc_error_status = 0
- end
-
- ###
- ### do_parse
- ###
-
- class_eval %{
- def do_parse
- #{Racc_Main_Parsing_Routine}(_racc_setup(), false)
- end
- }
-
- def next_token
- raise NotImplementedError, "#{self.class}\#next_token is not defined"
- end
-
- def _racc_do_parse_rb(arg, in_debug)
- action_table, action_check, action_default, action_pointer,
- _, _, _, _,
- _, _, token_table, _,
- _, _, * = arg
-
- _racc_init_sysvars
- tok = act = i = nil
-
- catch(:racc_end_parse) {
- while true
- if i = action_pointer[@racc_state[-1]]
- if @racc_read_next
- if @racc_t != 0 # not EOF
- tok, @racc_val = next_token()
- unless tok # EOF
- @racc_t = 0
- else
- @racc_t = (token_table[tok] or 1) # error token
- end
- racc_read_token(@racc_t, tok, @racc_val) if @yydebug
- @racc_read_next = false
- end
- end
- i += @racc_t
- unless i >= 0 and
- act = action_table[i] and
- action_check[i] == @racc_state[-1]
- act = action_default[@racc_state[-1]]
- end
- else
- act = action_default[@racc_state[-1]]
- end
- while act = _racc_evalact(act, arg)
- ;
- end
- end
- }
- end
-
- ###
- ### yyparse
- ###
-
- class_eval %{
- def yyparse(recv, mid)
- #{Racc_YY_Parse_Method}(recv, mid, _racc_setup(), true)
- end
- }
-
- def _racc_yyparse_rb(recv, mid, arg, c_debug)
- action_table, action_check, action_default, action_pointer,
- _, _, _, _,
- _, _, token_table, _,
- _, _, * = arg
-
- _racc_init_sysvars
- act = nil
- i = nil
-
- catch(:racc_end_parse) {
- until i = action_pointer[@racc_state[-1]]
- while act = _racc_evalact(action_default[@racc_state[-1]], arg)
- ;
- end
- end
- recv.__send__(mid) do |tok, val|
- unless tok
- @racc_t = 0
- else
- @racc_t = (token_table[tok] or 1) # error token
- end
- @racc_val = val
- @racc_read_next = false
-
- i += @racc_t
- unless i >= 0 and
- act = action_table[i] and
- action_check[i] == @racc_state[-1]
- act = action_default[@racc_state[-1]]
- end
- while act = _racc_evalact(act, arg)
- ;
- end
-
- while not(i = action_pointer[@racc_state[-1]]) or
- not @racc_read_next or
- @racc_t == 0 # $
- unless i and i += @racc_t and
- i >= 0 and
- act = action_table[i] and
- action_check[i] == @racc_state[-1]
- act = action_default[@racc_state[-1]]
- end
- while act = _racc_evalact(act, arg)
- ;
- end
- end
- end
- }
- end
-
- ###
- ### common
- ###
-
- def _racc_evalact(act, arg)
- action_table, action_check, _, action_pointer,
- _, _, _, _,
- _, _, _, shift_n, reduce_n,
- _, _, * = arg
- nerr = 0 # tmp
-
- if act > 0 and act < shift_n
- #
- # shift
- #
- if @racc_error_status > 0
- @racc_error_status -= 1 unless @racc_t == 1 # error token
- end
- @racc_vstack.push @racc_val
- @racc_state.push act
- @racc_read_next = true
- if @yydebug
- @racc_tstack.push @racc_t
- racc_shift @racc_t, @racc_tstack, @racc_vstack
- end
-
- elsif act < 0 and act > -reduce_n
- #
- # reduce
- #
- code = catch(:racc_jump) {
- @racc_state.push _racc_do_reduce(arg, act)
- false
- }
- if code
- case code
- when 1 # yyerror
- @racc_user_yyerror = true # user_yyerror
- return -reduce_n
- when 2 # yyaccept
- return shift_n
- else
- raise '[Racc Bug] unknown jump code'
- end
- end
-
- elsif act == shift_n
- #
- # accept
- #
- racc_accept if @yydebug
- throw :racc_end_parse, @racc_vstack[0]
-
- elsif act == -reduce_n
- #
- # error
- #
- case @racc_error_status
- when 0
- unless arg[21] # user_yyerror
- nerr += 1
- on_error @racc_t, @racc_val, @racc_vstack
- end
- when 3
- if @racc_t == 0 # is $
- throw :racc_end_parse, nil
- end
- @racc_read_next = true
- end
- @racc_user_yyerror = false
- @racc_error_status = 3
- while true
- if i = action_pointer[@racc_state[-1]]
- i += 1 # error token
- if i >= 0 and
- (act = action_table[i]) and
- action_check[i] == @racc_state[-1]
- break
- end
- end
- throw :racc_end_parse, nil if @racc_state.size <= 1
- @racc_state.pop
- @racc_vstack.pop
- if @yydebug
- @racc_tstack.pop
- racc_e_pop @racc_state, @racc_tstack, @racc_vstack
- end
- end
- return act
-
- else
- raise "[Racc Bug] unknown action #{act.inspect}"
- end
-
- racc_next_state(@racc_state[-1], @racc_state) if @yydebug
-
- nil
- end
-
- def _racc_do_reduce(arg, act)
- _, _, _, _,
- goto_table, goto_check, goto_default, goto_pointer,
- nt_base, reduce_table, _, _,
- _, use_result, * = arg
- state = @racc_state
- vstack = @racc_vstack
- tstack = @racc_tstack
-
- i = act * -3
- len = reduce_table[i]
- reduce_to = reduce_table[i+1]
- method_id = reduce_table[i+2]
- void_array = []
-
- tmp_t = tstack[-len, len] if @yydebug
- tmp_v = vstack[-len, len]
- tstack[-len, len] = void_array if @yydebug
- vstack[-len, len] = void_array
- state[-len, len] = void_array
-
- # tstack must be updated AFTER method call
- if use_result
- vstack.push __send__(method_id, tmp_v, vstack, tmp_v[0])
- else
- vstack.push __send__(method_id, tmp_v, vstack)
- end
- tstack.push reduce_to
-
- racc_reduce(tmp_t, reduce_to, tstack, vstack) if @yydebug
-
- k1 = reduce_to - nt_base
- if i = goto_pointer[k1]
- i += state[-1]
- if i >= 0 and (curstate = goto_table[i]) and goto_check[i] == k1
- return curstate
- end
- end
- goto_default[k1]
- end
-
- def on_error(t, val, vstack)
- raise ParseError, sprintf("\nparse error on value %s (%s)",
- val.inspect, token_to_str(t) || '?')
- end
-
- def yyerror
- throw :racc_jump, 1
- end
-
- def yyaccept
- throw :racc_jump, 2
- end
-
- def yyerrok
- @racc_error_status = 0
- end
-
- #
- # for debugging output
- #
-
- def racc_read_token(t, tok, val)
- @racc_debug_out.print 'read '
- @racc_debug_out.print tok.inspect, '(', racc_token2str(t), ') '
- @racc_debug_out.puts val.inspect
- @racc_debug_out.puts
- end
-
- def racc_shift(tok, tstack, vstack)
- @racc_debug_out.puts "shift #{racc_token2str tok}"
- racc_print_stacks tstack, vstack
- @racc_debug_out.puts
- end
-
- def racc_reduce(toks, sim, tstack, vstack)
- out = @racc_debug_out
- out.print 'reduce '
- if toks.empty?
- out.print ' <none>'
- else
- toks.each {|t| out.print ' ', racc_token2str(t) }
- end
- out.puts " --> #{racc_token2str(sim)}"
-
- racc_print_stacks tstack, vstack
- @racc_debug_out.puts
- end
-
- def racc_accept
- @racc_debug_out.puts 'accept'
- @racc_debug_out.puts
- end
-
- def racc_e_pop(state, tstack, vstack)
- @racc_debug_out.puts 'error recovering mode: pop token'
- racc_print_states state
- racc_print_stacks tstack, vstack
- @racc_debug_out.puts
- end
-
- def racc_next_state(curstate, state)
- @racc_debug_out.puts "goto #{curstate}"
- racc_print_states state
- @racc_debug_out.puts
- end
-
- def racc_print_stacks(t, v)
- out = @racc_debug_out
- out.print ' ['
- t.each_index do |i|
- out.print ' (', racc_token2str(t[i]), ' ', v[i].inspect, ')'
- end
- out.puts ' ]'
- end
-
- def racc_print_states(s)
- out = @racc_debug_out
- out.print ' ['
- s.each {|st| out.print ' ', st }
- out.puts ' ]'
- end
-
- def racc_token2str(tok)
- self.class::Racc_token_to_s_table[tok] or
- raise "[Racc Bug] can't convert token #{tok} to string"
- end
-
- def token_to_str(t)
- self.class::Racc_token_to_s_table[t]
- end
-
- end
-
-end
diff --git a/ruby_1_9_3/lib/rake.rb b/ruby_1_9_3/lib/rake.rb
deleted file mode 100644
index fc1a6a5165..0000000000
--- a/ruby_1_9_3/lib/rake.rb
+++ /dev/null
@@ -1,69 +0,0 @@
-#--
-
-# Copyright 2003-2010 by Jim Weirich (jim.weirich@gmail.com)
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to
-# deal in the Software without restriction, including without limitation the
-# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-# sell copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in
-# all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
-# IN THE SOFTWARE.
-#++
-
-require 'rake/version'
-
-# :stopdoc:
-RAKEVERSION = Rake::VERSION
-# :startdoc:
-
-require 'rbconfig'
-require 'fileutils'
-require 'singleton'
-require 'monitor'
-require 'optparse'
-require 'ostruct'
-
-require 'rake/ext/module'
-require 'rake/ext/string'
-require 'rake/ext/time'
-
-require 'rake/win32'
-
-require 'rake/task_argument_error'
-require 'rake/rule_recursion_overflow_error'
-require 'rake/rake_module'
-require 'rake/pseudo_status'
-require 'rake/task_arguments'
-require 'rake/invocation_chain'
-require 'rake/task'
-require 'rake/file_task'
-require 'rake/file_creation_task'
-require 'rake/multi_task'
-require 'rake/dsl_definition'
-require 'rake/file_utils_ext'
-require 'rake/file_list'
-require 'rake/default_loader'
-require 'rake/early_time'
-require 'rake/name_space'
-require 'rake/task_manager'
-require 'rake/application'
-
-$trace = false
-
-# :stopdoc:
-#
-# Some top level Constants.
-
-FileList = Rake::FileList
-RakeFileUtils = Rake::FileUtilsExt
diff --git a/ruby_1_9_3/lib/rake/alt_system.rb b/ruby_1_9_3/lib/rake/alt_system.rb
deleted file mode 100644
index 05af19863a..0000000000
--- a/ruby_1_9_3/lib/rake/alt_system.rb
+++ /dev/null
@@ -1,109 +0,0 @@
-#
-# Copyright (c) 2008 James M. Lawrence
-#
-# Permission is hereby granted, free of charge, to any person
-# obtaining a copy of this software and associated documentation files
-# (the "Software"), to deal in the Software without restriction,
-# including without limitation the rights to use, copy, modify, merge,
-# publish, distribute, sublicense, and/or sell copies of the Software,
-# and to permit persons to whom the Software is furnished to do so,
-# subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be
-# included in all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
-# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
-# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-# SOFTWARE.
-#
-
-require 'rbconfig'
-
-#
-# Alternate implementations of system() and backticks `` on Windows
-# for ruby-1.8 and earlier.
-#
-module Rake::AltSystem
- WINDOWS = RbConfig::CONFIG["host_os"] =~
- %r!(msdos|mswin|djgpp|mingw|[Ww]indows)!
-
- class << self
- def define_module_function(name, &block)
- define_method(name, &block)
- module_function(name)
- end
- end
-
- if WINDOWS and RUBY_VERSION < "1.9.0"
- RUNNABLE_EXTS = %w[com exe bat cmd]
- RUNNABLE_PATTERN = %r!\.(#{RUNNABLE_EXTS.join('|')})\Z!i
-
- define_module_function :kernel_system, &Kernel.method(:system)
- define_module_function :kernel_backticks, &Kernel.method(:'`')
-
- module_function
-
- def repair_command(cmd)
- "call " + (
- if cmd =~ %r!\A\s*\".*?\"!
- # already quoted
- cmd
- elsif match = cmd.match(%r!\A\s*(\S+)!)
- if match[1] =~ %r!/!
- # avoid x/y.bat interpretation as x with option /y
- %Q!"#{match[1]}"! + match.post_match
- else
- # a shell command will fail if quoted
- cmd
- end
- else
- # empty or whitespace
- cmd
- end
- )
- end
-
- def find_runnable(file)
- if file =~ RUNNABLE_PATTERN
- file
- else
- RUNNABLE_EXTS.each { |ext|
- if File.exist?(test = "#{file}.#{ext}")
- return test
- end
- }
- nil
- end
- end
-
- def system(cmd, *args)
- repaired = (
- if args.empty?
- [repair_command(cmd)]
- elsif runnable = find_runnable(cmd)
- [File.expand_path(runnable), *args]
- else
- # non-existent file
- [cmd, *args]
- end
- )
- kernel_system(*repaired)
- end
-
- def backticks(cmd)
- kernel_backticks(repair_command(cmd))
- end
-
- define_module_function :'`', &method(:backticks)
- else
- # Non-Windows or ruby-1.9+: same as Kernel versions
- define_module_function :system, &Kernel.method(:system)
- define_module_function :backticks, &Kernel.method(:'`')
- define_module_function :'`', &Kernel.method(:'`')
- end
-end
diff --git a/ruby_1_9_3/lib/rake/application.rb b/ruby_1_9_3/lib/rake/application.rb
deleted file mode 100644
index 2079fb9be6..0000000000
--- a/ruby_1_9_3/lib/rake/application.rb
+++ /dev/null
@@ -1,595 +0,0 @@
-require 'shellwords'
-require 'optparse'
-
-require 'rake/task_manager'
-require 'rake/win32'
-
-module Rake
-
- ######################################################################
- # Rake main application object. When invoking +rake+ from the
- # command line, a Rake::Application object is created and run.
- #
- class Application
- include TaskManager
-
- # The name of the application (typically 'rake')
- attr_reader :name
-
- # The original directory where rake was invoked.
- attr_reader :original_dir
-
- # Name of the actual rakefile used.
- attr_reader :rakefile
-
- # Number of columns on the terminal
- attr_accessor :terminal_columns
-
- # List of the top level task names (task names from the command line).
- attr_reader :top_level_tasks
-
- DEFAULT_RAKEFILES = ['rakefile', 'Rakefile', 'rakefile.rb', 'Rakefile.rb'].freeze
-
- # Initialize a Rake::Application object.
- def initialize
- super
- @name = 'rake'
- @rakefiles = DEFAULT_RAKEFILES.dup
- @rakefile = nil
- @pending_imports = []
- @imported = []
- @loaders = {}
- @default_loader = Rake::DefaultLoader.new
- @original_dir = Dir.pwd
- @top_level_tasks = []
- add_loader('rb', DefaultLoader.new)
- add_loader('rf', DefaultLoader.new)
- add_loader('rake', DefaultLoader.new)
- @tty_output = STDOUT.tty?
- @terminal_columns = ENV['RAKE_COLUMNS'].to_i
- end
-
- # Run the Rake application. The run method performs the following
- # three steps:
- #
- # * Initialize the command line options (+init+).
- # * Define the tasks (+load_rakefile+).
- # * Run the top level tasks (+run_tasks+).
- #
- # If you wish to build a custom rake command, you should call
- # +init+ on your application. Then define any tasks. Finally,
- # call +top_level+ to run your top level tasks.
- def run
- standard_exception_handling do
- init
- load_rakefile
- top_level
- end
- end
-
- # Initialize the command line parameters and app name.
- def init(app_name='rake')
- standard_exception_handling do
- @name = app_name
- handle_options
- collect_tasks
- end
- end
-
- # Find the rakefile and then load it and any pending imports.
- def load_rakefile
- standard_exception_handling do
- raw_load_rakefile
- end
- end
-
- # Run the top level tasks of a Rake application.
- def top_level
- standard_exception_handling do
- if options.show_tasks
- display_tasks_and_comments
- elsif options.show_prereqs
- display_prerequisites
- else
- top_level_tasks.each { |task_name| invoke_task(task_name) }
- end
- end
- end
-
- # Add a loader to handle imported files ending in the extension
- # +ext+.
- def add_loader(ext, loader)
- ext = ".#{ext}" unless ext =~ /^\./
- @loaders[ext] = loader
- end
-
- # Application options from the command line
- def options
- @options ||= OpenStruct.new
- end
-
- # private ----------------------------------------------------------------
-
- def invoke_task(task_string)
- name, args = parse_task_string(task_string)
- t = self[name]
- t.invoke(*args)
- end
-
- def parse_task_string(string)
- if string =~ /^([^\[]+)(\[(.*)\])$/
- name = $1
- args = $3.split(/\s*,\s*/)
- else
- name = string
- args = []
- end
- [name, args]
- end
-
- # Provide standard exception handling for the given block.
- def standard_exception_handling
- begin
- yield
- rescue SystemExit => ex
- # Exit silently with current status
- raise
- rescue OptionParser::InvalidOption => ex
- $stderr.puts ex.message
- exit(false)
- rescue Exception => ex
- # Exit with error message
- display_error_message(ex)
- exit(false)
- end
- end
-
- # Display the error message that caused the exception.
- def display_error_message(ex)
- $stderr.puts "#{name} aborted!"
- $stderr.puts ex.message
- if options.trace
- $stderr.puts ex.backtrace.join("\n")
- else
- $stderr.puts rakefile_location(ex.backtrace)
- end
- $stderr.puts "Tasks: #{ex.chain}" if has_chain?(ex)
- $stderr.puts "(See full trace by running task with --trace)" unless options.trace
- end
-
- # Warn about deprecated usage.
- #
- # Example:
- # Rake.application.deprecate("import", "Rake.import", caller.first)
- #
- def deprecate(old_usage, new_usage, call_site)
- return if options.ignore_deprecate
- $stderr.puts "WARNING: '#{old_usage}' is deprecated. " +
- "Please use '#{new_usage}' instead.\n" +
- " at #{call_site}"
- end
-
- # Does the exception have a task invocation chain?
- def has_chain?(exception)
- exception.respond_to?(:chain) && exception.chain
- end
- private :has_chain?
-
- # True if one of the files in RAKEFILES is in the current directory.
- # If a match is found, it is copied into @rakefile.
- def have_rakefile
- @rakefiles.each do |fn|
- if File.exist?(fn)
- others = Dir.glob(fn, File::FNM_CASEFOLD)
- return others.size == 1 ? others.first : fn
- elsif fn == ''
- return fn
- end
- end
- return nil
- end
-
- # True if we are outputting to TTY, false otherwise
- def tty_output?
- @tty_output
- end
-
- # Override the detected TTY output state (mostly for testing)
- def tty_output=( tty_output_state )
- @tty_output = tty_output_state
- end
-
- # We will truncate output if we are outputting to a TTY or if we've been
- # given an explicit column width to honor
- def truncate_output?
- tty_output? || @terminal_columns.nonzero?
- end
-
- # Display the tasks and comments.
- def display_tasks_and_comments
- displayable_tasks = tasks.select { |t|
- t.comment && t.name =~ options.show_task_pattern
- }
- case options.show_tasks
- when :tasks
- width = displayable_tasks.collect { |t| t.name_with_args.length }.max || 10
- max_column = truncate_output? ? terminal_width - name.size - width - 7 : nil
-
- displayable_tasks.each do |t|
- printf "#{name} %-#{width}s # %s\n",
- t.name_with_args, max_column ? truncate(t.comment, max_column) : t.comment
- end
- when :describe
- displayable_tasks.each do |t|
- puts "#{name} #{t.name_with_args}"
- t.full_comment.split("\n").each do |line|
- puts " #{line}"
- end
- puts
- end
- when :lines
- displayable_tasks.each do |t|
- t.locations.each do |loc|
- printf "#{name} %-30s %s\n",t.name_with_args, loc
- end
- end
- else
- fail "Unknown show task mode: '#{options.show_tasks}'"
- end
- end
-
- def terminal_width
- if @terminal_columns.nonzero?
- result = @terminal_columns
- else
- result = unix? ? dynamic_width : 80
- end
- (result < 10) ? 80 : result
- rescue
- 80
- end
-
- # Calculate the dynamic width of the
- def dynamic_width
- @dynamic_width ||= (dynamic_width_stty.nonzero? || dynamic_width_tput)
- end
-
- def dynamic_width_stty
- %x{stty size 2>/dev/null}.split[1].to_i
- end
-
- def dynamic_width_tput
- %x{tput cols 2>/dev/null}.to_i
- end
-
- def unix?
- RbConfig::CONFIG['host_os'] =~ /(aix|darwin|linux|(net|free|open)bsd|cygwin|solaris|irix|hpux)/i
- end
-
- def windows?
- Win32.windows?
- end
-
- def truncate(string, width)
- if string.length <= width
- string
- else
- ( string[0, width-3] || "" ) + "..."
- end
- end
-
- # Display the tasks and prerequisites
- def display_prerequisites
- tasks.each do |t|
- puts "#{name} #{t.name}"
- t.prerequisites.each { |pre| puts " #{pre}" }
- end
- end
-
- # A list of all the standard options used in rake, suitable for
- # passing to OptionParser.
- def standard_rake_options
- [
- ['--classic-namespace', '-C', "Put Task and FileTask in the top level namespace",
- lambda { |value|
- require 'rake/classic_namespace'
- options.classic_namespace = true
- }
- ],
- ['--describe', '-D [PATTERN]', "Describe the tasks (matching optional PATTERN), then exit.",
- lambda { |value|
- options.show_tasks = :describe
- options.show_task_pattern = Regexp.new(value || '')
- TaskManager.record_task_metadata = true
- }
- ],
- ['--dry-run', '-n', "Do a dry run without executing actions.",
- lambda { |value|
- Rake.verbose(true)
- Rake.nowrite(true)
- options.dryrun = true
- options.trace = true
- }
- ],
- ['--execute', '-e CODE', "Execute some Ruby code and exit.",
- lambda { |value|
- eval(value)
- exit
- }
- ],
- ['--execute-print', '-p CODE', "Execute some Ruby code, print the result, then exit.",
- lambda { |value|
- puts eval(value)
- exit
- }
- ],
- ['--execute-continue', '-E CODE',
- "Execute some Ruby code, then continue with normal task processing.",
- lambda { |value| eval(value) }
- ],
- ['--libdir', '-I LIBDIR', "Include LIBDIR in the search path for required modules.",
- lambda { |value| $:.push(value) }
- ],
- ['--no-search', '--nosearch', '-N', "Do not search parent directories for the Rakefile.",
- lambda { |value| options.nosearch = true }
- ],
- ['--prereqs', '-P', "Display the tasks and dependencies, then exit.",
- lambda { |value| options.show_prereqs = true }
- ],
- ['--quiet', '-q', "Do not log messages to standard output.",
- lambda { |value| Rake.verbose(false) }
- ],
- ['--rakefile', '-f [FILE]', "Use FILE as the rakefile.",
- lambda { |value|
- value ||= ''
- @rakefiles.clear
- @rakefiles << value
- }
- ],
- ['--rakelibdir', '--rakelib', '-R RAKELIBDIR',
- "Auto-import any .rake files in RAKELIBDIR. (default is 'rakelib')",
- # HACK Use File::PATH_SEPARATOR
- lambda { |value| options.rakelib = value.split(':') }
- ],
- ['--require', '-r MODULE', "Require MODULE before executing rakefile.",
- lambda { |value|
- begin
- require value
- rescue LoadError => ex
- begin
- rake_require value
- rescue LoadError
- raise ex
- end
- end
- }
- ],
- ['--rules', "Trace the rules resolution.",
- lambda { |value| options.trace_rules = true }
- ],
- ['--silent', '-s', "Like --quiet, but also suppresses the 'in directory' announcement.",
- lambda { |value|
- Rake.verbose(false)
- options.silent = true
- }
- ],
- ['--system', '-g',
- "Using system wide (global) rakefiles (usually '~/.rake/*.rake').",
- lambda { |value| options.load_system = true }
- ],
- ['--no-system', '--nosystem', '-G',
- "Use standard project Rakefile search paths, ignore system wide rakefiles.",
- lambda { |value| options.ignore_system = true }
- ],
- ['--tasks', '-T [PATTERN]', "Display the tasks (matching optional PATTERN) with descriptions, then exit.",
- lambda { |value|
- options.show_tasks = :tasks
- options.show_task_pattern = Regexp.new(value || '')
- Rake::TaskManager.record_task_metadata = true
- }
- ],
- ['--trace', '-t', "Turn on invoke/execute tracing, enable full backtrace.",
- lambda { |value|
- options.trace = true
- Rake.verbose(true)
- }
- ],
- ['--verbose', '-v', "Log message to standard output.",
- lambda { |value| Rake.verbose(true) }
- ],
- ['--version', '-V', "Display the program version.",
- lambda { |value|
- puts "rake, version #{RAKEVERSION}"
- exit
- }
- ],
- ['--where', '-W [PATTERN]', "Describe the tasks (matching optional PATTERN), then exit.",
- lambda { |value|
- options.show_tasks = :lines
- options.show_task_pattern = Regexp.new(value || '')
- Rake::TaskManager.record_task_metadata = true
- }
- ],
- ['--no-deprecation-warnings', '-X', "Disable the deprecation warnings.",
- lambda { |value|
- options.ignore_deprecate = true
- }
- ],
- ]
- end
-
- # Read and handle the command line options.
- def handle_options
- options.rakelib = ['rakelib']
-
- OptionParser.new do |opts|
- opts.banner = "rake [-f rakefile] {options} targets..."
- opts.separator ""
- opts.separator "Options are ..."
-
- opts.on_tail("-h", "--help", "-H", "Display this help message.") do
- puts opts
- exit
- end
-
- standard_rake_options.each { |args| opts.on(*args) }
- opts.environment('RAKEOPT')
- end.parse!
-
- # If class namespaces are requested, set the global options
- # according to the values in the options structure.
- if options.classic_namespace
- $show_tasks = options.show_tasks
- $show_prereqs = options.show_prereqs
- $trace = options.trace
- $dryrun = options.dryrun
- $silent = options.silent
- end
- end
-
- # Similar to the regular Ruby +require+ command, but will check
- # for *.rake files in addition to *.rb files.
- def rake_require(file_name, paths=$LOAD_PATH, loaded=$")
- fn = file_name + ".rake"
- return false if loaded.include?(fn)
- paths.each do |path|
- full_path = File.join(path, fn)
- if File.exist?(full_path)
- Rake.load_rakefile(full_path)
- loaded << fn
- return true
- end
- end
- fail LoadError, "Can't find #{file_name}"
- end
-
- def find_rakefile_location
- here = Dir.pwd
- while ! (fn = have_rakefile)
- Dir.chdir("..")
- if Dir.pwd == here || options.nosearch
- return nil
- end
- here = Dir.pwd
- end
- [fn, here]
- ensure
- Dir.chdir(Rake.original_dir)
- end
-
- def print_rakefile_directory(location)
- $stderr.puts "(in #{Dir.pwd})" unless
- options.silent or original_dir == location
- end
-
- def raw_load_rakefile # :nodoc:
- rakefile, location = find_rakefile_location
- if (! options.ignore_system) &&
- (options.load_system || rakefile.nil?) &&
- system_dir && File.directory?(system_dir)
- print_rakefile_directory(location)
- glob("#{system_dir}/*.rake") do |name|
- add_import name
- end
- else
- fail "No Rakefile found (looking for: #{@rakefiles.join(', ')})" if
- rakefile.nil?
- @rakefile = rakefile
- Dir.chdir(location)
- print_rakefile_directory(location)
- $rakefile = @rakefile if options.classic_namespace
- Rake.load_rakefile(File.expand_path(@rakefile)) if @rakefile && @rakefile != ''
- options.rakelib.each do |rlib|
- glob("#{rlib}/*.rake") do |name|
- add_import name
- end
- end
- end
- load_imports
- end
-
- def glob(path, &block)
- Dir[path.gsub("\\", '/')].each(&block)
- end
- private :glob
-
- # The directory path containing the system wide rakefiles.
- def system_dir
- @system_dir ||=
- begin
- if ENV['RAKE_SYSTEM']
- ENV['RAKE_SYSTEM']
- else
- standard_system_dir
- end
- end
- end
-
- # The standard directory containing system wide rake files.
- if Win32.windows?
- def standard_system_dir #:nodoc:
- Win32.win32_system_dir
- end
- else
- def standard_system_dir #:nodoc:
- File.join(File.expand_path('~'), '.rake')
- end
- end
- private :standard_system_dir
-
- # Collect the list of tasks on the command line. If no tasks are
- # given, return a list containing only the default task.
- # Environmental assignments are processed at this time as well.
- def collect_tasks
- @top_level_tasks = []
- ARGV.each do |arg|
- if arg =~ /^(\w+)=(.*)$/
- ENV[$1] = $2
- else
- @top_level_tasks << arg unless arg =~ /^-/
- end
- end
- @top_level_tasks.push("default") if @top_level_tasks.size == 0
- end
-
- # Add a file to the list of files to be imported.
- def add_import(fn)
- @pending_imports << fn
- end
-
- # Load the pending list of imported files.
- def load_imports
- while fn = @pending_imports.shift
- next if @imported.member?(fn)
- if fn_task = lookup(fn)
- fn_task.invoke
- end
- ext = File.extname(fn)
- loader = @loaders[ext] || @default_loader
- loader.load(fn)
- @imported << fn
- end
- end
-
- # Warn about deprecated use of top level constant names.
- def const_warning(const_name)
- @const_warning ||= false
- if ! @const_warning
- $stderr.puts %{WARNING: Deprecated reference to top-level constant '#{const_name}' } +
- %{found at: #{rakefile_location}} # '
- $stderr.puts %{ Use --classic-namespace on rake command}
- $stderr.puts %{ or 'require "rake/classic_namespace"' in Rakefile}
- end
- @const_warning = true
- end
-
- def rakefile_location backtrace = caller
- backtrace.map { |t| t[/([^:]+):/,1] }
-
- re = /^#{@rakefile}$/
- re = /#{re.source}/i if windows?
-
- backtrace.find { |str| str =~ re } || ''
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rake/classic_namespace.rb b/ruby_1_9_3/lib/rake/classic_namespace.rb
deleted file mode 100644
index 6e71012da4..0000000000
--- a/ruby_1_9_3/lib/rake/classic_namespace.rb
+++ /dev/null
@@ -1,11 +0,0 @@
-# The following classes used to be in the top level namespace.
-# Loading this file enables compatibility with older Rakefile that
-# referenced Task from the top level.
-
-warn "WARNING: Classic namespaces are deprecated and will be removed from future versions of Rake."
-# :stopdoc:
-Task = Rake::Task
-FileTask = Rake::FileTask
-FileCreationTask = Rake::FileCreationTask
-RakeApp = Rake::Application
-# :startdoc:
diff --git a/ruby_1_9_3/lib/rake/clean.rb b/ruby_1_9_3/lib/rake/clean.rb
deleted file mode 100644
index 5c9cbcdb24..0000000000
--- a/ruby_1_9_3/lib/rake/clean.rb
+++ /dev/null
@@ -1,32 +0,0 @@
-# The 'rake/clean' file defines two file lists (CLEAN and CLOBBER) and
-# two rake tasks (:clean and :clobber).
-#
-# [:clean] Clean up the project by deleting scratch files and backup
-# files. Add files to the CLEAN file list to have the :clean
-# target handle them.
-#
-# [:clobber] Clobber all generated and non-source files in a project.
-# The task depends on :clean, so all the clean files will
-# be deleted as well as files in the CLOBBER file list.
-# The intent of this task is to return a project to its
-# pristine, just unpacked state.
-
-require 'rake'
-
-# :stopdoc:
-CLEAN = Rake::FileList["**/*~", "**/*.bak", "**/core"]
-CLEAN.clear_exclude.exclude { |fn|
- fn.pathmap("%f") == 'core' && File.directory?(fn)
-}
-
-desc "Remove any temporary products."
-task :clean do
- CLEAN.each { |fn| rm_r fn rescue nil }
-end
-
-CLOBBER = Rake::FileList.new
-
-desc "Remove any generated file."
-task :clobber => [:clean] do
- CLOBBER.each { |fn| rm_r fn rescue nil }
-end
diff --git a/ruby_1_9_3/lib/rake/cloneable.rb b/ruby_1_9_3/lib/rake/cloneable.rb
deleted file mode 100644
index 19c780bff6..0000000000
--- a/ruby_1_9_3/lib/rake/cloneable.rb
+++ /dev/null
@@ -1,25 +0,0 @@
-module Rake
- # ##########################################################################
- # Mixin for creating easily cloned objects.
- #
- module Cloneable
- # Clone an object by making a new object and setting all the instance
- # variables to the same values.
- def dup
- sibling = self.class.new
- instance_variables.each do |ivar|
- value = self.instance_variable_get(ivar)
- new_value = value.clone rescue value
- sibling.instance_variable_set(ivar, new_value)
- end
- sibling.taint if tainted?
- sibling
- end
-
- def clone
- sibling = dup
- sibling.freeze if frozen?
- sibling
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rake/contrib/compositepublisher.rb b/ruby_1_9_3/lib/rake/contrib/compositepublisher.rb
deleted file mode 100644
index 69952a0808..0000000000
--- a/ruby_1_9_3/lib/rake/contrib/compositepublisher.rb
+++ /dev/null
@@ -1,21 +0,0 @@
-module Rake
-
- # Manage several publishers as a single entity.
- class CompositePublisher
- def initialize
- @publishers = []
- end
-
- # Add a publisher to the composite.
- def add(pub)
- @publishers << pub
- end
-
- # Upload all the individual publishers.
- def upload
- @publishers.each { |p| p.upload }
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rake/contrib/ftptools.rb b/ruby_1_9_3/lib/rake/contrib/ftptools.rb
deleted file mode 100644
index 78420c7412..0000000000
--- a/ruby_1_9_3/lib/rake/contrib/ftptools.rb
+++ /dev/null
@@ -1,150 +0,0 @@
-# = Tools for FTP uploading.
-#
-# This file is still under development and is not released for general
-# use.
-
-require 'date'
-require 'net/ftp'
-
-module Rake # :nodoc:
-
- ####################################################################
- # <b>Note:</b> <em> Not released for general use.</em>
- class FtpFile
- attr_reader :name, :size, :owner, :group, :time
-
- def self.date
- @date_class ||= Date
- end
-
- def self.time
- @time_class ||= Time
- end
-
- def initialize(path, entry)
- @path = path
- @mode, _, @owner, @group, size, d1, d2, d3, @name = entry.split(' ')
- @size = size.to_i
- @time = determine_time(d1, d2, d3)
- end
-
- def path
- File.join(@path, @name)
- end
-
- def directory?
- @mode[0] == ?d
- end
-
- def mode
- parse_mode(@mode)
- end
-
- def symlink?
- @mode[0] == ?l
- end
-
- private # --------------------------------------------------------
-
- def parse_mode(m)
- result = 0
- (1..9).each do |i|
- result = 2*result + ((m[i]==?-) ? 0 : 1)
- end
- result
- end
-
- def determine_time(d1, d2, d3)
- now = self.class.time.now
- if /:/ =~ d3
- result = Time.parse("#{d1} #{d2} #{now.year} #{d3}")
- if result > now
- result = Time.parse("#{d1} #{d2} #{now.year-1} #{d3}")
- end
- else
- result = Time.parse("#{d1} #{d2} #{d3}")
- end
- result
-# elements = ParseDate.parsedate("#{d1} #{d2} #{d3}")
-# if elements[0].nil?
-# today = self.class.date.today
-# if elements[1] > today.month
-# elements[0] = today.year - 1
-# else
-# elements[0] = today.year
-# end
-# end
-# elements = elements.collect { |el| el.nil? ? 0 : el }
-# Time.mktime(*elements[0,7])
- end
- end
-
- ####################################################################
- # Manage the uploading of files to an FTP account.
- class FtpUploader
-
- # Log uploads to standard output when true.
- attr_accessor :verbose
-
- class << FtpUploader
- # Create an uploader and pass it to the given block as +up+.
- # When the block is complete, close the uploader.
- def connect(path, host, account, password)
- up = self.new(path, host, account, password)
- begin
- yield(up)
- ensure
- up.close
- end
- end
- end
-
- # Create an FTP uploader targeting the directory +path+ on +host+
- # using the given account and password. +path+ will be the root
- # path of the uploader.
- def initialize(path, host, account, password)
- @created = Hash.new
- @path = path
- @ftp = Net::FTP.new(host, account, password)
- makedirs(@path)
- @ftp.chdir(@path)
- end
-
- # Create the directory +path+ in the uploader root path.
- def makedirs(path)
- route = []
- File.split(path).each do |dir|
- route << dir
- current_dir = File.join(route)
- if @created[current_dir].nil?
- @created[current_dir] = true
- $stderr.puts "Creating Directory #{current_dir}" if @verbose
- @ftp.mkdir(current_dir) rescue nil
- end
- end
- end
-
- # Upload all files matching +wildcard+ to the uploader's root
- # path.
- def upload_files(wildcard)
- Dir[wildcard].each do |fn|
- upload(fn)
- end
- end
-
- # Close the uploader.
- def close
- @ftp.close
- end
-
- private # --------------------------------------------------------
-
- # Upload a single file to the uploader's root path.
- def upload(file)
- $stderr.puts "Uploading #{file}" if @verbose
- dir = File.dirname(file)
- makedirs(dir)
- @ftp.putbinaryfile(file, file) unless File.directory?(file)
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rake/contrib/publisher.rb b/ruby_1_9_3/lib/rake/contrib/publisher.rb
deleted file mode 100644
index 8b11edb59c..0000000000
--- a/ruby_1_9_3/lib/rake/contrib/publisher.rb
+++ /dev/null
@@ -1,73 +0,0 @@
-# Copyright 2003-2010 by Jim Weirich (jim.weirich@gmail.com)
-# All rights reserved.
-
-# :stopdoc:
-
-# Configuration information about an upload host system.
-# name :: Name of host system.
-# webdir :: Base directory for the web information for the
-# application. The application name (APP) is appended to
-# this directory before using.
-# pkgdir :: Directory on the host system where packages can be
-# placed.
-HostInfo = Struct.new(:name, :webdir, :pkgdir)
-
-# :startdoc:
-
-# Manage several publishers as a single entity.
-class CompositePublisher
- def initialize
- @publishers = []
- end
-
- # Add a publisher to the composite.
- def add(pub)
- @publishers << pub
- end
-
- # Upload all the individual publishers.
- def upload
- @publishers.each { |p| p.upload }
- end
-end
-
-# Publish an entire directory to an existing remote directory using
-# SSH.
-class SshDirPublisher
- def initialize(host, remote_dir, local_dir)
- @host = host
- @remote_dir = remote_dir
- @local_dir = local_dir
- end
-
- def upload
- run %{scp -rq #{@local_dir}/* #{@host}:#{@remote_dir}}
- end
-end
-
-# Publish an entire directory to a fresh remote directory using SSH.
-class SshFreshDirPublisher < SshDirPublisher
- def upload
- run %{ssh #{@host} rm -rf #{@remote_dir}} rescue nil
- run %{ssh #{@host} mkdir #{@remote_dir}}
- super
- end
-end
-
-# Publish a list of files to an existing remote directory.
-class SshFilePublisher
- # Create a publisher using the give host information.
- def initialize(host, remote_dir, local_dir, *files)
- @host = host
- @remote_dir = remote_dir
- @local_dir = local_dir
- @files = files
- end
-
- # Upload the local directory to the remote directory.
- def upload
- @files.each do |fn|
- run %{scp -q #{@local_dir}/#{fn} #{@host}:#{@remote_dir}}
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rake/contrib/rubyforgepublisher.rb b/ruby_1_9_3/lib/rake/contrib/rubyforgepublisher.rb
deleted file mode 100644
index a4b96936c8..0000000000
--- a/ruby_1_9_3/lib/rake/contrib/rubyforgepublisher.rb
+++ /dev/null
@@ -1,16 +0,0 @@
-require 'rake/contrib/sshpublisher'
-
-module Rake
-
- class RubyForgePublisher < SshDirPublisher
- attr_reader :project, :proj_id, :user
-
- def initialize(projname, user)
- super(
- "#{user}@rubyforge.org",
- "/var/www/gforge-projects/#{projname}",
- "html")
- end
- end
-
-end
diff --git a/ruby_1_9_3/lib/rake/contrib/sshpublisher.rb b/ruby_1_9_3/lib/rake/contrib/sshpublisher.rb
deleted file mode 100644
index bd6adc127e..0000000000
--- a/ruby_1_9_3/lib/rake/contrib/sshpublisher.rb
+++ /dev/null
@@ -1,50 +0,0 @@
-require 'rake/dsl_definition'
-require 'rake/contrib/compositepublisher'
-
-module Rake
-
- # Publish an entire directory to an existing remote directory using
- # SSH.
- class SshDirPublisher
- include Rake::DSL
-
- def initialize(host, remote_dir, local_dir)
- @host = host
- @remote_dir = remote_dir
- @local_dir = local_dir
- end
-
- def upload
- sh %{scp -rq #{@local_dir}/* #{@host}:#{@remote_dir}}
- end
- end
-
- # Publish an entire directory to a fresh remote directory using SSH.
- class SshFreshDirPublisher < SshDirPublisher
- def upload
- sh %{ssh #{@host} rm -rf #{@remote_dir}} rescue nil
- sh %{ssh #{@host} mkdir #{@remote_dir}}
- super
- end
- end
-
- # Publish a list of files to an existing remote directory.
- class SshFilePublisher
- include Rake::DSL
-
- # Create a publisher using the give host information.
- def initialize(host, remote_dir, local_dir, *files)
- @host = host
- @remote_dir = remote_dir
- @local_dir = local_dir
- @files = files
- end
-
- # Upload the local directory to the remote directory.
- def upload
- @files.each do |fn|
- sh %{scp -q #{@local_dir}/#{fn} #{@host}:#{@remote_dir}}
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rake/contrib/sys.rb b/ruby_1_9_3/lib/rake/contrib/sys.rb
deleted file mode 100644
index 41963f1fef..0000000000
--- a/ruby_1_9_3/lib/rake/contrib/sys.rb
+++ /dev/null
@@ -1,191 +0,0 @@
-warn 'Sys has been deprecated in favor of FileUtils'
-
-#--
-# Copyright 2003-2010 by Jim Weirich (jim.weirich@gmail.com)
-# All rights reserved.
-#++
-#
-begin
- require 'ftools'
-rescue LoadError
-end
-require 'rbconfig'
-
-######################################################################
-# Sys provides a number of file manipulation tools for the convenience
-# of writing Rakefiles. All commands in this module will announce
-# their activity on standard output if the $verbose flag is set
-# ($verbose = true is the default). You can control this by globally
-# setting $verbose or by using the +verbose+ and +quiet+ methods.
-#
-# Sys has been deprecated in favor of the FileUtils module available
-# in Ruby 1.8.
-#
-module Sys
- RUBY = RbConfig::CONFIG['ruby_install_name']
-
- # Install all the files matching +wildcard+ into the +dest_dir+
- # directory. The permission mode is set to +mode+.
- def install(wildcard, dest_dir, mode)
- Dir[wildcard].each do |fn|
- File.install(fn, dest_dir, mode, $verbose)
- end
- end
-
- # Run the system command +cmd+.
- def run(cmd)
- log cmd
- system(cmd) or fail "Command Failed: [#{cmd}]"
- end
-
- # Run a Ruby interpreter with the given arguments.
- def ruby(*args)
- run "#{RUBY} #{args.join(' ')}"
- end
-
- # Copy a single file from +file_name+ to +dest_file+.
- def copy(file_name, dest_file)
- log "Copying file #{file_name} to #{dest_file}"
- File.copy(file_name, dest_file)
- end
-
- # Copy all files matching +wildcard+ into the directory +dest_dir+.
- def copy_files(wildcard, dest_dir)
- for_matching_files(wildcard, dest_dir) { |from, to| copy(from, to) }
- end
-
- # Link +file_name+ to +dest_file+.
- def link(file_name, dest_file)
- log "Linking file #{file_name} to #{dest_file}"
- File.link(file_name, dest_file)
- end
-
- # Link all files matching +wildcard+ into the directory +dest_dir+.
- def link_files(wildcard, dest_dir)
- for_matching_files(wildcard, dest_dir) { |from, to| link(from, to) }
- end
-
- # Symlink +file_name+ to +dest_file+.
- def symlink(file_name, dest_file)
- log "Symlinking file #{file_name} to #{dest_file}"
- File.symlink(file_name, dest_file)
- end
-
- # Symlink all files matching +wildcard+ into the directory +dest_dir+.
- def symlink_files(wildcard, dest_dir)
- for_matching_files(wildcard, dest_dir) { |from, to| link(from, to) }
- end
-
- # Remove all files matching +wildcard+. If a matching file is a
- # directory, it must be empty to be removed. used +delete_all+ to
- # recursively delete directories.
- def delete(*wildcards)
- wildcards.each do |wildcard|
- Dir[wildcard].each do |fn|
- if File.directory?(fn)
- log "Deleting directory #{fn}"
- Dir.delete(fn)
- else
- log "Deleting file #{fn}"
- File.delete(fn)
- end
- end
- end
- end
-
- # Recursively delete all files and directories matching +wildcard+.
- def delete_all(*wildcards)
- wildcards.each do |wildcard|
- Dir[wildcard].each do |fn|
- next if ! File.exist?(fn)
- if File.directory?(fn)
- Dir["#{fn}/*"].each do |subfn|
- next if subfn=='.' || subfn=='..'
- delete_all(subfn)
- end
- log "Deleting directory #{fn}"
- Dir.delete(fn)
- else
- log "Deleting file #{fn}"
- File.delete(fn)
- end
- end
- end
- end
-
- # Make the directories given in +dirs+.
- def makedirs(*dirs)
- dirs.each do |fn|
- log "Making directory #{fn}"
- File.makedirs(fn)
- end
- end
-
- # Make +dir+ the current working directory for the duration of
- # executing the given block.
- def indir(dir)
- olddir = Dir.pwd
- Dir.chdir(dir)
- yield
- ensure
- Dir.chdir(olddir)
- end
-
- # Split a file path into individual directory names.
- #
- # For example:
- # split_all("a/b/c") => ['a', 'b', 'c']
- def split_all(path)
- head, tail = File.split(path)
- return [tail] if head == '.' || tail == '/'
- return [head, tail] if head == '/'
- return split_all(head) + [tail]
- end
-
- # Write a message to standard error if $verbose is enabled.
- def log(msg)
- print " " if $trace && $verbose
- $stderr.puts msg if $verbose
- end
-
- # Perform a block with $verbose disabled.
- def quiet(&block)
- with_verbose(false, &block)
- end
-
- # Perform a block with $verbose enabled.
- def verbose(&block)
- with_verbose(true, &block)
- end
-
- # Perform a block with each file matching a set of wildcards.
- def for_files(*wildcards)
- wildcards.each do |wildcard|
- Dir[wildcard].each do |fn|
- yield(fn)
- end
- end
- end
-
- extend(self)
-
- private # ----------------------------------------------------------
-
- def for_matching_files(wildcard, dest_dir)
- Dir[wildcard].each do |fn|
- dest_file = File.join(dest_dir, fn)
- parent = File.dirname(dest_file)
- makedirs(parent) if ! File.directory?(parent)
- yield(fn, dest_file)
- end
- end
-
- def with_verbose(v)
- oldverbose = $verbose
- $verbose = v
- yield
- ensure
- $verbose = oldverbose
- end
-
-end
diff --git a/ruby_1_9_3/lib/rake/default_loader.rb b/ruby_1_9_3/lib/rake/default_loader.rb
deleted file mode 100644
index 5dd3c05617..0000000000
--- a/ruby_1_9_3/lib/rake/default_loader.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-module Rake
-
- # Default Rakefile loader used by +import+.
- class DefaultLoader
- def load(fn)
- Rake.load_rakefile(File.expand_path(fn))
- end
- end
-
-end
diff --git a/ruby_1_9_3/lib/rake/dsl_definition.rb b/ruby_1_9_3/lib/rake/dsl_definition.rb
deleted file mode 100644
index 6d9a6b88f3..0000000000
--- a/ruby_1_9_3/lib/rake/dsl_definition.rb
+++ /dev/null
@@ -1,176 +0,0 @@
-# Rake DSL functions.
-require 'rake/file_utils_ext'
-
-module Rake
-
- ##
- # DSL is a module that provides #task, #desc, #namespace, etc. Use this
- # when you'd like to use rake outside the top level scope.
-
- module DSL
-
- #--
- # Include the FileUtils file manipulation functions in the top
- # level module, but mark them private so that they don't
- # unintentionally define methods on other objects.
- #++
-
- include FileUtilsExt
- private(*FileUtils.instance_methods(false))
- private(*FileUtilsExt.instance_methods(false))
-
- private
-
- # Declare a basic task.
- #
- # Example:
- # task :clobber => [:clean] do
- # rm_rf "html"
- # end
- #
- def task(*args, &block)
- Rake::Task.define_task(*args, &block)
- end
-
-
- # Declare a file task.
- #
- # Example:
- # file "config.cfg" => ["config.template"] do
- # open("config.cfg", "w") do |outfile|
- # open("config.template") do |infile|
- # while line = infile.gets
- # outfile.puts line
- # end
- # end
- # end
- # end
- #
- def file(*args, &block)
- Rake::FileTask.define_task(*args, &block)
- end
-
- # Declare a file creation task.
- # (Mainly used for the directory command).
- def file_create(args, &block)
- Rake::FileCreationTask.define_task(args, &block)
- end
-
- # Declare a set of files tasks to create the given directories on
- # demand.
- #
- # Example:
- # directory "testdata/doc"
- #
- def directory(dir)
- Rake.each_dir_parent(dir) do |d|
- file_create d do |t|
- mkdir_p t.name if ! File.exist?(t.name)
- end
- end
- end
-
- # Declare a task that performs its prerequisites in
- # parallel. Multitasks does *not* guarantee that its prerequisites
- # will execute in any given order (which is obvious when you think
- # about it)
- #
- # Example:
- # multitask :deploy => [:deploy_gem, :deploy_rdoc]
- #
- def multitask(args, &block)
- Rake::MultiTask.define_task(args, &block)
- end
-
- # Create a new rake namespace and use it for evaluating the given
- # block. Returns a NameSpace object that can be used to lookup
- # tasks defined in the namespace.
- #
- # E.g.
- #
- # ns = namespace "nested" do
- # task :run
- # end
- # task_run = ns[:run] # find :run in the given namespace.
- #
- def namespace(name=nil, &block)
- name = name.to_s if name.kind_of?(Symbol)
- name = name.to_str if name.respond_to?(:to_str)
- unless name.kind_of?(String) || name.nil?
- raise ArgumentError, "Expected a String or Symbol for a namespace name"
- end
- Rake.application.in_namespace(name, &block)
- end
-
- # Declare a rule for auto-tasks.
- #
- # Example:
- # rule '.o' => '.c' do |t|
- # sh %{cc -o #{t.name} #{t.source}}
- # end
- #
- def rule(*args, &block)
- Rake::Task.create_rule(*args, &block)
- end
-
- # Describe the next rake task.
- #
- # Example:
- # desc "Run the Unit Tests"
- # task :test => [:build]
- # runtests
- # end
- #
- def desc(description)
- Rake.application.last_description = description
- end
-
- # Import the partial Rakefiles +fn+. Imported files are loaded
- # _after_ the current file is completely loaded. This allows the
- # import statement to appear anywhere in the importing file, and yet
- # allowing the imported files to depend on objects defined in the
- # importing file.
- #
- # A common use of the import statement is to include files
- # containing dependency declarations.
- #
- # See also the --rakelibdir command line option.
- #
- # Example:
- # import ".depend", "my_rules"
- #
- def import(*fns)
- fns.each do |fn|
- Rake.application.add_import(fn)
- end
- end
-
- end
-
- DeprecatedCommands = Object.new.extend(DSL)
-
- module DeprecatedObjectDSL # :nodoc:
- DSL.private_instance_methods(false).each do |name|
- line = __LINE__+1
- class_eval %{
- def #{name}(*args, &block)
- unless Rake.application.options.ignore_deprecate
- unless @rake_dsl_warning
- $stderr.puts "WARNING: Global access to Rake DSL methods is deprecated. Please include"
- $stderr.puts " ... Rake::DSL into classes and modules which use the Rake DSL methods."
- @rake_dsl_warning = true
- end
- $stderr.puts "WARNING: DSL method \#{self.class}##{name} called at \#{caller.first}"
- end
- Rake::DeprecatedCommands.send(:#{name}, *args, &block)
- end
- private :#{name}
- }, __FILE__, line
- end
- end
-
- extend FileUtilsExt
-end
-
-self.extend Rake::DSL
-include Rake::DeprecatedObjectDSL
diff --git a/ruby_1_9_3/lib/rake/early_time.rb b/ruby_1_9_3/lib/rake/early_time.rb
deleted file mode 100644
index 8c0e7d3339..0000000000
--- a/ruby_1_9_3/lib/rake/early_time.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-module Rake
-
- # EarlyTime is a fake timestamp that occurs _before_ any other time value.
- class EarlyTime
- include Comparable
- include Singleton
-
- def <=>(other)
- -1
- end
-
- def to_s
- "<EARLY TIME>"
- end
- end
-
- EARLY = EarlyTime.instance
-end
diff --git a/ruby_1_9_3/lib/rake/ext/core.rb b/ruby_1_9_3/lib/rake/ext/core.rb
deleted file mode 100644
index 1f3a738906..0000000000
--- a/ruby_1_9_3/lib/rake/ext/core.rb
+++ /dev/null
@@ -1,27 +0,0 @@
-######################################################################
-# Core extension library
-#
-class Module
- # Check for an existing method in the current class before extending. IF
- # the method already exists, then a warning is printed and the extension is
- # not added. Otherwise the block is yielded and any definitions in the
- # block will take effect.
- #
- # Usage:
- #
- # class String
- # rake_extension("xyz") do
- # def xyz
- # ...
- # end
- # end
- # end
- #
- def rake_extension(method)
- if method_defined?(method)
- $stderr.puts "WARNING: Possible conflict with Rake extension: #{self}##{method} already exists"
- else
- yield
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rake/ext/module.rb b/ruby_1_9_3/lib/rake/ext/module.rb
deleted file mode 100644
index 3f64aef6c8..0000000000
--- a/ruby_1_9_3/lib/rake/ext/module.rb
+++ /dev/null
@@ -1,39 +0,0 @@
-require 'rake/ext/core'
-require 'rake/task'
-require 'rake/file_task'
-require 'rake/file_creation_task'
-require 'rake/application'
-require 'rake/task_manager'
-
-######################################################################
-# Rake extensions to Module.
-#
-class Module
-
- # Rename the original handler to make it available.
- alias :rake_original_const_missing :const_missing
-
- # Check for deprecated uses of top level (i.e. in Object) uses of
- # Rake class names. If someone tries to reference the constant
- # name, display a warning and return the proper object. Using the
- # --classic-namespace command line option will define these
- # constants in Object and avoid this handler.
- def const_missing(const_name)
- case const_name
- when :Task
- Rake.application.const_warning(const_name)
- Rake::Task
- when :FileTask
- Rake.application.const_warning(const_name)
- Rake::FileTask
- when :FileCreationTask
- Rake.application.const_warning(const_name)
- Rake::FileCreationTask
- when :RakeApp
- Rake.application.const_warning(const_name)
- Rake::Application
- else
- rake_original_const_missing(const_name)
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rake/ext/string.rb b/ruby_1_9_3/lib/rake/ext/string.rb
deleted file mode 100644
index fb22a9deb1..0000000000
--- a/ruby_1_9_3/lib/rake/ext/string.rb
+++ /dev/null
@@ -1,167 +0,0 @@
-require 'rake/ext/core'
-
-######################################################################
-# Rake extension methods for String.
-#
-class String
- rake_extension("ext") do
- # Replace the file extension with +newext+. If there is no extension on
- # the string, append the new extension to the end. If the new extension
- # is not given, or is the empty string, remove any existing extension.
- #
- # +ext+ is a user added method for the String class.
- def ext(newext='')
- return self.dup if ['.', '..'].include? self
- if newext != ''
- newext = (newext =~ /^\./) ? newext : ("." + newext)
- end
- self.chomp(File.extname(self)) << newext
- end
- end
-
- rake_extension("pathmap") do
- # Explode a path into individual components. Used by +pathmap+.
- def pathmap_explode
- head, tail = File.split(self)
- return [self] if head == self
- return [tail] if head == '.' || tail == '/'
- return [head, tail] if head == '/'
- return head.pathmap_explode + [tail]
- end
- protected :pathmap_explode
-
- # Extract a partial path from the path. Include +n+ directories from the
- # front end (left hand side) if +n+ is positive. Include |+n+|
- # directories from the back end (right hand side) if +n+ is negative.
- def pathmap_partial(n)
- dirs = File.dirname(self).pathmap_explode
- partial_dirs =
- if n > 0
- dirs[0...n]
- elsif n < 0
- dirs.reverse[0...-n].reverse
- else
- "."
- end
- File.join(partial_dirs)
- end
- protected :pathmap_partial
-
- # Preform the pathmap replacement operations on the given path. The
- # patterns take the form 'pat1,rep1;pat2,rep2...'.
- def pathmap_replace(patterns, &block)
- result = self
- patterns.split(';').each do |pair|
- pattern, replacement = pair.split(',')
- pattern = Regexp.new(pattern)
- if replacement == '*' && block_given?
- result = result.sub(pattern, &block)
- elsif replacement
- result = result.sub(pattern, replacement)
- else
- result = result.sub(pattern, '')
- end
- end
- result
- end
- protected :pathmap_replace
-
- # Map the path according to the given specification. The specification
- # controls the details of the mapping. The following special patterns are
- # recognized:
- #
- # * <b>%p</b> -- The complete path.
- # * <b>%f</b> -- The base file name of the path, with its file extension,
- # but without any directories.
- # * <b>%n</b> -- The file name of the path without its file extension.
- # * <b>%d</b> -- The directory list of the path.
- # * <b>%x</b> -- The file extension of the path. An empty string if there
- # is no extension.
- # * <b>%X</b> -- Everything *but* the file extension.
- # * <b>%s</b> -- The alternate file separator if defined, otherwise use
- # the standard file separator.
- # * <b>%%</b> -- A percent sign.
- #
- # The %d specifier can also have a numeric prefix (e.g. '%2d'). If the
- # number is positive, only return (up to) +n+ directories in the path,
- # starting from the left hand side. If +n+ is negative, return (up to)
- # |+n+| directories from the right hand side of the path.
- #
- # Examples:
- #
- # 'a/b/c/d/file.txt'.pathmap("%2d") => 'a/b'
- # 'a/b/c/d/file.txt'.pathmap("%-2d") => 'c/d'
- #
- # Also the %d, %p, %f, %n, %x, and %X operators can take a
- # pattern/replacement argument to perform simple string substitutions on a
- # particular part of the path. The pattern and replacement are separated
- # by a comma and are enclosed by curly braces. The replacement spec comes
- # after the % character but before the operator letter. (e.g.
- # "%{old,new}d"). Multiple replacement specs should be separated by
- # semi-colons (e.g. "%{old,new;src,bin}d").
- #
- # Regular expressions may be used for the pattern, and back refs may be
- # used in the replacement text. Curly braces, commas and semi-colons are
- # excluded from both the pattern and replacement text (let's keep parsing
- # reasonable).
- #
- # For example:
- #
- # "src/org/onestepback/proj/A.java".pathmap("%{^src,bin}X.class")
- #
- # returns:
- #
- # "bin/org/onestepback/proj/A.class"
- #
- # If the replacement text is '*', then a block may be provided to perform
- # some arbitrary calculation for the replacement.
- #
- # For example:
- #
- # "/path/to/file.TXT".pathmap("%X%{.*,*}x") { |ext|
- # ext.downcase
- # }
- #
- # Returns:
- #
- # "/path/to/file.txt"
- #
- def pathmap(spec=nil, &block)
- return self if spec.nil?
- result = ''
- spec.scan(/%\{[^}]*\}-?\d*[sdpfnxX%]|%-?\d+d|%.|[^%]+/) do |frag|
- case frag
- when '%f'
- result << File.basename(self)
- when '%n'
- result << File.basename(self).ext
- when '%d'
- result << File.dirname(self)
- when '%x'
- result << File.extname(self)
- when '%X'
- result << self.ext
- when '%p'
- result << self
- when '%s'
- result << (File::ALT_SEPARATOR || File::SEPARATOR)
- when '%-'
- # do nothing
- when '%%'
- result << "%"
- when /%(-?\d+)d/
- result << pathmap_partial($1.to_i)
- when /^%\{([^}]*)\}(\d*[dpfnxX])/
- patterns, operator = $1, $2
- result << pathmap('%' + operator).pathmap_replace(patterns, &block)
- when /^%/
- fail ArgumentError, "Unknown pathmap specifier #{frag} in '#{spec}'"
- else
- result << frag
- end
- end
- result
- end
- end
-end # class String
-
diff --git a/ruby_1_9_3/lib/rake/ext/time.rb b/ruby_1_9_3/lib/rake/ext/time.rb
deleted file mode 100644
index 7877abf0ce..0000000000
--- a/ruby_1_9_3/lib/rake/ext/time.rb
+++ /dev/null
@@ -1,14 +0,0 @@
-#--
-# Extensions to time to allow comparisons with an early time class.
-
-class Time
- alias rake_original_time_compare :<=>
- def <=>(other)
- if Rake::EarlyTime === other
- - other.<=>(self)
- else
- rake_original_time_compare(other)
- end
- end
-end
-
diff --git a/ruby_1_9_3/lib/rake/file_creation_task.rb b/ruby_1_9_3/lib/rake/file_creation_task.rb
deleted file mode 100644
index c87e2192bb..0000000000
--- a/ruby_1_9_3/lib/rake/file_creation_task.rb
+++ /dev/null
@@ -1,24 +0,0 @@
-require 'rake/file_task'
-require 'rake/early_time'
-
-module Rake
-
- # A FileCreationTask is a file task that when used as a dependency will be
- # needed if and only if the file has not been created. Once created, it is
- # not re-triggered if any of its dependencies are newer, nor does trigger
- # any rebuilds of tasks that depend on it whenever it is updated.
- #
- class FileCreationTask < FileTask
- # Is this file task needed? Yes if it doesn't exist.
- def needed?
- ! File.exist?(name)
- end
-
- # Time stamp for file creation task. This time stamp is earlier
- # than any other time stamp.
- def timestamp
- Rake::EARLY
- end
- end
-
-end
diff --git a/ruby_1_9_3/lib/rake/file_list.rb b/ruby_1_9_3/lib/rake/file_list.rb
deleted file mode 100644
index e49ccd0147..0000000000
--- a/ruby_1_9_3/lib/rake/file_list.rb
+++ /dev/null
@@ -1,403 +0,0 @@
-require 'rake/cloneable'
-require 'rake/file_utils_ext'
-require 'rake/pathmap'
-
-######################################################################
-module Rake
-
- # #########################################################################
- # A FileList is essentially an array with a few helper methods defined to
- # make file manipulation a bit easier.
- #
- # FileLists are lazy. When given a list of glob patterns for possible files
- # to be included in the file list, instead of searching the file structures
- # to find the files, a FileList holds the pattern for latter use.
- #
- # This allows us to define a number of FileList to match any number of
- # files, but only search out the actual files when then FileList itself is
- # actually used. The key is that the first time an element of the
- # FileList/Array is requested, the pending patterns are resolved into a real
- # list of file names.
- #
- class FileList
-
- include Cloneable
-
- # == Method Delegation
- #
- # The lazy evaluation magic of FileLists happens by implementing all the
- # array specific methods to call +resolve+ before delegating the heavy
- # lifting to an embedded array object (@items).
- #
- # In addition, there are two kinds of delegation calls. The regular kind
- # delegates to the @items array and returns the result directly. Well,
- # almost directly. It checks if the returned value is the @items object
- # itself, and if so will return the FileList object instead.
- #
- # The second kind of delegation call is used in methods that normally
- # return a new Array object. We want to capture the return value of these
- # methods and wrap them in a new FileList object. We enumerate these
- # methods in the +SPECIAL_RETURN+ list below.
-
- # List of array methods (that are not in +Object+) that need to be
- # delegated.
- ARRAY_METHODS = (Array.instance_methods - Object.instance_methods).map { |n| n.to_s }
-
- # List of additional methods that must be delegated.
- MUST_DEFINE = %w[to_a inspect <=>]
-
- # List of methods that should not be delegated here (we define special
- # versions of them explicitly below).
- MUST_NOT_DEFINE = %w[to_a to_ary partition *]
-
- # List of delegated methods that return new array values which need
- # wrapping.
- SPECIAL_RETURN = %w[
- map collect sort sort_by select find_all reject grep
- compact flatten uniq values_at
- + - & |
- ]
-
- DELEGATING_METHODS = (ARRAY_METHODS + MUST_DEFINE - MUST_NOT_DEFINE).collect{ |s| s.to_s }.sort.uniq
-
- # Now do the delegation.
- DELEGATING_METHODS.each_with_index do |sym, i|
- if SPECIAL_RETURN.include?(sym)
- ln = __LINE__+1
- class_eval %{
- def #{sym}(*args, &block)
- resolve
- result = @items.send(:#{sym}, *args, &block)
- FileList.new.import(result)
- end
- }, __FILE__, ln
- else
- ln = __LINE__+1
- class_eval %{
- def #{sym}(*args, &block)
- resolve
- result = @items.send(:#{sym}, *args, &block)
- result.object_id == @items.object_id ? self : result
- end
- }, __FILE__, ln
- end
- end
-
- # Create a file list from the globbable patterns given. If you wish to
- # perform multiple includes or excludes at object build time, use the
- # "yield self" pattern.
- #
- # Example:
- # file_list = FileList.new('lib/**/*.rb', 'test/test*.rb')
- #
- # pkg_files = FileList.new('lib/**/*') do |fl|
- # fl.exclude(/\bCVS\b/)
- # end
- #
- def initialize(*patterns)
- @pending_add = []
- @pending = false
- @exclude_patterns = DEFAULT_IGNORE_PATTERNS.dup
- @exclude_procs = DEFAULT_IGNORE_PROCS.dup
- @items = []
- patterns.each { |pattern| include(pattern) }
- yield self if block_given?
- end
-
- # Add file names defined by glob patterns to the file list. If an array
- # is given, add each element of the array.
- #
- # Example:
- # file_list.include("*.java", "*.cfg")
- # file_list.include %w( math.c lib.h *.o )
- #
- def include(*filenames)
- # TODO: check for pending
- filenames.each do |fn|
- if fn.respond_to? :to_ary
- include(*fn.to_ary)
- else
- @pending_add << fn
- end
- end
- @pending = true
- self
- end
- alias :add :include
-
- # Register a list of file name patterns that should be excluded from the
- # list. Patterns may be regular expressions, glob patterns or regular
- # strings. In addition, a block given to exclude will remove entries that
- # return true when given to the block.
- #
- # Note that glob patterns are expanded against the file system. If a file
- # is explicitly added to a file list, but does not exist in the file
- # system, then an glob pattern in the exclude list will not exclude the
- # file.
- #
- # Examples:
- # FileList['a.c', 'b.c'].exclude("a.c") => ['b.c']
- # FileList['a.c', 'b.c'].exclude(/^a/) => ['b.c']
- #
- # If "a.c" is a file, then ...
- # FileList['a.c', 'b.c'].exclude("a.*") => ['b.c']
- #
- # If "a.c" is not a file, then ...
- # FileList['a.c', 'b.c'].exclude("a.*") => ['a.c', 'b.c']
- #
- def exclude(*patterns, &block)
- patterns.each do |pat|
- @exclude_patterns << pat
- end
- if block_given?
- @exclude_procs << block
- end
- resolve_exclude if ! @pending
- self
- end
-
-
- # Clear all the exclude patterns so that we exclude nothing.
- def clear_exclude
- @exclude_patterns = []
- @exclude_procs = []
- self
- end
-
- # Define equality.
- def ==(array)
- to_ary == array
- end
-
- # Return the internal array object.
- def to_a
- resolve
- @items
- end
-
- # Return the internal array object.
- def to_ary
- to_a
- end
-
- # Lie about our class.
- def is_a?(klass)
- klass == Array || super(klass)
- end
- alias kind_of? is_a?
-
- # Redefine * to return either a string or a new file list.
- def *(other)
- result = @items * other
- case result
- when Array
- FileList.new.import(result)
- else
- result
- end
- end
-
- # Resolve all the pending adds now.
- def resolve
- if @pending
- @pending = false
- @pending_add.each do |fn| resolve_add(fn) end
- @pending_add = []
- resolve_exclude
- end
- self
- end
-
- def resolve_add(fn)
- case fn
- when %r{[*?\[\{]}
- add_matching(fn)
- else
- self << fn
- end
- end
- private :resolve_add
-
- def resolve_exclude
- reject! { |fn| exclude?(fn) }
- self
- end
- private :resolve_exclude
-
- # Return a new FileList with the results of running +sub+ against each
- # element of the original list.
- #
- # Example:
- # FileList['a.c', 'b.c'].sub(/\.c$/, '.o') => ['a.o', 'b.o']
- #
- def sub(pat, rep)
- inject(FileList.new) { |res, fn| res << fn.sub(pat,rep) }
- end
-
- # Return a new FileList with the results of running +gsub+ against each
- # element of the original list.
- #
- # Example:
- # FileList['lib/test/file', 'x/y'].gsub(/\//, "\\")
- # => ['lib\\test\\file', 'x\\y']
- #
- def gsub(pat, rep)
- inject(FileList.new) { |res, fn| res << fn.gsub(pat,rep) }
- end
-
- # Same as +sub+ except that the original file list is modified.
- def sub!(pat, rep)
- each_with_index { |fn, i| self[i] = fn.sub(pat,rep) }
- self
- end
-
- # Same as +gsub+ except that the original file list is modified.
- def gsub!(pat, rep)
- each_with_index { |fn, i| self[i] = fn.gsub(pat,rep) }
- self
- end
-
- # Apply the pathmap spec to each of the included file names, returning a
- # new file list with the modified paths. (See String#pathmap for
- # details.)
- def pathmap(spec=nil)
- collect { |fn| fn.pathmap(spec) }
- end
-
- # Return a new FileList with <tt>String#ext</tt> method applied to
- # each member of the array.
- #
- # This method is a shortcut for:
- #
- # array.collect { |item| item.ext(newext) }
- #
- # +ext+ is a user added method for the Array class.
- def ext(newext='')
- collect { |fn| fn.ext(newext) }
- end
-
-
- # Grep each of the files in the filelist using the given pattern. If a
- # block is given, call the block on each matching line, passing the file
- # name, line number, and the matching line of text. If no block is given,
- # a standard emacs style file:linenumber:line message will be printed to
- # standard out. Returns the number of matched items.
- def egrep(pattern, *options)
- matched = 0
- each do |fn|
- begin
- open(fn, "r:ascii-8bit", *options) do |inf|
- count = 0
- inf.each do |line|
- count += 1
- if pattern.match(line)
- matched += 1
- if block_given?
- yield fn, count, line
- else
- puts "#{fn}:#{count}:#{line}"
- end
- end
- end
- end
- rescue StandardError => ex
- $stderr.puts "Error while processing '#{fn}': #{ex}"
- end
- end
- matched
- end
-
- # Return a new file list that only contains file names from the current
- # file list that exist on the file system.
- def existing
- select { |fn| File.exist?(fn) }
- end
-
- # Modify the current file list so that it contains only file name that
- # exist on the file system.
- def existing!
- resolve
- @items = @items.select { |fn| File.exist?(fn) }
- self
- end
-
- # FileList version of partition. Needed because the nested arrays should
- # be FileLists in this version.
- def partition(&block) # :nodoc:
- resolve
- result = @items.partition(&block)
- [
- FileList.new.import(result[0]),
- FileList.new.import(result[1]),
- ]
- end
-
- # Convert a FileList to a string by joining all elements with a space.
- def to_s
- resolve
- self.join(' ')
- end
-
- # Add matching glob patterns.
- def add_matching(pattern)
- Dir[pattern].each do |fn|
- self << fn unless exclude?(fn)
- end
- end
- private :add_matching
-
- # Should the given file name be excluded?
- def exclude?(fn)
- return true if @exclude_patterns.any? do |pat|
- case pat
- when Regexp
- fn =~ pat
- when /[*?]/
- File.fnmatch?(pat, fn, File::FNM_PATHNAME)
- else
- fn == pat
- end
- end
- @exclude_procs.any? { |p| p.call(fn) }
- end
-
- DEFAULT_IGNORE_PATTERNS = [
- /(^|[\/\\])CVS([\/\\]|$)/,
- /(^|[\/\\])\.svn([\/\\]|$)/,
- /\.bak$/,
- /~$/
- ]
- DEFAULT_IGNORE_PROCS = [
- proc { |fn| fn =~ /(^|[\/\\])core$/ && ! File.directory?(fn) }
- ]
-
- def import(array)
- @items = array
- self
- end
-
- class << self
- # Create a new file list including the files listed. Similar to:
- #
- # FileList.new(*args)
- def [](*args)
- new(*args)
- end
- end
- end
-end
-
-module Rake
- class << self
-
- # Yield each file or directory component.
- def each_dir_parent(dir) # :nodoc:
- old_length = nil
- while dir != '.' && dir.length != old_length
- yield(dir)
- old_length = dir.length
- dir = File.dirname(dir)
- end
- end
- end
-end # module Rake
diff --git a/ruby_1_9_3/lib/rake/file_task.rb b/ruby_1_9_3/lib/rake/file_task.rb
deleted file mode 100644
index 78902a86fd..0000000000
--- a/ruby_1_9_3/lib/rake/file_task.rb
+++ /dev/null
@@ -1,47 +0,0 @@
-require 'rake/task.rb'
-require 'rake/early_time'
-
-module Rake
- # #########################################################################
- # A FileTask is a task that includes time based dependencies. If any of a
- # FileTask's prerequisites have a timestamp that is later than the file
- # represented by this task, then the file must be rebuilt (using the
- # supplied actions).
- #
- class FileTask < Task
-
- # Is this file task needed? Yes if it doesn't exist, or if its time stamp
- # is out of date.
- def needed?
- ! File.exist?(name) || out_of_date?(timestamp)
- end
-
- # Time stamp for file task.
- def timestamp
- if File.exist?(name)
- File.mtime(name.to_s)
- else
- Rake::EARLY
- end
- end
-
- private
-
- # Are there any prerequisites with a later time than the given time stamp?
- def out_of_date?(stamp)
- @prerequisites.any? { |n| application[n, @scope].timestamp > stamp}
- end
-
- # ----------------------------------------------------------------
- # Task class methods.
- #
- class << self
- # Apply the scope to the task name according to the rules for this kind
- # of task. File based tasks ignore the scope when creating the name.
- def scope_name(scope, task_name)
- task_name
- end
- end
- end
-end
-
diff --git a/ruby_1_9_3/lib/rake/file_utils.rb b/ruby_1_9_3/lib/rake/file_utils.rb
deleted file mode 100644
index e02d541ab8..0000000000
--- a/ruby_1_9_3/lib/rake/file_utils.rb
+++ /dev/null
@@ -1,114 +0,0 @@
-require 'rbconfig'
-require 'fileutils'
-
-#--
-# This a FileUtils extension that defines several additional commands to be
-# added to the FileUtils utility functions.
-module FileUtils
- # Path to the currently running Ruby program
- RUBY = File.join(
- RbConfig::CONFIG['bindir'],
- RbConfig::CONFIG['ruby_install_name'] + RbConfig::CONFIG['EXEEXT']).
- sub(/.*\s.*/m, '"\&"')
-
- OPT_TABLE['sh'] = %w(noop verbose)
- OPT_TABLE['ruby'] = %w(noop verbose)
-
- # Run the system command +cmd+. If multiple arguments are given the command
- # is not run with the shell (same semantics as Kernel::exec and
- # Kernel::system).
- #
- # Example:
- # sh %{ls -ltr}
- #
- # sh 'ls', 'file with spaces'
- #
- # # check exit status after command runs
- # sh %{grep pattern file} do |ok, res|
- # if ! ok
- # puts "pattern not found (status = #{res.exitstatus})"
- # end
- # end
- #
- def sh(*cmd, &block)
- options = (Hash === cmd.last) ? cmd.pop : {}
- shell_runner = block_given? ? block : create_shell_runner(cmd)
- set_verbose_option(options)
- options[:noop] ||= Rake::FileUtilsExt.nowrite_flag
- Rake.rake_check_options options, :noop, :verbose
- Rake.rake_output_message cmd.join(" ") if options[:verbose]
-
- unless options[:noop]
- res = rake_system(*cmd)
- status = $?
- status = PseudoStatus.new(1) if !res && status.nil?
- shell_runner.call(res, status)
- end
- end
-
- def create_shell_runner(cmd) # :nodoc:
- show_command = cmd.join(" ")
- show_command = show_command[0,42] + "..." unless $trace
- lambda { |ok, status|
- ok or fail "Command failed with status (#{status.exitstatus}): [#{show_command}]"
- }
- end
- private :create_shell_runner
-
- def set_verbose_option(options) # :nodoc:
- unless options.key? :verbose
- options[:verbose] =
- Rake::FileUtilsExt.verbose_flag == Rake::FileUtilsExt::DEFAULT ||
- Rake::FileUtilsExt.verbose_flag
- end
- end
- private :set_verbose_option
-
- def rake_system(*cmd) # :nodoc:
- Rake::AltSystem.system(*cmd)
- end
- private :rake_system
-
- # Run a Ruby interpreter with the given arguments.
- #
- # Example:
- # ruby %{-pe '$_.upcase!' <README}
- #
- def ruby(*args,&block)
- options = (Hash === args.last) ? args.pop : {}
- if args.length > 1 then
- sh(*([RUBY] + args + [options]), &block)
- else
- sh("#{RUBY} #{args.first}", options, &block)
- end
- end
-
- LN_SUPPORTED = [true]
-
- # Attempt to do a normal file link, but fall back to a copy if the link
- # fails.
- def safe_ln(*args)
- unless LN_SUPPORTED[0]
- cp(*args)
- else
- begin
- ln(*args)
- rescue StandardError, NotImplementedError
- LN_SUPPORTED[0] = false
- cp(*args)
- end
- end
- end
-
- # Split a file path into individual directory names.
- #
- # Example:
- # split_all("a/b/c") => ['a', 'b', 'c']
- #
- def split_all(path)
- head, tail = File.split(path)
- return [tail] if head == '.' || tail == '/'
- return [head, tail] if head == '/'
- return split_all(head) + [tail]
- end
-end
diff --git a/ruby_1_9_3/lib/rake/file_utils_ext.rb b/ruby_1_9_3/lib/rake/file_utils_ext.rb
deleted file mode 100644
index 557420df80..0000000000
--- a/ruby_1_9_3/lib/rake/file_utils_ext.rb
+++ /dev/null
@@ -1,145 +0,0 @@
-require 'rake/file_utils'
-
-module Rake
- #
- # FileUtilsExt provides a custom version of the FileUtils methods
- # that respond to the <tt>verbose</tt> and <tt>nowrite</tt>
- # commands.
- #
- module FileUtilsExt
- include FileUtils
-
- class << self
- attr_accessor :verbose_flag, :nowrite_flag
- end
-
- DEFAULT = Object.new
-
- FileUtilsExt.verbose_flag = DEFAULT
- FileUtilsExt.nowrite_flag = false
-
- $fileutils_verbose = true
- $fileutils_nowrite = false
-
- FileUtils::OPT_TABLE.each do |name, opts|
- default_options = []
- if opts.include?(:verbose) || opts.include?("verbose")
- default_options << ':verbose => FileUtilsExt.verbose_flag'
- end
- if opts.include?(:noop) || opts.include?("noop")
- default_options << ':noop => FileUtilsExt.nowrite_flag'
- end
-
- next if default_options.empty?
- module_eval(<<-EOS, __FILE__, __LINE__ + 1)
- def #{name}( *args, &block )
- super(
- *rake_merge_option(args,
- #{default_options.join(', ')}
- ), &block)
- end
- EOS
- end
-
- # Get/set the verbose flag controlling output from the FileUtils
- # utilities. If verbose is true, then the utility method is
- # echoed to standard output.
- #
- # Examples:
- # verbose # return the current value of the
- # # verbose flag
- # verbose(v) # set the verbose flag to _v_.
- # verbose(v) { code } # Execute code with the verbose flag set
- # # temporarily to _v_. Return to the
- # # original value when code is done.
- def verbose(value=nil)
- oldvalue = FileUtilsExt.verbose_flag
- FileUtilsExt.verbose_flag = value unless value.nil?
- if block_given?
- begin
- yield
- ensure
- FileUtilsExt.verbose_flag = oldvalue
- end
- end
- FileUtilsExt.verbose_flag
- end
-
- # Get/set the nowrite flag controlling output from the FileUtils
- # utilities. If verbose is true, then the utility method is
- # echoed to standard output.
- #
- # Examples:
- # nowrite # return the current value of the
- # # nowrite flag
- # nowrite(v) # set the nowrite flag to _v_.
- # nowrite(v) { code } # Execute code with the nowrite flag set
- # # temporarily to _v_. Return to the
- # # original value when code is done.
- def nowrite(value=nil)
- oldvalue = FileUtilsExt.nowrite_flag
- FileUtilsExt.nowrite_flag = value unless value.nil?
- if block_given?
- begin
- yield
- ensure
- FileUtilsExt.nowrite_flag = oldvalue
- end
- end
- oldvalue
- end
-
- # Use this function to prevent potentially destructive ruby code
- # from running when the :nowrite flag is set.
- #
- # Example:
- #
- # when_writing("Building Project") do
- # project.build
- # end
- #
- # The following code will build the project under normal
- # conditions. If the nowrite(true) flag is set, then the example
- # will print:
- #
- # DRYRUN: Building Project
- #
- # instead of actually building the project.
- #
- def when_writing(msg=nil)
- if FileUtilsExt.nowrite_flag
- $stderr.puts "DRYRUN: #{msg}" if msg
- else
- yield
- end
- end
-
- # Merge the given options with the default values.
- def rake_merge_option(args, defaults)
- if Hash === args.last
- defaults.update(args.last)
- args.pop
- end
- args.push defaults
- args
- end
-
- # Send the message to the default rake output (which is $stderr).
- def rake_output_message(message)
- $stderr.puts(message)
- end
-
- # Check that the options do not contain options not listed in
- # +optdecl+. An ArgumentError exception is thrown if non-declared
- # options are found.
- def rake_check_options(options, *optdecl)
- h = options.dup
- optdecl.each do |name|
- h.delete name
- end
- raise ArgumentError, "no such option: #{h.keys.join(' ')}" unless h.empty?
- end
-
- extend self
- end
-end
diff --git a/ruby_1_9_3/lib/rake/gempackagetask.rb b/ruby_1_9_3/lib/rake/gempackagetask.rb
deleted file mode 100644
index 5f1fc4def8..0000000000
--- a/ruby_1_9_3/lib/rake/gempackagetask.rb
+++ /dev/null
@@ -1,15 +0,0 @@
-# rake/gempackagetask is deprecated in favor of rubygems/package_task
-
-warn 'rake/gempackagetask is deprecated. Use rubygems/package_task instead'
-
-require 'rubygems'
-require 'rubygems/package_task'
-
-require 'rake'
-
-# :stopdoc:
-
-module Rake
- GemPackageTask = Gem::PackageTask
-end
-
diff --git a/ruby_1_9_3/lib/rake/invocation_chain.rb b/ruby_1_9_3/lib/rake/invocation_chain.rb
deleted file mode 100644
index 8a01ab4c29..0000000000
--- a/ruby_1_9_3/lib/rake/invocation_chain.rb
+++ /dev/null
@@ -1,51 +0,0 @@
-module Rake
-
- ####################################################################
- # InvocationChain tracks the chain of task invocations to detect
- # circular dependencies.
- class InvocationChain
- def initialize(value, tail)
- @value = value
- @tail = tail
- end
-
- def member?(obj)
- @value == obj || @tail.member?(obj)
- end
-
- def append(value)
- if member?(value)
- fail RuntimeError, "Circular dependency detected: #{to_s} => #{value}"
- end
- self.class.new(value, self)
- end
-
- def to_s
- "#{prefix}#{@value}"
- end
-
- def self.append(value, chain)
- chain.append(value)
- end
-
- private
-
- def prefix
- "#{@tail.to_s} => "
- end
-
- class EmptyInvocationChain
- def member?(obj)
- false
- end
- def append(value)
- InvocationChain.new(value, self)
- end
- def to_s
- "TOP"
- end
- end
-
- EMPTY = EmptyInvocationChain.new
- end
-end
diff --git a/ruby_1_9_3/lib/rake/invocation_exception_mixin.rb b/ruby_1_9_3/lib/rake/invocation_exception_mixin.rb
deleted file mode 100644
index 84ff3353ba..0000000000
--- a/ruby_1_9_3/lib/rake/invocation_exception_mixin.rb
+++ /dev/null
@@ -1,16 +0,0 @@
-module Rake
- module InvocationExceptionMixin
- # Return the invocation chain (list of Rake tasks) that were in
- # effect when this exception was detected by rake. May be null if
- # no tasks were active.
- def chain
- @rake_invocation_chain ||= nil
- end
-
- # Set the invocation chain in effect when this exception was
- # detected.
- def chain=(value)
- @rake_invocation_chain = value
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rake/lib/project.rake b/ruby_1_9_3/lib/rake/lib/project.rake
deleted file mode 100644
index a5497328a7..0000000000
--- a/ruby_1_9_3/lib/rake/lib/project.rake
+++ /dev/null
@@ -1,21 +0,0 @@
-task "create:project" => ["lib", "test", "Rakefile"]
-
-directory "lib"
-directory "test"
-
-file "Rakefile" do
- File.open("Rakefile", "w") do |out|
- out.puts %{# -*- ruby -*-
-
-require 'rake/clean'
-require 'rake/testtask'
-
-task :default => :test
-
-Rake::TestTask.new do |t|
- t.verbose = false
- t.test_files = FileList['test/test_*.rb']
-end
-}
- end
-end
diff --git a/ruby_1_9_3/lib/rake/loaders/makefile.rb b/ruby_1_9_3/lib/rake/loaders/makefile.rb
deleted file mode 100644
index 4ece4323af..0000000000
--- a/ruby_1_9_3/lib/rake/loaders/makefile.rb
+++ /dev/null
@@ -1,40 +0,0 @@
-module Rake
-
- # Makefile loader to be used with the import file loader.
- class MakefileLoader
- include Rake::DSL
-
- SPACE_MARK = "\0"
-
- # Load the makefile dependencies in +fn+.
- def load(fn)
- lines = File.read fn
- lines.gsub!(/\\ /, SPACE_MARK)
- lines.gsub!(/#[^\n]*\n/m, "")
- lines.gsub!(/\\\n/, ' ')
- lines.each_line do |line|
- process_line(line)
- end
- end
-
- private
-
- # Process one logical line of makefile data.
- def process_line(line)
- file_tasks, args = line.split(':', 2)
- return if args.nil?
- dependents = args.split.map { |d| respace(d) }
- file_tasks.scan(/\S+/) do |file_task|
- file_task = respace(file_task)
- file file_task => dependents
- end
- end
-
- def respace(str)
- str.tr SPACE_MARK, ' '
- end
- end
-
- # Install the handler
- Rake.application.add_loader('mf', MakefileLoader.new)
-end
diff --git a/ruby_1_9_3/lib/rake/multi_task.rb b/ruby_1_9_3/lib/rake/multi_task.rb
deleted file mode 100644
index 21c8de732f..0000000000
--- a/ruby_1_9_3/lib/rake/multi_task.rb
+++ /dev/null
@@ -1,16 +0,0 @@
-module Rake
-
- # Same as a regular task, but the immediate prerequisites are done in
- # parallel using Ruby threads.
- #
- class MultiTask < Task
- private
- def invoke_prerequisites(args, invocation_chain)
- threads = @prerequisites.collect { |p|
- Thread.new(p) { |r| application[r, @scope].invoke_with_call_chain(args, invocation_chain) }
- }
- threads.each { |t| t.join }
- end
- end
-
-end
diff --git a/ruby_1_9_3/lib/rake/name_space.rb b/ruby_1_9_3/lib/rake/name_space.rb
deleted file mode 100644
index e1cc0940b8..0000000000
--- a/ruby_1_9_3/lib/rake/name_space.rb
+++ /dev/null
@@ -1,25 +0,0 @@
-module Rake
-
- # The NameSpace class will lookup task names in the the scope
- # defined by a +namespace+ command.
- #
- class NameSpace
-
- # Create a namespace lookup object using the given task manager
- # and the list of scopes.
- def initialize(task_manager, scope_list)
- @task_manager = task_manager
- @scope = scope_list.dup
- end
-
- # Lookup a task named +name+ in the namespace.
- def [](name)
- @task_manager.lookup(name, @scope)
- end
-
- # Return the list of tasks defined in this and nested namespaces.
- def tasks
- @task_manager.tasks_in_scope(@scope)
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rake/packagetask.rb b/ruby_1_9_3/lib/rake/packagetask.rb
deleted file mode 100644
index 08c1a8c025..0000000000
--- a/ruby_1_9_3/lib/rake/packagetask.rb
+++ /dev/null
@@ -1,185 +0,0 @@
-# Define a package task library to aid in the definition of
-# redistributable package files.
-
-require 'rake'
-require 'rake/tasklib'
-
-module Rake
-
- # Create a packaging task that will package the project into
- # distributable files (e.g zip archive or tar files).
- #
- # The PackageTask will create the following targets:
- #
- # [<b>:package</b>]
- # Create all the requested package files.
- #
- # [<b>:clobber_package</b>]
- # Delete all the package files. This target is automatically
- # added to the main clobber target.
- #
- # [<b>:repackage</b>]
- # Rebuild the package files from scratch, even if they are not out
- # of date.
- #
- # [<b>"<em>package_dir</em>/<em>name</em>-<em>version</em>.tgz"</b>]
- # Create a gzipped tar package (if <em>need_tar</em> is true).
- #
- # [<b>"<em>package_dir</em>/<em>name</em>-<em>version</em>.tar.gz"</b>]
- # Create a gzipped tar package (if <em>need_tar_gz</em> is true).
- #
- # [<b>"<em>package_dir</em>/<em>name</em>-<em>version</em>.tar.bz2"</b>]
- # Create a bzip2'd tar package (if <em>need_tar_bz2</em> is true).
- #
- # [<b>"<em>package_dir</em>/<em>name</em>-<em>version</em>.zip"</b>]
- # Create a zip package archive (if <em>need_zip</em> is true).
- #
- # Example:
- #
- # Rake::PackageTask.new("rake", "1.2.3") do |p|
- # p.need_tar = true
- # p.package_files.include("lib/**/*.rb")
- # end
- #
- class PackageTask < TaskLib
- # Name of the package (from the GEM Spec).
- attr_accessor :name
-
- # Version of the package (e.g. '1.3.2').
- attr_accessor :version
-
- # Directory used to store the package files (default is 'pkg').
- attr_accessor :package_dir
-
- # True if a gzipped tar file (tgz) should be produced (default is false).
- attr_accessor :need_tar
-
- # True if a gzipped tar file (tar.gz) should be produced (default is false).
- attr_accessor :need_tar_gz
-
- # True if a bzip2'd tar file (tar.bz2) should be produced (default is false).
- attr_accessor :need_tar_bz2
-
- # True if a zip file should be produced (default is false)
- attr_accessor :need_zip
-
- # List of files to be included in the package.
- attr_accessor :package_files
-
- # Tar command for gzipped or bzip2ed archives. The default is 'tar'.
- attr_accessor :tar_command
-
- # Zip command for zipped archives. The default is 'zip'.
- attr_accessor :zip_command
-
- # Create a Package Task with the given name and version. Use +:noversion+
- # as the version to build a package without a version or to provide a
- # fully-versioned package name.
-
- def initialize(name=nil, version=nil)
- init(name, version)
- yield self if block_given?
- define unless name.nil?
- end
-
- # Initialization that bypasses the "yield self" and "define" step.
- def init(name, version)
- @name = name
- @version = version
- @package_files = Rake::FileList.new
- @package_dir = 'pkg'
- @need_tar = false
- @need_tar_gz = false
- @need_tar_bz2 = false
- @need_zip = false
- @tar_command = 'tar'
- @zip_command = 'zip'
- end
-
- # Create the tasks defined by this task library.
- def define
- fail "Version required (or :noversion)" if @version.nil?
- @version = nil if :noversion == @version
-
- desc "Build all the packages"
- task :package
-
- desc "Force a rebuild of the package files"
- task :repackage => [:clobber_package, :package]
-
- desc "Remove package products"
- task :clobber_package do
- rm_r package_dir rescue nil
- end
-
- task :clobber => [:clobber_package]
-
- [
- [need_tar, tgz_file, "z"],
- [need_tar_gz, tar_gz_file, "z"],
- [need_tar_bz2, tar_bz2_file, "j"]
- ].each do |(need, file, flag)|
- if need
- task :package => ["#{package_dir}/#{file}"]
- file "#{package_dir}/#{file}" => [package_dir_path] + package_files do
- chdir(package_dir) do
- sh %{#{@tar_command} #{flag}cvf #{file} #{package_name}}
- end
- end
- end
- end
-
- if need_zip
- task :package => ["#{package_dir}/#{zip_file}"]
- file "#{package_dir}/#{zip_file}" => [package_dir_path] + package_files do
- chdir(package_dir) do
- sh %{#{@zip_command} -r #{zip_file} #{package_name}}
- end
- end
- end
-
- directory package_dir
-
- file package_dir_path => @package_files do
- mkdir_p package_dir rescue nil
- @package_files.each do |fn|
- f = File.join(package_dir_path, fn)
- fdir = File.dirname(f)
- mkdir_p(fdir) if !File.exist?(fdir)
- if File.directory?(fn)
- mkdir_p(f)
- else
- rm_f f
- safe_ln(fn, f)
- end
- end
- end
- self
- end
-
- def package_name
- @version ? "#{@name}-#{@version}" : @name
- end
-
- def package_dir_path
- "#{package_dir}/#{package_name}"
- end
-
- def tgz_file
- "#{package_name}.tgz"
- end
-
- def tar_gz_file
- "#{package_name}.tar.gz"
- end
-
- def tar_bz2_file
- "#{package_name}.tar.bz2"
- end
-
- def zip_file
- "#{package_name}.zip"
- end
- end
-
-end
diff --git a/ruby_1_9_3/lib/rake/pathmap.rb b/ruby_1_9_3/lib/rake/pathmap.rb
deleted file mode 100644
index 2275724341..0000000000
--- a/ruby_1_9_3/lib/rake/pathmap.rb
+++ /dev/null
@@ -1 +0,0 @@
-require 'rake/ext/string'
diff --git a/ruby_1_9_3/lib/rake/pseudo_status.rb b/ruby_1_9_3/lib/rake/pseudo_status.rb
deleted file mode 100644
index b58df3da18..0000000000
--- a/ruby_1_9_3/lib/rake/pseudo_status.rb
+++ /dev/null
@@ -1,24 +0,0 @@
-module Rake
-
- ####################################################################
- # Exit status class for times the system just gives us a nil.
- class PseudoStatus
- attr_reader :exitstatus
- def initialize(code=0)
- @exitstatus = code
- end
- def to_i
- @exitstatus << 8
- end
- def >>(n)
- to_i >> n
- end
- def stopped?
- false
- end
- def exited?
- true
- end
- end
-
-end
diff --git a/ruby_1_9_3/lib/rake/rake_module.rb b/ruby_1_9_3/lib/rake/rake_module.rb
deleted file mode 100644
index a9d210c637..0000000000
--- a/ruby_1_9_3/lib/rake/rake_module.rb
+++ /dev/null
@@ -1,29 +0,0 @@
-require 'rake/application'
-
-module Rake
-
- # Rake module singleton methods.
- #
- class << self
- # Current Rake Application
- def application
- @application ||= Rake::Application.new
- end
-
- # Set the current Rake application object.
- def application=(app)
- @application = app
- end
-
- # Return the original directory where the Rake application was started.
- def original_dir
- application.original_dir
- end
-
- # Load a rakefile.
- def load_rakefile(path)
- load(path)
- end
- end
-
-end
diff --git a/ruby_1_9_3/lib/rake/rake_test_loader.rb b/ruby_1_9_3/lib/rake/rake_test_loader.rb
deleted file mode 100644
index 7e3a6b3f35..0000000000
--- a/ruby_1_9_3/lib/rake/rake_test_loader.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-require 'rake'
-
-# Load the test files from the command line.
-argv = ARGV.select do |argument|
- case argument
- when /^-/ then
- argument
- when /\*/ then
- FileList[argument].to_a.each do |file|
- require File.expand_path file
- end
-
- false
- else
- require File.expand_path argument
-
- false
- end
-end
-
-ARGV.replace argv
-
diff --git a/ruby_1_9_3/lib/rake/rdoctask.rb b/ruby_1_9_3/lib/rake/rdoctask.rb
deleted file mode 100644
index b6ae224a9e..0000000000
--- a/ruby_1_9_3/lib/rake/rdoctask.rb
+++ /dev/null
@@ -1,234 +0,0 @@
-# rake/rdoctask is deprecated in favor of rdoc/task
-
-if Rake.application
- Rake.application.deprecate('require \'rake/rdoctask\'', 'require \'rdoc/task\' (in RDoc 2.4.2+)', __FILE__)
-end
-
-require 'rubygems'
-
-begin
- gem 'rdoc'
- require 'rdoc'
- require 'rdoc/task'
-rescue LoadError, Gem::LoadError
-end
-
-# :stopdoc:
-
-if defined?(RDoc::Task) then
- module Rake
- RDocTask = RDoc::Task unless const_defined? :RDocTask
- end
-else
- require 'rake'
- require 'rake/tasklib'
-
- module Rake
-
- # NOTE: Rake::RDocTask is deprecated in favor of RDoc:Task which is included
- # in RDoc 2.4.2+. Use require 'rdoc/task' to require it.
- #
- # Create a documentation task that will generate the RDoc files for
- # a project.
- #
- # The RDocTask will create the following targets:
- #
- # [<b><em>rdoc</em></b>]
- # Main task for this RDOC task.
- #
- # [<b>:clobber_<em>rdoc</em></b>]
- # Delete all the rdoc files. This target is automatically
- # added to the main clobber target.
- #
- # [<b>:re<em>rdoc</em></b>]
- # Rebuild the rdoc files from scratch, even if they are not out
- # of date.
- #
- # Simple Example:
- #
- # Rake::RDocTask.new do |rd|
- # rd.main = "README.rdoc"
- # rd.rdoc_files.include("README.rdoc", "lib/**/*.rb")
- # end
- #
- # The +rd+ object passed to the block is an RDocTask object. See the
- # attributes list for the RDocTask class for available customization options.
- #
- # == Specifying different task names
- #
- # You may wish to give the task a different name, such as if you are
- # generating two sets of documentation. For instance, if you want to have a
- # development set of documentation including private methods:
- #
- # Rake::RDocTask.new(:rdoc_dev) do |rd|
- # rd.main = "README.doc"
- # rd.rdoc_files.include("README.rdoc", "lib/**/*.rb")
- # rd.options << "--all"
- # end
- #
- # The tasks would then be named :<em>rdoc_dev</em>, :clobber_<em>rdoc_dev</em>, and
- # :re<em>rdoc_dev</em>.
- #
- # If you wish to have completely different task names, then pass a Hash as
- # first argument. With the <tt>:rdoc</tt>, <tt>:clobber_rdoc</tt> and
- # <tt>:rerdoc</tt> options, you can customize the task names to your liking.
- # For example:
- #
- # Rake::RDocTask.new(:rdoc => "rdoc", :clobber_rdoc => "rdoc:clean", :rerdoc => "rdoc:force")
- #
- # This will create the tasks <tt>:rdoc</tt>, <tt>:rdoc_clean</tt> and
- # <tt>:rdoc:force</tt>.
- #
- class RDocTask < TaskLib
- # Name of the main, top level task. (default is :rdoc)
- attr_accessor :name
-
- # Name of directory to receive the html output files. (default is "html")
- attr_accessor :rdoc_dir
-
- # Title of RDoc documentation. (defaults to rdoc's default)
- attr_accessor :title
-
- # Name of file to be used as the main, top level file of the
- # RDoc. (default is none)
- attr_accessor :main
-
- # Name of template to be used by rdoc. (defaults to rdoc's default)
- attr_accessor :template
-
- # List of files to be included in the rdoc generation. (default is [])
- attr_accessor :rdoc_files
-
- # Additional list of options to be passed rdoc. (default is [])
- attr_accessor :options
-
- # Whether to run the rdoc process as an external shell (default is false)
- attr_accessor :external
-
- attr_accessor :inline_source
-
- # Create an RDoc task with the given name. See the RDocTask class overview
- # for documentation.
- def initialize(name = :rdoc) # :yield: self
- if name.is_a?(Hash)
- invalid_options = name.keys.map { |k| k.to_sym } - [:rdoc, :clobber_rdoc, :rerdoc]
- if !invalid_options.empty?
- raise ArgumentError, "Invalid option(s) passed to RDocTask.new: #{invalid_options.join(", ")}"
- end
- end
-
- @name = name
- @rdoc_files = Rake::FileList.new
- @rdoc_dir = 'html'
- @main = nil
- @title = nil
- @template = nil
- @external = false
- @inline_source = true
- @options = []
- yield self if block_given?
- define
- end
-
- # Create the tasks defined by this task lib.
- def define
- if rdoc_task_name != "rdoc"
- desc "Build the RDOC HTML Files"
- else
- desc "Build the #{rdoc_task_name} HTML Files"
- end
- task rdoc_task_name
-
- desc "Force a rebuild of the RDOC files"
- task rerdoc_task_name => [clobber_task_name, rdoc_task_name]
-
- desc "Remove rdoc products"
- task clobber_task_name do
- rm_r rdoc_dir rescue nil
- end
-
- task :clobber => [clobber_task_name]
-
- directory @rdoc_dir
- task rdoc_task_name => [rdoc_target]
- file rdoc_target => @rdoc_files + [Rake.application.rakefile] do
- rm_r @rdoc_dir rescue nil
- @before_running_rdoc.call if @before_running_rdoc
- args = option_list + @rdoc_files
- if @external
- argstring = args.join(' ')
- sh %{ruby -Ivendor vendor/rd #{argstring}}
- else
- require 'rdoc/rdoc'
- RDoc::RDoc.new.document(args)
- end
- end
- self
- end
-
- def option_list
- result = @options.dup
- result << "-o" << @rdoc_dir
- result << "--main" << quote(main) if main
- result << "--title" << quote(title) if title
- result << "-T" << quote(template) if template
- result << "--inline-source" if inline_source && !@options.include?("--inline-source") && !@options.include?("-S")
- result
- end
-
- def quote(str)
- if @external
- "'#{str}'"
- else
- str
- end
- end
-
- def option_string
- option_list.join(' ')
- end
-
- # The block passed to this method will be called just before running the
- # RDoc generator. It is allowed to modify RDocTask attributes inside the
- # block.
- def before_running_rdoc(&block)
- @before_running_rdoc = block
- end
-
- private
-
- def rdoc_target
- "#{rdoc_dir}/index.html"
- end
-
- def rdoc_task_name
- case name
- when Hash
- (name[:rdoc] || "rdoc").to_s
- else
- name.to_s
- end
- end
-
- def clobber_task_name
- case name
- when Hash
- (name[:clobber_rdoc] || "clobber_rdoc").to_s
- else
- "clobber_#{name}"
- end
- end
-
- def rerdoc_task_name
- case name
- when Hash
- (name[:rerdoc] || "rerdoc").to_s
- else
- "re#{name}"
- end
- end
-
- end
- end
-end
-
diff --git a/ruby_1_9_3/lib/rake/ruby182_test_unit_fix.rb b/ruby_1_9_3/lib/rake/ruby182_test_unit_fix.rb
deleted file mode 100755
index 9e411ed51a..0000000000
--- a/ruby_1_9_3/lib/rake/ruby182_test_unit_fix.rb
+++ /dev/null
@@ -1,25 +0,0 @@
-# Local Rake override to fix bug in Ruby 0.8.2
-module Test # :nodoc:
- # Local Rake override to fix bug in Ruby 0.8.2
- module Unit # :nodoc:
- # Local Rake override to fix bug in Ruby 0.8.2
- module Collector # :nodoc:
- # Local Rake override to fix bug in Ruby 0.8.2
- class Dir # :nodoc:
- undef collect_file
- def collect_file(name, suites, already_gathered) # :nodoc:
- dir = File.dirname(File.expand_path(name))
- $:.unshift(dir) unless $:.first == 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)
- end
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rake/rule_recursion_overflow_error.rb b/ruby_1_9_3/lib/rake/rule_recursion_overflow_error.rb
deleted file mode 100644
index da4318da9d..0000000000
--- a/ruby_1_9_3/lib/rake/rule_recursion_overflow_error.rb
+++ /dev/null
@@ -1,20 +0,0 @@
-
-module Rake
-
- # Error indicating a recursion overflow error in task selection.
- class RuleRecursionOverflowError < StandardError
- def initialize(*args)
- super
- @targets = []
- end
-
- def add_target(target)
- @targets << target
- end
-
- def message
- super + ": [" + @targets.reverse.join(' => ') + "]"
- end
- end
-
-end
diff --git a/ruby_1_9_3/lib/rake/runtest.rb b/ruby_1_9_3/lib/rake/runtest.rb
deleted file mode 100644
index 2b98a60cae..0000000000
--- a/ruby_1_9_3/lib/rake/runtest.rb
+++ /dev/null
@@ -1,21 +0,0 @@
-require 'test/unit'
-require 'test/unit/assertions'
-
-module Rake
- include Test::Unit::Assertions
-
- def run_tests(pattern='test/test*.rb', log_enabled=false)
- Dir["#{pattern}"].each { |fn|
- $stderr.puts fn if log_enabled
- begin
- require fn
- rescue Exception => ex
- $stderr.puts "Error in #{fn}: #{ex.message}"
- $stderr.puts ex.backtrace
- assert false
- end
- }
- end
-
- extend self
-end
diff --git a/ruby_1_9_3/lib/rake/task.rb b/ruby_1_9_3/lib/rake/task.rb
deleted file mode 100644
index f977d18711..0000000000
--- a/ruby_1_9_3/lib/rake/task.rb
+++ /dev/null
@@ -1,327 +0,0 @@
-require 'rake/invocation_exception_mixin'
-
-module Rake
-
- # #########################################################################
- # A Task is the basic unit of work in a Rakefile. Tasks have associated
- # actions (possibly more than one) and a list of prerequisites. When
- # invoked, a task will first ensure that all of its prerequisites have an
- # opportunity to run and then it will execute its own actions.
- #
- # Tasks are not usually created directly using the new method, but rather
- # use the +file+ and +task+ convenience methods.
- #
- class Task
- # List of prerequisites for a task.
- attr_reader :prerequisites
-
- # List of actions attached to a task.
- attr_reader :actions
-
- # Application owning this task.
- attr_accessor :application
-
- # Comment for this task. Restricted to a single line of no more than 50
- # characters.
- attr_reader :comment
-
- # Full text of the (possibly multi-line) comment.
- attr_reader :full_comment
-
- # Array of nested namespaces names used for task lookup by this task.
- attr_reader :scope
-
- # File/Line locations of each of the task definitions for this
- # task (only valid if the task was defined with the detect
- # location option set).
- attr_reader :locations
-
- # Return task name
- def to_s
- name
- end
-
- def inspect
- "<#{self.class} #{name} => [#{prerequisites.join(', ')}]>"
- end
-
- # List of sources for task.
- attr_writer :sources
- def sources
- @sources ||= []
- end
-
- # List of prerequisite tasks
- def prerequisite_tasks
- prerequisites.collect { |pre| lookup_prerequisite(pre) }
- end
-
- def lookup_prerequisite(prerequisite_name)
- application[prerequisite_name, @scope]
- end
- private :lookup_prerequisite
-
- # First source from a rule (nil if no sources)
- def source
- @sources.first if defined?(@sources)
- end
-
- # Create a task named +task_name+ with no actions or prerequisites. Use
- # +enhance+ to add actions and prerequisites.
- def initialize(task_name, app)
- @name = task_name.to_s
- @prerequisites = []
- @actions = []
- @already_invoked = false
- @full_comment = nil
- @comment = nil
- @lock = Monitor.new
- @application = app
- @scope = app.current_scope
- @arg_names = nil
- @locations = []
- end
-
- # Enhance a task with prerequisites or actions. Returns self.
- def enhance(deps=nil, &block)
- @prerequisites |= deps if deps
- @actions << block if block_given?
- self
- end
-
- # Name of the task, including any namespace qualifiers.
- def name
- @name.to_s
- end
-
- # Name of task with argument list description.
- def name_with_args # :nodoc:
- if arg_description
- "#{name}#{arg_description}"
- else
- name
- end
- end
-
- # Argument description (nil if none).
- def arg_description # :nodoc:
- @arg_names ? "[#{(arg_names || []).join(',')}]" : nil
- end
-
- # Name of arguments for this task.
- def arg_names
- @arg_names || []
- end
-
- # Reenable the task, allowing its tasks to be executed if the task
- # is invoked again.
- def reenable
- @already_invoked = false
- end
-
- # Clear the existing prerequisites and actions of a rake task.
- def clear
- clear_prerequisites
- clear_actions
- self
- end
-
- # Clear the existing prerequisites of a rake task.
- def clear_prerequisites
- prerequisites.clear
- self
- end
-
- # Clear the existing actions on a rake task.
- def clear_actions
- actions.clear
- self
- end
-
- # Invoke the task if it is needed. Prerequisites are invoked first.
- def invoke(*args)
- task_args = TaskArguments.new(arg_names, args)
- invoke_with_call_chain(task_args, InvocationChain::EMPTY)
- end
-
- # Same as invoke, but explicitly pass a call chain to detect
- # circular dependencies.
- def invoke_with_call_chain(task_args, invocation_chain) # :nodoc:
- new_chain = InvocationChain.append(self, invocation_chain)
- @lock.synchronize do
- if application.options.trace
- $stderr.puts "** Invoke #{name} #{format_trace_flags}"
- end
- return if @already_invoked
- @already_invoked = true
- invoke_prerequisites(task_args, new_chain)
- execute(task_args) if needed?
- end
- rescue Exception => ex
- add_chain_to(ex, new_chain)
- raise ex
- end
- protected :invoke_with_call_chain
-
- def add_chain_to(exception, new_chain)
- exception.extend(InvocationExceptionMixin) unless exception.respond_to?(:chain)
- exception.chain = new_chain if exception.chain.nil?
- end
- private :add_chain_to
-
- # Invoke all the prerequisites of a task.
- def invoke_prerequisites(task_args, invocation_chain) # :nodoc:
- prerequisite_tasks.each { |prereq|
- prereq_args = task_args.new_scope(prereq.arg_names)
- prereq.invoke_with_call_chain(prereq_args, invocation_chain)
- }
- end
-
- # Format the trace flags for display.
- def format_trace_flags
- flags = []
- flags << "first_time" unless @already_invoked
- flags << "not_needed" unless needed?
- flags.empty? ? "" : "(" + flags.join(", ") + ")"
- end
- private :format_trace_flags
-
- # Execute the actions associated with this task.
- def execute(args=nil)
- args ||= EMPTY_TASK_ARGS
- if application.options.dryrun
- $stderr.puts "** Execute (dry run) #{name}"
- return
- end
- if application.options.trace
- $stderr.puts "** Execute #{name}"
- end
- application.enhance_with_matching_rule(name) if @actions.empty?
- @actions.each do |act|
- case act.arity
- when 1
- act.call(self)
- else
- act.call(self, args)
- end
- end
- end
-
- # Is this task needed?
- def needed?
- true
- end
-
- # Timestamp for this task. Basic tasks return the current time for their
- # time stamp. Other tasks can be more sophisticated.
- def timestamp
- prerequisite_tasks.collect { |pre| pre.timestamp }.max || Time.now
- end
-
- # Add a description to the task. The description can consist of an option
- # argument list (enclosed brackets) and an optional comment.
- def add_description(description)
- return if ! description
- comment = description.strip
- add_comment(comment) if comment && ! comment.empty?
- end
-
- # Writing to the comment attribute is the same as adding a description.
- def comment=(description)
- add_description(description)
- end
-
- # Add a comment to the task. If a comment already exists, separate
- # the new comment with " / ".
- def add_comment(comment)
- if @full_comment
- @full_comment << " / "
- else
- @full_comment = ''
- end
- @full_comment << comment
- if @full_comment =~ /\A([^.]+?\.)( |$)/
- @comment = $1
- else
- @comment = @full_comment
- end
- end
- private :add_comment
-
- # Set the names of the arguments for this task. +args+ should be
- # an array of symbols, one for each argument name.
- def set_arg_names(args)
- @arg_names = args.map { |a| a.to_sym }
- end
-
- # Return a string describing the internal state of a task. Useful for
- # debugging.
- def investigation
- result = "------------------------------\n"
- result << "Investigating #{name}\n"
- result << "class: #{self.class}\n"
- result << "task needed: #{needed?}\n"
- result << "timestamp: #{timestamp}\n"
- result << "pre-requisites: \n"
- prereqs = prerequisite_tasks
- prereqs.sort! {|a,b| a.timestamp <=> b.timestamp}
- prereqs.each do |p|
- result << "--#{p.name} (#{p.timestamp})\n"
- end
- latest_prereq = prerequisite_tasks.collect { |pre| pre.timestamp }.max
- result << "latest-prerequisite time: #{latest_prereq}\n"
- result << "................................\n\n"
- return result
- end
-
- # ----------------------------------------------------------------
- # Rake Module Methods
- #
- class << self
-
- # Clear the task list. This cause rake to immediately forget all the
- # tasks that have been assigned. (Normally used in the unit tests.)
- def clear
- Rake.application.clear
- end
-
- # List of all defined tasks.
- def tasks
- Rake.application.tasks
- end
-
- # Return a task with the given name. If the task is not currently
- # known, try to synthesize one from the defined rules. If no rules are
- # found, but an existing file matches the task name, assume it is a file
- # task with no dependencies or actions.
- def [](task_name)
- Rake.application[task_name]
- end
-
- # TRUE if the task name is already defined.
- def task_defined?(task_name)
- Rake.application.lookup(task_name) != nil
- end
-
- # Define a task given +args+ and an option block. If a rule with the
- # given name already exists, the prerequisites and actions are added to
- # the existing task. Returns the defined task.
- def define_task(*args, &block)
- Rake.application.define_task(self, *args, &block)
- end
-
- # Define a rule for synthesizing tasks.
- def create_rule(*args, &block)
- Rake.application.create_rule(*args, &block)
- end
-
- # Apply the scope to the task name according to the rules for
- # this kind of task. Generic tasks will accept the scope as
- # part of the name.
- def scope_name(scope, task_name)
- (scope + [task_name]).join(':')
- end
-
- end # class << Rake::Task
- end # class Rake::Task
-end
diff --git a/ruby_1_9_3/lib/rake/task_argument_error.rb b/ruby_1_9_3/lib/rake/task_argument_error.rb
deleted file mode 100644
index 3e1dda64db..0000000000
--- a/ruby_1_9_3/lib/rake/task_argument_error.rb
+++ /dev/null
@@ -1,7 +0,0 @@
-module Rake
-
- # Error indicating an ill-formed task declaration.
- class TaskArgumentError < ArgumentError
- end
-
-end
diff --git a/ruby_1_9_3/lib/rake/task_arguments.rb b/ruby_1_9_3/lib/rake/task_arguments.rb
deleted file mode 100644
index 02d01b99f9..0000000000
--- a/ruby_1_9_3/lib/rake/task_arguments.rb
+++ /dev/null
@@ -1,78 +0,0 @@
-module Rake
-
- ####################################################################
- # TaskArguments manage the arguments passed to a task.
- #
- class TaskArguments
- include Enumerable
-
- attr_reader :names
-
- # Create a TaskArgument object with a list of named arguments
- # (given by :names) and a set of associated values (given by
- # :values). :parent is the parent argument object.
- def initialize(names, values, parent=nil)
- @names = names
- @parent = parent
- @hash = {}
- names.each_with_index { |name, i|
- @hash[name.to_sym] = values[i] unless values[i].nil?
- }
- end
-
- # Create a new argument scope using the prerequisite argument
- # names.
- def new_scope(names)
- values = names.collect { |n| self[n] }
- self.class.new(names, values, self)
- end
-
- # Find an argument value by name or index.
- def [](index)
- lookup(index.to_sym)
- end
-
- # Specify a hash of default values for task arguments. Use the
- # defaults only if there is no specific value for the given
- # argument.
- def with_defaults(defaults)
- @hash = defaults.merge(@hash)
- end
-
- def each(&block)
- @hash.each(&block)
- end
-
- def values_at(*keys)
- keys.map { |k| lookup(k) }
- end
-
- def method_missing(sym, *args, &block)
- lookup(sym.to_sym)
- end
-
- def to_hash
- @hash
- end
-
- def to_s
- @hash.inspect
- end
-
- def inspect
- to_s
- end
-
- protected
-
- def lookup(name)
- if @hash.has_key?(name)
- @hash[name]
- elsif @parent
- @parent.lookup(name)
- end
- end
- end
-
- EMPTY_TASK_ARGS = TaskArguments.new([], [])
-end
diff --git a/ruby_1_9_3/lib/rake/task_manager.rb b/ruby_1_9_3/lib/rake/task_manager.rb
deleted file mode 100644
index 4c3c26aa3a..0000000000
--- a/ruby_1_9_3/lib/rake/task_manager.rb
+++ /dev/null
@@ -1,307 +0,0 @@
-module Rake
-
- # The TaskManager module is a mixin for managing tasks.
- module TaskManager
- # Track the last comment made in the Rakefile.
- attr_accessor :last_description
- alias :last_comment :last_description # Backwards compatibility
-
- def initialize
- super
- @tasks = Hash.new
- @rules = Array.new
- @scope = Array.new
- @last_description = nil
- end
-
- def create_rule(*args, &block)
- pattern, _, deps = resolve_args(args)
- pattern = Regexp.new(Regexp.quote(pattern) + '$') if String === pattern
- @rules << [pattern, deps, block]
- end
-
- def define_task(task_class, *args, &block)
- task_name, arg_names, deps = resolve_args(args)
- task_name = task_class.scope_name(@scope, task_name)
- deps = [deps] unless deps.respond_to?(:to_ary)
- deps = deps.collect {|d| d.to_s }
- task = intern(task_class, task_name)
- task.set_arg_names(arg_names) unless arg_names.empty?
- if Rake::TaskManager.record_task_metadata
- add_location(task)
- task.add_description(get_description(task))
- end
- task.enhance(deps, &block)
- end
-
- # Lookup a task. Return an existing task if found, otherwise
- # create a task of the current type.
- def intern(task_class, task_name)
- @tasks[task_name.to_s] ||= task_class.new(task_name, self)
- end
-
- # Find a matching task for +task_name+.
- def [](task_name, scopes=nil)
- task_name = task_name.to_s
- self.lookup(task_name, scopes) or
- enhance_with_matching_rule(task_name) or
- synthesize_file_task(task_name) or
- fail "Don't know how to build task '#{task_name}'"
- end
-
- def synthesize_file_task(task_name)
- return nil unless File.exist?(task_name)
- define_task(Rake::FileTask, task_name)
- end
-
- # Resolve the arguments for a task/rule. Returns a triplet of
- # [task_name, arg_name_list, prerequisites].
- def resolve_args(args)
- if args.last.is_a?(Hash)
- deps = args.pop
- resolve_args_with_dependencies(args, deps)
- else
- resolve_args_without_dependencies(args)
- end
- end
-
- # Resolve task arguments for a task or rule when there are no
- # dependencies declared.
- #
- # The patterns recognized by this argument resolving function are:
- #
- # task :t
- # task :t, [:a]
- # task :t, :a (deprecated)
- #
- def resolve_args_without_dependencies(args)
- task_name = args.shift
- if args.size == 1 && args.first.respond_to?(:to_ary)
- arg_names = args.first.to_ary
- else
- arg_names = args
- end
- [task_name, arg_names, []]
- end
- private :resolve_args_without_dependencies
-
- # Resolve task arguments for a task or rule when there are
- # dependencies declared.
- #
- # The patterns recognized by this argument resolving function are:
- #
- # task :t => [:d]
- # task :t, [a] => [:d]
- # task :t, :needs => [:d] (deprecated)
- # task :t, :a, :needs => [:d] (deprecated)
- #
- def resolve_args_with_dependencies(args, hash) # :nodoc:
- fail "Task Argument Error" if hash.size != 1
- key, value = hash.map { |k, v| [k,v] }.first
- if args.empty?
- task_name = key
- arg_names = []
- deps = value
- elsif key == :needs
- Rake.application.deprecate(
- "task :t, arg, :needs => [deps]",
- "task :t, [args] => [deps]",
- caller.detect { |c| c !~ /\blib\/rake\b/ })
- task_name = args.shift
- arg_names = args
- deps = value
- else
- task_name = args.shift
- arg_names = key
- deps = value
- end
- deps = [deps] unless deps.respond_to?(:to_ary)
- [task_name, arg_names, deps]
- end
- private :resolve_args_with_dependencies
-
- # If a rule can be found that matches the task name, enhance the
- # task with the prerequisites and actions from the rule. Set the
- # source attribute of the task appropriately for the rule. Return
- # the enhanced task or nil of no rule was found.
- def enhance_with_matching_rule(task_name, level=0)
- fail Rake::RuleRecursionOverflowError,
- "Rule Recursion Too Deep" if level >= 16
- @rules.each do |pattern, extensions, block|
- if pattern.match(task_name)
- task = attempt_rule(task_name, extensions, block, level)
- return task if task
- end
- end
- nil
- rescue Rake::RuleRecursionOverflowError => ex
- ex.add_target(task_name)
- fail ex
- end
-
- # List of all defined tasks in this application.
- def tasks
- @tasks.values.sort_by { |t| t.name }
- end
-
- # List of all the tasks defined in the given scope (and its
- # sub-scopes).
- def tasks_in_scope(scope)
- prefix = scope.join(":")
- tasks.select { |t|
- /^#{prefix}:/ =~ t.name
- }
- end
-
- # Clear all tasks in this application.
- def clear
- @tasks.clear
- @rules.clear
- end
-
- # Lookup a task, using scope and the scope hints in the task name.
- # This method performs straight lookups without trying to
- # synthesize file tasks or rules. Special scope names (e.g. '^')
- # are recognized. If no scope argument is supplied, use the
- # current scope. Return nil if the task cannot be found.
- def lookup(task_name, initial_scope=nil)
- initial_scope ||= @scope
- task_name = task_name.to_s
- if task_name =~ /^rake:/
- scopes = []
- task_name = task_name.sub(/^rake:/, '')
- elsif task_name =~ /^(\^+)/
- scopes = initial_scope[0, initial_scope.size - $1.size]
- task_name = task_name.sub(/^(\^+)/, '')
- else
- scopes = initial_scope
- end
- lookup_in_scope(task_name, scopes)
- end
-
- # Lookup the task name
- def lookup_in_scope(name, scope)
- n = scope.size
- while n >= 0
- tn = (scope[0,n] + [name]).join(':')
- task = @tasks[tn]
- return task if task
- n -= 1
- end
- nil
- end
- private :lookup_in_scope
-
- # Return the list of scope names currently active in the task
- # manager.
- def current_scope
- @scope.dup
- end
-
- # Evaluate the block in a nested namespace named +name+. Create
- # an anonymous namespace if +name+ is nil.
- def in_namespace(name)
- name ||= generate_name
- @scope.push(name)
- ns = NameSpace.new(self, @scope)
- yield(ns)
- ns
- ensure
- @scope.pop
- end
-
- private
-
- # Add a location to the locations field of the given task.
- def add_location(task)
- loc = find_location
- task.locations << loc if loc
- task
- end
-
- # Find the location that called into the dsl layer.
- def find_location
- locations = caller
- i = 0
- while locations[i]
- return locations[i+1] if locations[i] =~ /rake\/dsl_definition.rb/
- i += 1
- end
- nil
- end
-
- # Generate an anonymous namespace name.
- def generate_name
- @seed ||= 0
- @seed += 1
- "_anon_#{@seed}"
- end
-
- def trace_rule(level, message)
- $stderr.puts "#{" "*level}#{message}" if Rake.application.options.trace_rules
- end
-
- # Attempt to create a rule given the list of prerequisites.
- def attempt_rule(task_name, extensions, block, level)
- sources = make_sources(task_name, extensions)
- prereqs = sources.collect { |source|
- trace_rule level, "Attempting Rule #{task_name} => #{source}"
- if File.exist?(source) || Rake::Task.task_defined?(source)
- trace_rule level, "(#{task_name} => #{source} ... EXIST)"
- source
- elsif parent = enhance_with_matching_rule(source, level+1)
- trace_rule level, "(#{task_name} => #{source} ... ENHANCE)"
- parent.name
- else
- trace_rule level, "(#{task_name} => #{source} ... FAIL)"
- return nil
- end
- }
- task = FileTask.define_task({task_name => prereqs}, &block)
- task.sources = prereqs
- task
- end
-
- # Make a list of sources from the list of file name extensions /
- # translation procs.
- def make_sources(task_name, extensions)
- result = extensions.collect { |ext|
- case ext
- when /%/
- task_name.pathmap(ext)
- when %r{/}
- ext
- when /^\./
- task_name.ext(ext)
- when String
- ext
- when Proc
- if ext.arity == 1
- ext.call(task_name)
- else
- ext.call
- end
- else
- fail "Don't know how to handle rule dependent: #{ext.inspect}"
- end
- }
- result.flatten
- end
-
-
- private
-
- # Return the current description, clearing it in the process.
- def get_description(task)
- desc = @last_description
- @last_description = nil
- desc
- end
-
- class << self
- attr_accessor :record_task_metadata
- TaskManager.record_task_metadata = false
- end
- end
-
-end
diff --git a/ruby_1_9_3/lib/rake/tasklib.rb b/ruby_1_9_3/lib/rake/tasklib.rb
deleted file mode 100644
index f1e17dad31..0000000000
--- a/ruby_1_9_3/lib/rake/tasklib.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-require 'rake'
-
-module Rake
-
- # Base class for Task Libraries.
- class TaskLib
- include Cloneable
- include Rake::DSL
-
- # Make a symbol by pasting two strings together.
- #
- # NOTE: DEPRECATED! This method is kinda stupid. I don't know why
- # I didn't just use string interpolation. But now other task
- # libraries depend on this so I can't remove it without breaking
- # other people's code. So for now it stays for backwards
- # compatibility. BUT DON'T USE IT.
- def paste(a,b) # :nodoc:
- (a.to_s + b.to_s).intern
- end
- end
-
-end
diff --git a/ruby_1_9_3/lib/rake/testtask.rb b/ruby_1_9_3/lib/rake/testtask.rb
deleted file mode 100644
index 04d3ae473a..0000000000
--- a/ruby_1_9_3/lib/rake/testtask.rb
+++ /dev/null
@@ -1,191 +0,0 @@
-# Define a task library for running unit tests.
-
-require 'rake'
-require 'rake/tasklib'
-
-module Rake
-
- # Create a task that runs a set of tests.
- #
- # Example:
- #
- # Rake::TestTask.new do |t|
- # t.libs << "test"
- # t.test_files = FileList['test/test*.rb']
- # t.verbose = true
- # end
- #
- # If rake is invoked with a "TEST=filename" command line option,
- # then the list of test files will be overridden to include only the
- # filename specified on the command line. This provides an easy way
- # to run just one test.
- #
- # If rake is invoked with a "TESTOPTS=options" command line option,
- # then the given options are passed to the test process after a
- # '--'. This allows Test::Unit options to be passed to the test
- # suite.
- #
- # Examples:
- #
- # rake test # run tests normally
- # rake test TEST=just_one_file.rb # run just one test file.
- # rake test TESTOPTS="-v" # run in verbose mode
- # rake test TESTOPTS="--runner=fox" # use the fox test runner
- #
- class TestTask < TaskLib
-
- # Name of test task. (default is :test)
- attr_accessor :name
-
- # List of directories to added to $LOAD_PATH before running the
- # tests. (default is 'lib')
- attr_accessor :libs
-
- # True if verbose test output desired. (default is false)
- attr_accessor :verbose
-
- # Test options passed to the test suite. An explicit
- # TESTOPTS=opts on the command line will override this. (default
- # is NONE)
- attr_accessor :options
-
- # Request that the tests be run with the warning flag set.
- # E.g. warning=true implies "ruby -w" used to run the tests.
- attr_accessor :warning
-
- # Glob pattern to match test files. (default is 'test/test*.rb')
- attr_accessor :pattern
-
- # Style of test loader to use. Options are:
- #
- # * :rake -- Rake provided test loading script (default).
- # * :testrb -- Ruby provided test loading script.
- # * :direct -- Load tests using command line loader.
- #
- attr_accessor :loader
-
- # Array of commandline options to pass to ruby when running test loader.
- attr_accessor :ruby_opts
-
- # Explicitly define the list of test files to be included in a
- # test. +list+ is expected to be an array of file names (a
- # FileList is acceptable). If both +pattern+ and +test_files+ are
- # used, then the list of test files is the union of the two.
- def test_files=(list)
- @test_files = list
- end
-
- # Create a testing task.
- def initialize(name=:test)
- @name = name
- @libs = ["lib"]
- @pattern = nil
- @options = nil
- @test_files = nil
- @verbose = false
- @warning = false
- @loader = :rake
- @ruby_opts = []
- yield self if block_given?
- @pattern = 'test/test*.rb' if @pattern.nil? && @test_files.nil?
- define
- end
-
- # Create the tasks defined by this task lib.
- def define
- desc "Run tests" + (@name==:test ? "" : " for #{@name}")
- task @name do
- FileUtilsExt.verbose(@verbose) do
- ruby "#{ruby_opts_string} #{run_code} #{file_list_string} #{option_list}"
- end
- end
- self
- end
-
- def option_list # :nodoc:
- (ENV['TESTOPTS'] ||
- ENV['TESTOPT'] ||
- ENV['TEST_OPTS'] ||
- ENV['TEST_OPT'] ||
- @options ||
- "")
- end
-
- def ruby_opts_string
- opts = @ruby_opts.dup
- opts.unshift( "-I\"#{lib_path}\"" ) unless @libs.empty?
- opts.unshift( "-w" ) if @warning
- opts.join(" ")
- end
-
- def lib_path
- @libs.join(File::PATH_SEPARATOR)
- end
-
- def file_list_string
- file_list.collect { |fn| "\"#{fn}\"" }.join(' ')
- end
-
- def file_list # :nodoc:
- if ENV['TEST']
- FileList[ ENV['TEST'] ]
- else
- result = []
- result += @test_files.to_a if @test_files
- result << @pattern if @pattern
- result
- end
- end
-
- def fix # :nodoc:
- case ruby_version
- when '1.8.2'
- "\"#{find_file 'rake/ruby182_test_unit_fix'}\""
- else
- nil
- end || ''
- end
-
- def ruby_version
- RUBY_VERSION
- end
-
- def run_code
- case @loader
- when :direct
- "-e \"ARGV.each{|f| require f}\""
- when :testrb
- "-S testrb #{fix}"
- when :rake
- "-I\"#{rake_lib_dir}\" \"#{rake_loader}\""
- end
- end
-
- def rake_loader # :nodoc:
- find_file('rake/rake_test_loader') or
- fail "unable to find rake test loader"
- end
-
- def find_file(fn) # :nodoc:
- $LOAD_PATH.each do |path|
- file_path = File.join(path, "#{fn}.rb")
- return file_path if File.exist? file_path
- end
- nil
- end
-
- def rake_lib_dir # :nodoc:
- find_dir('rake') or
- fail "unable to find rake lib"
- end
-
- def find_dir(fn) # :nodoc:
- $LOAD_PATH.each do |path|
- file_path = File.join(path, "#{fn}.rb")
- return path if File.exist? file_path
- end
- nil
- end
-
- end
-end
diff --git a/ruby_1_9_3/lib/rake/version.rb b/ruby_1_9_3/lib/rake/version.rb
deleted file mode 100644
index 6c43493df9..0000000000
--- a/ruby_1_9_3/lib/rake/version.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-module Rake
- VERSION = '0.9.2.2'
-
- module Version # :nodoc: all
- MAJOR, MINOR, BUILD = VERSION.split '.'
- NUMBERS = [ MAJOR, MINOR, BUILD ]
- end
-end
diff --git a/ruby_1_9_3/lib/rake/win32.rb b/ruby_1_9_3/lib/rake/win32.rb
deleted file mode 100644
index 98289a10b4..0000000000
--- a/ruby_1_9_3/lib/rake/win32.rb
+++ /dev/null
@@ -1,55 +0,0 @@
-
-module Rake
- require 'rake/alt_system'
-
- # Win 32 interface methods for Rake. Windows specific functionality
- # will be placed here to collect that knowledge in one spot.
- module Win32
-
- # Error indicating a problem in locating the home directory on a
- # Win32 system.
- class Win32HomeError < RuntimeError
- end
-
- class << self
- # True if running on a windows system.
- def windows?
- AltSystem::WINDOWS
- end
-
- # Run a command line on windows.
- def rake_system(*cmd)
- AltSystem.system(*cmd)
- end
-
- # The standard directory containing system wide rake files on
- # Win 32 systems. Try the following environment variables (in
- # order):
- #
- # * HOME
- # * HOMEDRIVE + HOMEPATH
- # * APPDATA
- # * USERPROFILE
- #
- # If the above are not defined, the return nil.
- def win32_system_dir #:nodoc:
- win32_shared_path = ENV['HOME']
- if win32_shared_path.nil? && ENV['HOMEDRIVE'] && ENV['HOMEPATH']
- win32_shared_path = ENV['HOMEDRIVE'] + ENV['HOMEPATH']
- end
-
- win32_shared_path ||= ENV['APPDATA']
- win32_shared_path ||= ENV['USERPROFILE']
- raise Win32HomeError, "Unable to determine home path environment variable." if
- win32_shared_path.nil? or win32_shared_path.empty?
- normalize(File.join(win32_shared_path, 'Rake'))
- end
-
- # Normalize a win32 path so that the slashes are all forward slashes.
- def normalize(path)
- path.gsub(/\\/, '/')
- end
-
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rational.rb b/ruby_1_9_3/lib/rational.rb
deleted file mode 100644
index a1aeca1e40..0000000000
--- a/ruby_1_9_3/lib/rational.rb
+++ /dev/null
@@ -1,23 +0,0 @@
-# :enddoc:
-
-warn('lib/rational.rb is deprecated') if $VERBOSE
-
-class Fixnum
-
- alias quof fdiv
- alias rdiv quo
-
- alias power! ** unless method_defined? :power!
- alias rpower **
-
-end
-
-class Bignum
-
- alias quof fdiv
- alias rdiv quo
-
- alias power! ** unless method_defined? :power!
- alias rpower **
-
-end
diff --git a/ruby_1_9_3/lib/rbconfig/.document b/ruby_1_9_3/lib/rbconfig/.document
deleted file mode 100644
index 4cea83cd0e..0000000000
--- a/ruby_1_9_3/lib/rbconfig/.document
+++ /dev/null
@@ -1 +0,0 @@
-# these files are obsolete
diff --git a/ruby_1_9_3/lib/rbconfig/datadir.rb b/ruby_1_9_3/lib/rbconfig/datadir.rb
deleted file mode 100644
index 9b7eabb473..0000000000
--- a/ruby_1_9_3/lib/rbconfig/datadir.rb
+++ /dev/null
@@ -1,13 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-# N.B. This file is used by Config.datadir in rubygems.rb, and must not be
-# removed before that require is removed. I require to avoid warning more than
-# once.
-
-warn 'rbconfig/datadir.rb and {Rb}Config.datadir is being deprecated from '\
- 'RubyGems. It will be removed completely on or after June 2011. If you '\
- 'wish to rely on a datadir, please use Gem.datadir.'
diff --git a/ruby_1_9_3/lib/rbconfig/obsolete.rb b/ruby_1_9_3/lib/rbconfig/obsolete.rb
deleted file mode 100644
index eae9155af6..0000000000
--- a/ruby_1_9_3/lib/rbconfig/obsolete.rb
+++ /dev/null
@@ -1,5 +0,0 @@
-loc = caller[0]
-loc = loc[/\A.*:\d+:/] if loc
-loc = "#{loc} " if loc
-warn "#{loc}Use RbConfig instead of obsolete and deprecated Config."
-Config = RbConfig # compatibility for ruby-1.8.4 and older.
diff --git a/ruby_1_9_3/lib/rdoc.rb b/ruby_1_9_3/lib/rdoc.rb
deleted file mode 100644
index 50f3f542ee..0000000000
--- a/ruby_1_9_3/lib/rdoc.rb
+++ /dev/null
@@ -1,147 +0,0 @@
-$DEBUG_RDOC = nil
-
-# :main: README.txt
-
-##
-# RDoc is a Ruby documentation system which contains RDoc::RDoc for generating
-# documentation, RDoc::RI for interactive documentation and RDoc::Markup for
-# text markup.
-#
-# RDoc::RDoc produces documentation for Ruby source files. It works similarly
-# to JavaDoc, parsing the source and extracting the definition for classes,
-# modules, methods, includes and requires. It associates these with optional
-# documentation contained in an immediately preceding comment block then
-# renders the result using an output formatter.
-#
-# RDoc::Markup that converts plain text into various output formats. The
-# markup library is used to interpret the comment blocks that RDoc uses to
-# document methods, classes, and so on.
-#
-# RDoc::RI implements the +ri+ command-line tool which displays on-line
-# documentation for ruby classes, methods, etc. +ri+ features several output
-# formats and an interactive mode (<tt>ri -i</tt>). See <tt>ri --help</tt>
-# for further details.
-#
-# == Roadmap
-#
-# * If you want to use RDoc to create documentation for your Ruby source files,
-# see RDoc::Markup and refer to <tt>rdoc --help</tt> for command line
-# usage.
-# * If you want to write documentation for Ruby files see RDoc::Parser::Ruby
-# * If you want to write documentation for extensions written in C see
-# RDoc::Parser::C
-# * If you want to generate documentation using <tt>rake</tt> see RDoc::Task.
-# * If you want to drive RDoc programmatically, see RDoc::RDoc.
-# * If you want to use the library to format text blocks into HTML, look at
-# RDoc::Markup.
-# * If you want to make an RDoc plugin such as a generator or directive
-# handler see RDoc::RDoc.
-# * If you want to write your own output generator see RDoc::Generator.
-#
-# == Summary
-#
-# Once installed, you can create documentation using the +rdoc+ command
-#
-# % rdoc [options] [names...]
-#
-# For an up-to-date option summary, type
-#
-# % rdoc --help
-#
-# A typical use might be to generate documentation for a package of Ruby
-# source (such as RDoc itself).
-#
-# % rdoc
-#
-# This command generates documentation for all the Ruby and C source
-# files in and below the current directory. These will be stored in a
-# documentation tree starting in the subdirectory +doc+.
-#
-# You can make this slightly more useful for your readers by having the
-# index page contain the documentation for the primary file. In our
-# case, we could type
-#
-# % rdoc --main README.txt
-#
-# You'll find information on the various formatting tricks you can use
-# in comment blocks in the documentation this generates.
-#
-# RDoc uses file extensions to determine how to process each file. File names
-# ending +.rb+ and +.rbw+ are assumed to be Ruby source. Files
-# ending +.c+ are parsed as C files. All other files are assumed to
-# contain just Markup-style markup (with or without leading '#' comment
-# markers). If directory names are passed to RDoc, they are scanned
-# recursively for C and Ruby source files only.
-#
-# == Other stuff
-#
-# RDoc is currently being maintained by Eric Hodel <drbrain@segment7.net>.
-#
-# Dave Thomas <dave@pragmaticprogrammer.com> is the original author of RDoc.
-#
-# == Credits
-#
-# * The Ruby parser in rdoc/parse.rb is based heavily on the outstanding
-# work of Keiju ISHITSUKA of Nippon Rational Inc, who produced the Ruby
-# parser for irb and the rtags package.
-
-module RDoc
-
- ##
- # Exception thrown by any rdoc error.
-
- class Error < RuntimeError; end
-
- def self.const_missing const_name # :nodoc:
- if const_name.to_s == 'RDocError' then
- warn "RDoc::RDocError is deprecated"
- return Error
- end
-
- super
- end
-
- ##
- # RDoc version you are using
-
- VERSION = '3.9.5'
-
- ##
- # Method visibilities
-
- VISIBILITIES = [:public, :protected, :private]
-
- ##
- # Name of the dotfile that contains the description of files to be processed
- # in the current directory
-
- DOT_DOC_FILENAME = ".document"
-
- ##
- # General RDoc modifiers
-
- GENERAL_MODIFIERS = %w[nodoc].freeze
-
- ##
- # RDoc modifiers for classes
-
- CLASS_MODIFIERS = GENERAL_MODIFIERS
-
- ##
- # RDoc modifiers for attributes
-
- ATTR_MODIFIERS = GENERAL_MODIFIERS
-
- ##
- # RDoc modifiers for constants
-
- CONSTANT_MODIFIERS = GENERAL_MODIFIERS
-
- ##
- # RDoc modifiers for methods
-
- METHOD_MODIFIERS = GENERAL_MODIFIERS +
- %w[arg args yield yields notnew not-new not_new doc]
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/alias.rb b/ruby_1_9_3/lib/rdoc/alias.rb
deleted file mode 100644
index fa433dc0a9..0000000000
--- a/ruby_1_9_3/lib/rdoc/alias.rb
+++ /dev/null
@@ -1,113 +0,0 @@
-require 'rdoc/code_object'
-
-##
-# Represent an alias, which is an old_name/new_name pair associated with a
-# particular context
-#--
-# TODO implement Alias as a proxy to a method/attribute, inheriting from
-# MethodAttr
-
-class RDoc::Alias < RDoc::CodeObject
-
- ##
- # Aliased method's name
-
- attr_reader :new_name
-
- alias name new_name
-
- ##
- # Aliasee method's name
-
- attr_reader :old_name
-
- ##
- # Is this an alias declared in a singleton context?
-
- attr_accessor :singleton
-
- ##
- # Source file token stream
-
- attr_reader :text
-
- ##
- # Creates a new Alias with a token stream of +text+ that aliases +old_name+
- # to +new_name+, has +comment+ and is a +singleton+ context.
-
- def initialize(text, old_name, new_name, comment, singleton = false)
- super()
-
- @text = text
- @singleton = singleton
- @old_name = old_name
- @new_name = new_name
- self.comment = comment
- end
-
- ##
- # Order by #singleton then #new_name
-
- def <=>(other)
- [@singleton ? 0 : 1, new_name] <=> [other.singleton ? 0 : 1, other.new_name]
- end
-
- ##
- # HTML fragment reference for this alias
-
- def aref
- type = singleton ? 'c' : 'i'
- "#alias-#{type}-#{html_name}"
- end
-
- ##
- # Full old name including namespace
-
- def full_old_name
- @full_name || "#{parent.name}#{pretty_old_name}"
- end
-
- ##
- # HTML id-friendly version of +#new_name+.
-
- def html_name
- CGI.escape(@new_name.gsub('-', '-2D')).gsub('%','-').sub(/^-/, '')
- end
-
- def inspect # :nodoc:
- parent_name = parent ? parent.name : '(unknown)'
- "#<%s:0x%x %s.alias_method %s, %s>" % [
- self.class, object_id,
- parent_name, @old_name, @new_name,
- ]
- end
-
- ##
- # '::' for the alias of a singleton method/attribute, '#' for instance-level.
-
- def name_prefix
- singleton ? '::' : '#'
- end
-
- ##
- # Old name with prefix '::' or '#'.
-
- def pretty_old_name
- "#{singleton ? '::' : '#'}#{@old_name}"
- end
-
- ##
- # New name with prefix '::' or '#'.
-
- def pretty_new_name
- "#{singleton ? '::' : '#'}#{@new_name}"
- end
-
- alias pretty_name pretty_new_name
-
- def to_s # :nodoc:
- "alias: #{self.new_name} -> #{self.pretty_old_name} in: #{parent}"
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/anon_class.rb b/ruby_1_9_3/lib/rdoc/anon_class.rb
deleted file mode 100644
index 63c09e11f1..0000000000
--- a/ruby_1_9_3/lib/rdoc/anon_class.rb
+++ /dev/null
@@ -1,12 +0,0 @@
-require 'rdoc/class_module'
-
-##
-# An anonymous class like:
-#
-# c = Class.new do end
-#
-# AnonClass is currently not used.
-
-class RDoc::AnonClass < RDoc::ClassModule
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/any_method.rb b/ruby_1_9_3/lib/rdoc/any_method.rb
deleted file mode 100644
index c008edfe95..0000000000
--- a/ruby_1_9_3/lib/rdoc/any_method.rb
+++ /dev/null
@@ -1,207 +0,0 @@
-require 'rdoc/method_attr'
-require 'rdoc/token_stream'
-
-##
-# AnyMethod is the base class for objects representing methods
-
-class RDoc::AnyMethod < RDoc::MethodAttr
-
- MARSHAL_VERSION = 1 # :nodoc:
-
- ##
- # Don't rename \#initialize to \::new
-
- attr_accessor :dont_rename_initialize
-
- ##
- # The C function that implements this method (if it was defined in a C file)
-
- attr_accessor :c_function
-
- ##
- # Different ways to call this method
-
- attr_accessor :call_seq
-
- ##
- # Parameters for this method
-
- attr_accessor :params
-
- include RDoc::TokenStream
-
- ##
- # Creates a new AnyMethod with a token stream +text+ and +name+
-
- def initialize text, name
- super
-
- @c_function = nil
- @dont_rename_initialize = false
- @token_stream = nil
- end
-
- ##
- # Adds +an_alias+ as an alias for this method in +context+.
-
- def add_alias an_alias, context = nil
- method = self.class.new an_alias.text, an_alias.new_name
-
- method.record_location an_alias.file
- method.singleton = self.singleton
- method.params = self.params
- method.visibility = self.visibility
- method.comment = an_alias.comment
- method.is_alias_for = self
- @aliases << method
- context.add_method method if context
- method
- end
-
- ##
- # Prefix for +aref+ is 'method'.
-
- def aref_prefix
- 'method'
- end
-
- ##
- # The call_seq or the param_seq with method name, if there is no call_seq.
- #
- # Use this for displaying a method's argument lists.
-
- def arglists
- if @call_seq then
- @call_seq
- elsif @params then
- "#{name}#{param_seq}"
- end
- end
-
- ##
- # Dumps this AnyMethod for use by ri. See also #marshal_load
-
- def marshal_dump
- aliases = @aliases.map do |a|
- [a.name, parse(a.comment)]
- end
-
- [ MARSHAL_VERSION,
- @name,
- full_name,
- @singleton,
- @visibility,
- parse(@comment),
- @call_seq,
- @block_params,
- aliases,
- @params,
- @file.absolute_name,
- ]
- end
-
- ##
- # Loads this AnyMethod from +array+. For a loaded AnyMethod the following
- # methods will return cached values:
- #
- # * #full_name
- # * #parent_name
-
- def marshal_load(array)
- @dont_rename_initialize = nil
- @is_alias_for = nil
- @token_stream = nil
- @aliases = []
-
- version = array[0]
- @name = array[1]
- @full_name = array[2]
- @singleton = array[3]
- @visibility = array[4]
- @comment = array[5]
- @call_seq = array[6]
- @block_params = array[7]
-
- array[8].each do |new_name, comment|
- add_alias RDoc::Alias.new(nil, @name, new_name, comment, @singleton)
- end
-
- @params = array[9]
-
- @parent_name = if @full_name =~ /#/ then
- $`
- else
- name = @full_name.split('::')
- name.pop
- name.join '::'
- end
-
- @file = RDoc::TopLevel.new array[10] if version > 0
- end
-
- ##
- # Method name
- #
- # If the method has no assigned name, it extracts it from #call_seq.
-
- def name
- return @name if @name
-
- @name = @call_seq[/^.*?\.(\w+)/, 1] || @call_seq if @call_seq
- end
-
- ##
- # A list of this method's method and yield parameters. +call-seq+ params
- # are preferred over parsed method and block params.
-
- def param_list
- if @call_seq then
- params = @call_seq.split("\n").last
- params = params.sub(/.*?\((.*)\)/, '\1')
- params = params.sub(/(\{|do)\s*\|([^|]*)\|.*/, ',\2')
- elsif @params then
- params = @params.sub(/\((.*)\)/, '\1')
-
- params << ",#{@block_params}" if @block_params
- elsif @block_params then
- params = @block_params
- else
- return []
- end
-
- params.gsub(/\s+/, '').split ','
- end
-
- ##
- # Pretty parameter list for this method. If the method's parameters were
- # given by +call-seq+ it is preferred over the parsed values.
-
- def param_seq
- if @call_seq then
- params = @call_seq.split("\n").last
- params = params.sub(/[^( ]+/, '')
- params = params.sub(/(\|[^|]+\|)\s*\.\.\.\s*(end|\})/, '\1 \2')
- else
- params = @params.gsub(/\s*\#.*/, '')
- params = params.tr("\n", " ").squeeze(" ")
- params = "(#{params})" unless params[0] == ?(
- end
-
- if @block_params then
- # If this method has explicit block parameters, remove any explicit
- # &block
- params.sub!(/,?\s*&\w+/, '')
-
- block = @block_params.gsub(/\s*\#.*/, '')
- block = block.tr("\n", " ").squeeze(" ")
- if block[0] == ?(
- block.sub!(/^\(/, '').sub!(/\)/, '')
- end
- params << " { |#{block}| ... }"
- end
-
- params
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/attr.rb b/ruby_1_9_3/lib/rdoc/attr.rb
deleted file mode 100644
index 5d9bc17831..0000000000
--- a/ruby_1_9_3/lib/rdoc/attr.rb
+++ /dev/null
@@ -1,136 +0,0 @@
-require 'rdoc/method_attr'
-
-##
-# An attribute created by \#attr, \#attr_reader, \#attr_writer or
-# \#attr_accessor
-
-class RDoc::Attr < RDoc::MethodAttr
-
- MARSHAL_VERSION = 2 # :nodoc:
-
- ##
- # Is the attribute readable ('R'), writable ('W') or both ('RW')?
-
- attr_accessor :rw
-
- ##
- # Creates a new Attr with body +text+, +name+, read/write status +rw+ and
- # +comment+. +singleton+ marks this as a class attribute.
-
- def initialize(text, name, rw, comment, singleton = false)
- super text, name
-
- @rw = rw
- @singleton = singleton
- self.comment = comment
- end
-
- ##
- # Attributes are equal when their names, singleton and rw are identical
-
- def == other
- self.class == other.class and
- self.name == other.name and
- self.rw == other.rw and
- self.singleton == other.singleton
- end
-
- ##
- # Add +an_alias+ as an attribute in +context+.
-
- def add_alias(an_alias, context)
- new_attr = self.class.new(self.text, an_alias.new_name, self.rw,
- self.comment, self.singleton)
-
- new_attr.record_location an_alias.file
- new_attr.visibility = self.visibility
- new_attr.is_alias_for = self
- @aliases << new_attr
- context.add_attribute new_attr
- new_attr
- end
-
- ##
- # The #aref prefix for attributes
-
- def aref_prefix
- 'attribute'
- end
-
- ##
- # Returns attr_reader, attr_writer or attr_accessor as appropriate.
-
- def definition
- case @rw
- when 'RW' then 'attr_accessor'
- when 'R' then 'attr_reader'
- when 'W' then 'attr_writer'
- end
- end
-
- def inspect # :nodoc:
- alias_for = @is_alias_for ? " (alias for #{@is_alias_for.name})" : nil
- visibility = self.visibility
- visibility = "forced #{visibility}" if force_documentation
- "#<%s:0x%x %s %s (%s)%s>" % [
- self.class, object_id,
- full_name,
- rw,
- visibility,
- alias_for,
- ]
- end
-
- ##
- # Dumps this Attr for use by ri. See also #marshal_load
-
- def marshal_dump
- [ MARSHAL_VERSION,
- @name,
- full_name,
- @rw,
- @visibility,
- parse(@comment),
- singleton,
- @file.absolute_name,
- ]
- end
-
- ##
- # Loads this Attr from +array+. For a loaded Attr the following
- # methods will return cached values:
- #
- # * #full_name
- # * #parent_name
-
- def marshal_load array
- version = array[0]
- @name = array[1]
- @full_name = array[2]
- @rw = array[3]
- @visibility = array[4]
- @comment = array[5]
- @singleton = array[6] || false # MARSHAL_VERSION == 0
-
- @file = RDoc::TopLevel.new array[7] if version > 1
-
- @parent_name = @full_name
- end
-
- def pretty_print q # :nodoc:
- q.group 2, "[#{self.class.name} #{full_name} #{rw} #{visibility}", "]" do
- unless comment.empty? then
- q.breakable
- q.text "comment:"
- q.breakable
- q.pp @comment
- end
- end
- end
-
- def to_s # :nodoc:
- "#{definition} #{name} in: #{parent}"
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/class_module.rb b/ruby_1_9_3/lib/rdoc/class_module.rb
deleted file mode 100644
index 27066d8bd7..0000000000
--- a/ruby_1_9_3/lib/rdoc/class_module.rb
+++ /dev/null
@@ -1,582 +0,0 @@
-require 'rdoc/context'
-
-##
-# ClassModule is the base class for objects representing either a class or a
-# module.
-
-class RDoc::ClassModule < RDoc::Context
-
- ##
- # 1::
- # RDoc 3.7
- # * Added visibility, singleton and file to attributes
- # * Added file to constants
- # * Added file to includes
- # * Added file to methods
-
- MARSHAL_VERSION = 1 # :nodoc:
-
- ##
- # Constants that are aliases for this class or module
-
- attr_accessor :constant_aliases
-
- ##
- # Comment and the location it came from. Use #add_comment to add comments
-
- attr_reader :comment_location
-
- attr_accessor :diagram # :nodoc:
-
- ##
- # Class or module this constant is an alias for
-
- attr_accessor :is_alias_for
-
- ##
- # Return a RDoc::ClassModule of class +class_type+ that is a copy
- # of module +module+. Used to promote modules to classes.
- #--
- # TODO move to RDoc::NormalClass (I think)
-
- def self.from_module class_type, mod
- klass = class_type.new mod.name
-
- mod.comment_location.each do |comment, location|
- klass.add_comment comment, location
- end
-
- klass.parent = mod.parent
- klass.section = mod.section
- klass.viewer = mod.viewer
-
- klass.attributes.concat mod.attributes
- klass.method_list.concat mod.method_list
- klass.aliases.concat mod.aliases
- klass.external_aliases.concat mod.external_aliases
- klass.constants.concat mod.constants
- klass.includes.concat mod.includes
-
- klass.methods_hash.update mod.methods_hash
- klass.constants_hash.update mod.constants_hash
-
- klass.current_section = mod.current_section
- klass.in_files.concat mod.in_files
- klass.sections.concat mod.sections
- klass.unmatched_alias_lists = mod.unmatched_alias_lists
- klass.current_section = mod.current_section
- klass.visibility = mod.visibility
-
- klass.classes_hash.update mod.classes_hash
- klass.modules_hash.update mod.modules_hash
- klass.metadata.update mod.metadata
-
- klass.document_self = mod.received_nodoc ? nil : mod.document_self
- klass.document_children = mod.document_children
- klass.force_documentation = mod.force_documentation
- klass.done_documenting = mod.done_documenting
-
- # update the parent of all children
-
- (klass.attributes +
- klass.method_list +
- klass.aliases +
- klass.external_aliases +
- klass.constants +
- klass.includes +
- klass.classes +
- klass.modules).each do |obj|
- obj.parent = klass
- obj.full_name = nil
- end
-
- klass
- end
-
- ##
- # Creates a new ClassModule with +name+ with optional +superclass+
- #
- # This is a constructor for subclasses, and must never be called directly.
-
- def initialize(name, superclass = nil)
- @constant_aliases = []
- @diagram = nil
- @is_alias_for = nil
- @name = name
- @superclass = superclass
- @comment_location = [] # [[comment, location]]
-
- super()
- end
-
- ##
- # Adds +comment+ to this ClassModule's list of comments at +location+. This
- # method is preferred over #comment= since it allows ri data to be updated
- # across multiple runs.
-
- def add_comment comment, location
- return if comment.empty? or not document_self
-
- original = comment
-
- comment = normalize_comment comment
- @comment_location << [comment, location]
-
- self.comment = original
- end
-
- ##
- # Ancestors list for this ClassModule: the list of included modules
- # (classes will add their superclass if any).
- #
- # Returns the included classes or modules, not the includes
- # themselves. The returned values are either String or
- # RDoc::NormalModule instances (see RDoc::Include#module).
- #
- # The values are returned in reverse order of their inclusion,
- # which is the order suitable for searching methods/attributes
- # in the ancestors. The superclass, if any, comes last.
-
- def ancestors
- includes.map { |i| i.module }.reverse
- end
-
- ##
- # Clears the comment. Used by the ruby parser.
-
- def clear_comment
- @comment = ''
- end
-
- ##
- # This method is deprecated, use #add_comment instead.
- #
- # Appends +comment+ to the current comment, but separated by a rule. Works
- # more like <tt>+=</tt>.
-
- def comment= comment
- return if comment.empty?
-
- comment = normalize_comment comment
- comment = "#{@comment}\n---\n#{comment}" unless @comment.empty?
-
- super comment
- end
-
- ##
- # Prepares this ClassModule for use by a generator.
- #
- # See RDoc::TopLevel::complete
-
- def complete min_visibility
- update_aliases
- remove_nodoc_children
- update_includes
- remove_invisible min_visibility
- end
-
- ##
- # Iterates the ancestors of this class or module for which an
- # RDoc::ClassModule exists.
-
- def each_ancestor # :yields: module
- ancestors.each do |mod|
- next if String === mod
- yield mod
- end
- end
-
- ##
- # Looks for a symbol in the #ancestors. See Context#find_local_symbol.
-
- def find_ancestor_local_symbol symbol
- each_ancestor do |m|
- res = m.find_local_symbol(symbol)
- return res if res
- end
-
- nil
- end
-
- ##
- # Finds a class or module with +name+ in this namespace or its descendants
-
- def find_class_named name
- return self if full_name == name
- return self if @name == name
-
- @classes.values.find do |klass|
- next if klass == self
- klass.find_class_named name
- end
- end
-
- ##
- # Return the fully qualified name of this class or module
-
- def full_name
- @full_name ||= if RDoc::ClassModule === @parent then
- "#{@parent.full_name}::#{@name}"
- else
- @name
- end
- end
-
- ##
- # TODO: filter included items by #display?
-
- def marshal_dump # :nodoc:
- attrs = attributes.sort.map do |attr|
- [ attr.name, attr.rw,
- attr.visibility, attr.singleton, attr.file_name,
- ]
- end
-
- method_types = methods_by_type.map do |type, visibilities|
- visibilities = visibilities.map do |visibility, methods|
- method_names = methods.map do |method|
- [method.name, method.file_name]
- end
-
- [visibility, method_names.uniq]
- end
-
- [type, visibilities]
- end
-
- [ MARSHAL_VERSION,
- @name,
- full_name,
- @superclass,
- parse(@comment_location),
- attrs,
- constants.map do |const|
- [const.name, parse(const.comment), const.file_name]
- end,
- includes.map do |incl|
- [incl.name, parse(incl.comment), incl.file_name]
- end,
- method_types,
- ]
- end
-
- def marshal_load array # :nodoc:
- initialize_methods_etc
- @current_section = nil
- @document_self = true
- @done_documenting = false
- @parent = nil
- @temporary_section = nil
- @visibility = nil
-
- @name = array[1]
- @full_name = array[2]
- @superclass = array[3]
- @comment = array[4]
-
- @comment_location = if RDoc::Markup::Document === @comment.parts.first then
- @comment
- else
- RDoc::Markup::Document.new @comment
- end
-
- array[5].each do |name, rw, visibility, singleton, file|
- singleton ||= false
- visibility ||= :public
-
- attr = RDoc::Attr.new nil, name, rw, nil, singleton
-
- add_attribute attr
- attr.visibility = visibility
- attr.record_location RDoc::TopLevel.new file
- end
-
- array[6].each do |name, comment, file|
- const = add_constant RDoc::Constant.new(name, nil, comment)
- const.record_location RDoc::TopLevel.new file
- end
-
- array[7].each do |name, comment, file|
- incl = add_include RDoc::Include.new(name, comment)
- incl.record_location RDoc::TopLevel.new file
- end
-
- array[8].each do |type, visibilities|
- visibilities.each do |visibility, methods|
- @visibility = visibility
-
- methods.each do |name, file|
- method = RDoc::AnyMethod.new nil, name
- method.singleton = true if type == 'class'
- method.record_location RDoc::TopLevel.new file
- add_method method
- end
- end
- end
- end
-
- ##
- # Merges +class_module+ into this ClassModule.
- #
- # The data in +class_module+ is preferred over the receiver.
-
- def merge class_module
- other_document = parse class_module.comment_location
-
- if other_document then
- document = parse @comment_location
-
- document = document.merge other_document
-
- @comment = @comment_location = document
- end
-
- cm = class_module
- other_files = cm.in_files
-
- merge_collections attributes, cm.attributes, other_files do |add, attr|
- if add then
- add_attribute attr
- else
- @attributes.delete attr
- @methods_hash.delete attr.pretty_name
- end
- end
-
- merge_collections constants, cm.constants, other_files do |add, const|
- if add then
- add_constant const
- else
- @constants.delete const
- @constants_hash.delete const.name
- end
- end
-
- merge_collections includes, cm.includes, other_files do |add, incl|
- if add then
- add_include incl
- else
- @includes.delete incl
- end
- end
-
- merge_collections method_list, cm.method_list, other_files do |add, meth|
- if add then
- add_method meth
- else
- @method_list.delete meth
- @methods_hash.delete meth.pretty_name
- end
- end
-
- self
- end
-
- ##
- # Merges collection +mine+ with +other+ preferring other. +other_files+ is
- # used to help determine which items should be deleted.
- #
- # Yields whether the item should be added or removed (true or false) and the
- # item to be added or removed.
- #
- # merge_collections things, other.things, other.in_files do |add, thing|
- # if add then
- # # add the thing
- # else
- # # remove the thing
- # end
- # end
-
- def merge_collections mine, other, other_files, &block # :nodoc:
- my_things = mine. group_by { |thing| thing.file }
- other_things = other.group_by { |thing| thing.file }
-
- my_things.delete_if do |file, things|
- next false unless other_files.include? file
-
- things.each do |thing|
- yield false, thing
- end
-
- true
- end
-
- other_things.each do |file, things|
- my_things[file].each { |thing| yield false, thing } if
- my_things.include?(file)
-
- things.each do |thing|
- yield true, thing
- end
- end
- end
-
- ##
- # Does this object represent a module?
-
- def module?
- false
- end
-
- ##
- # Allows overriding the initial name.
- #
- # Used for modules and classes that are constant aliases.
-
- def name= new_name
- @name = new_name
- end
-
- ##
- # Parses +comment_location+ into an RDoc::Markup::Document composed of
- # multiple RDoc::Markup::Documents with their file set.
-
- def parse comment_location
- case comment_location
- when String then
- super
- when Array then
- docs = comment_location.map do |comment, location|
- doc = super comment
- doc.file = location.absolute_name
- doc
- end
-
- RDoc::Markup::Document.new(*docs)
- when RDoc::Markup::Document then
- return comment_location
- else
- raise ArgumentError, "unknown comment class #{comment_location.class}"
- end
- end
-
- ##
- # Path to this class or module
-
- def path
- http_url RDoc::RDoc.current.generator.class_dir
- end
-
- ##
- # Name to use to generate the url:
- # modules and classes that are aliases for another
- # module or class return the name of the latter.
-
- def name_for_path
- is_alias_for ? is_alias_for.full_name : full_name
- end
-
- ##
- # Returns the classes and modules that are not constants
- # aliasing another class or module. For use by formatters
- # only (caches its result).
-
- def non_aliases
- @non_aliases ||= classes_and_modules.reject { |cm| cm.is_alias_for }
- end
-
- ##
- # Updates the child modules or classes of class/module +parent+ by
- # deleting the ones that have been removed from the documentation.
- #
- # +parent_hash+ is either <tt>parent.modules_hash</tt> or
- # <tt>parent.classes_hash</tt> and +all_hash+ is ::all_modules_hash or
- # ::all_classes_hash.
-
- def remove_nodoc_children
- prefix = self.full_name + '::'
-
- modules_hash.each_key do |name|
- full_name = prefix + name
- modules_hash.delete name unless RDoc::TopLevel.all_modules_hash[full_name]
- end
-
- classes_hash.each_key do |name|
- full_name = prefix + name
- classes_hash.delete name unless RDoc::TopLevel.all_classes_hash[full_name]
- end
- end
-
- ##
- # Get the superclass of this class. Attempts to retrieve the superclass
- # object, returns the name if it is not known.
-
- def superclass
- RDoc::TopLevel.find_class_named(@superclass) || @superclass
- end
-
- ##
- # Set the superclass of this class to +superclass+
-
- def superclass=(superclass)
- raise NoMethodError, "#{full_name} is a module" if module?
- @superclass = superclass
- end
-
- def to_s # :nodoc:
- if is_alias_for then
- "#{self.class.name} #{self.full_name} -> #{is_alias_for}"
- else
- super
- end
- end
-
- ##
- # 'module' or 'class'
-
- def type
- module? ? 'module' : 'class'
- end
-
- ##
- # Updates the child modules & classes by replacing the ones that are
- # aliases through a constant.
- #
- # The aliased module/class is replaced in the children and in
- # RDoc::TopLevel::all_modules_hash or RDoc::TopLevel::all_classes_hash
- # by a copy that has <tt>RDoc::ClassModule#is_alias_for</tt> set to
- # the aliased module/class, and this copy is added to <tt>#aliases</tt>
- # of the aliased module/class.
- #
- # Formatters can use the #non_aliases method to retrieve children that
- # are not aliases, for instance to list the namespace content, since
- # the aliased modules are included in the constants of the class/module,
- # that are listed separately.
-
- def update_aliases
- constants.each do |const|
- next unless cm = const.is_alias_for
- cm_alias = cm.dup
- cm_alias.name = const.name
- cm_alias.parent = self
- cm_alias.full_name = nil # force update for new parent
- cm_alias.aliases.clear
- cm_alias.is_alias_for = cm
-
- if cm.module? then
- RDoc::TopLevel.all_modules_hash[cm_alias.full_name] = cm_alias
- modules_hash[const.name] = cm_alias
- else
- RDoc::TopLevel.all_classes_hash[cm_alias.full_name] = cm_alias
- classes_hash[const.name] = cm_alias
- end
-
- cm.aliases << cm_alias
- end
- end
-
- ##
- # Deletes from #includes those whose module has been removed from the
- # documentation.
- #--
- # FIXME: includes are not reliably removed, see _possible_bug test case
-
- def update_includes
- includes.reject! do |include|
- mod = include.module
- !(String === mod) && RDoc::TopLevel.all_modules_hash[mod.full_name].nil?
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/code_object.rb b/ruby_1_9_3/lib/rdoc/code_object.rb
deleted file mode 100644
index 54826fffbd..0000000000
--- a/ruby_1_9_3/lib/rdoc/code_object.rb
+++ /dev/null
@@ -1,307 +0,0 @@
-require 'rdoc'
-require 'rdoc/text'
-
-##
-# Base class for the RDoc code tree.
-#
-# We contain the common stuff for contexts (which are containers) and other
-# elements (methods, attributes and so on)
-#
-# Here's the tree of the CodeObject subclasses:
-#
-# * RDoc::Context
-# * RDoc::TopLevel
-# * RDoc::ClassModule
-# * RDoc::AnonClass (never used so far)
-# * RDoc::NormalClass
-# * RDoc::NormalModule
-# * RDoc::SingleClass
-# * RDoc::MethodAttr
-# * RDoc::Attr
-# * RDoc::AnyMethod
-# * RDoc::GhostMethod
-# * RDoc::MetaMethod
-# * RDoc::Alias
-# * RDoc::Constant
-# * RDoc::Require
-# * RDoc::Include
-
-class RDoc::CodeObject
-
- include RDoc::Text
-
- ##
- # Our comment
-
- attr_reader :comment
-
- ##
- # Do we document our children?
-
- attr_reader :document_children
-
- ##
- # Do we document ourselves?
-
- attr_reader :document_self
-
- ##
- # Are we done documenting (ie, did we come across a :enddoc:)?
-
- attr_reader :done_documenting
-
- ##
- # Which file this code object was defined in
-
- attr_reader :file
-
- ##
- # Force documentation of this CodeObject
-
- attr_reader :force_documentation
-
- ##
- # Line in #file where this CodeObject was defined
-
- attr_accessor :line
-
- ##
- # Hash of arbitrary metadata for this CodeObject
-
- attr_reader :metadata
-
- ##
- # Offset in #file where this CodeObject was defined
- #--
- # TODO character or byte?
-
- attr_accessor :offset
-
- ##
- # Our parent CodeObject
-
- attr_accessor :parent
-
- ##
- # Did we ever receive a +:nodoc:+ directive?
-
- attr_reader :received_nodoc
-
- ##
- # Which section are we in
-
- attr_accessor :section
-
- ##
- # 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
-
- ##
- # Creates a new CodeObject that will document itself and its children
-
- def initialize
- @metadata = {}
- @comment = ''
- @parent = nil
- @file = nil
- @full_name = nil
-
- @document_children = true
- @document_self = true
- @done_documenting = false
- @force_documentation = false
- @received_nodoc = false
- @ignored = false
- end
-
- ##
- # Replaces our comment with +comment+, unless it is empty.
-
- def comment=(comment)
- @comment = case comment
- when NilClass then ''
- when RDoc::Markup::Document then comment
- else
- if comment and not comment.empty? then
- normalize_comment comment
- else
- # TODO is this sufficient?
- # HACK correct fix is to have #initialize create @comment
- # with the correct encoding
- if String === @comment and
- Object.const_defined? :Encoding and @comment.empty? then
- @comment.force_encoding comment.encoding
- end
- @comment
- end
- end
- end
-
- ##
- # Should this CodeObject be shown in documentation?
-
- def display?
- @document_self and not @ignored
- end
-
- ##
- # Enables or disables documentation of this CodeObject's children unless it
- # has been turned off by :enddoc:
-
- def document_children=(document_children)
- @document_children = document_children unless @done_documenting
- end
-
- ##
- # Enables or disables documentation of this CodeObject unless it has been
- # turned off by :enddoc:. If the argument is +nil+ it means the
- # documentation is turned off by +:nodoc:+.
-
- def document_self=(document_self)
- return if @done_documenting
-
- @document_self = document_self
- @received_nodoc = true if document_self.nil?
- end
-
- ##
- # Does this object have a comment with content or is #received_nodoc true?
-
- def documented?
- @received_nodoc or !@comment.empty?
- end
-
- ##
- # Turns documentation on/off, and turns on/off #document_self
- # and #document_children.
- #
- # Once documentation has been turned off (by +:enddoc:+),
- # the object will refuse to turn #document_self or
- # #document_children on, so +:doc:+ and +:start_doc:+ directives
- # will have no effect in the current file.
-
- def done_documenting=(value)
- @done_documenting = value
- @document_self = !value
- @document_children = @document_self
- end
-
- ##
- # Yields each parent of this CodeObject. See also
- # RDoc::ClassModule#each_ancestor
-
- def each_parent
- code_object = self
-
- while code_object = code_object.parent do
- yield code_object
- end
-
- self
- end
-
- ##
- # File name where this CodeObject was found.
- #
- # See also RDoc::Context#in_files
-
- def file_name
- return unless @file
-
- @file.absolute_name
- end
-
- ##
- # Force the documentation of this object unless documentation
- # has been turned off by :endoc:
- #--
- # HACK untested, was assigning to an ivar
-
- def force_documentation=(value)
- @force_documentation = value unless @done_documenting
- end
-
- ##
- # Sets the full_name overriding any computed full name.
- #
- # Set to +nil+ to clear RDoc's cached value
-
- def full_name= full_name
- @full_name = full_name
- end
-
- ##
- # Use this to ignore a CodeObject and all its children until found again
- # (#record_location is called). An ignored item will not be shown in
- # documentation.
- #
- # See github issue #55
- #
- # The ignored status is temporary in order to allow implementation details
- # to be hidden. At the end of processing a file RDoc allows all classes
- # and modules to add new documentation to previously created classes.
- #
- # If a class was ignored (via stopdoc) then reopened later with additional
- # documentation it should be shown. If a class was ignored and never
- # reopened it should not be shown. The ignore flag allows this to occur.
-
- def ignore
- @ignored = true
-
- stop_doc
- end
-
- ##
- # Has this class been ignored?
-
- def ignored?
- @ignored
- end
-
- ##
- # File name of our parent
-
- def parent_file_name
- @parent ? @parent.base_name : '(unknown)'
- end
-
- ##
- # Name of our parent
-
- def parent_name
- @parent ? @parent.full_name : '(unknown)'
- end
-
- ##
- # Records the RDoc::TopLevel (file) where this code object was defined
-
- def record_location top_level
- @ignored = false
- @file = top_level
- end
-
- ##
- # Enable capture of documentation unless documentation has been
- # turned off by :endoc:
-
- def start_doc
- return if @done_documenting
-
- @document_self = true
- @document_children = true
- @ignored = false
- end
-
- ##
- # Disable capture of documentation
-
- def stop_doc
- @document_self = false
- @document_children = false
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/code_objects.rb b/ruby_1_9_3/lib/rdoc/code_objects.rb
deleted file mode 100644
index c60dad92df..0000000000
--- a/ruby_1_9_3/lib/rdoc/code_objects.rb
+++ /dev/null
@@ -1,23 +0,0 @@
-# We represent the various high-level code constructs that appear in Ruby
-# programs: classes, modules, methods, and so on.
-
-require 'rdoc/code_object'
-require 'rdoc/context'
-require 'rdoc/top_level'
-
-require 'rdoc/class_module'
-require 'rdoc/normal_class'
-require 'rdoc/normal_module'
-require 'rdoc/anon_class'
-require 'rdoc/single_class'
-
-require 'rdoc/any_method'
-require 'rdoc/alias'
-require 'rdoc/ghost_method'
-require 'rdoc/meta_method'
-
-require 'rdoc/attr'
-require 'rdoc/constant'
-require 'rdoc/require'
-require 'rdoc/include'
-
diff --git a/ruby_1_9_3/lib/rdoc/constant.rb b/ruby_1_9_3/lib/rdoc/constant.rb
deleted file mode 100644
index 056ce130be..0000000000
--- a/ruby_1_9_3/lib/rdoc/constant.rb
+++ /dev/null
@@ -1,86 +0,0 @@
-require 'rdoc/code_object'
-
-##
-# A constant
-
-class RDoc::Constant < RDoc::CodeObject
-
- ##
- # If this constant is an alias for a module or class,
- # this is the RDoc::ClassModule it is an alias for.
- # +nil+ otherwise.
-
- attr_accessor :is_alias_for
-
- ##
- # The constant's name
-
- attr_accessor :name
-
- ##
- # The constant's value
-
- attr_accessor :value
-
- ##
- # Creates a new constant with +name+, +value+ and +comment+
-
- def initialize(name, value, comment)
- super()
- @name = name
- @value = value
- @is_alias_for = nil
- self.comment = comment
- end
-
- ##
- # Constants are ordered by name
-
- def <=> other
- return unless self.class === other
-
- [parent_name, name] <=> [other.parent_name, other.name]
- end
-
- ##
- # Constants are equal when their #parent and #name is the same
-
- def == other
- self.class == other.class and
- @parent == other.parent and
- @name == other.name
- end
-
- ##
- # A constant is documented if it has a comment, or is an alias
- # for a documented class or module.
-
- def documented?
- super or is_alias_for && is_alias_for.documented?
- end
-
- def inspect # :nodoc:
- "#<%s:0x%x %s::%s>" % [
- self.class, object_id,
- parent_name, @name,
- ]
- end
-
- ##
- # Path to this constant
-
- def path
- "#{@parent.path}##{@name}"
- end
-
- def to_s # :nodoc:
- parent_name = parent ? parent.full_name : '(unknown)'
- if is_alias_for
- "constant #{parent_name}::#@name -> #{is_alias_for}"
- else
- "constant #{parent_name}::#@name"
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/context.rb b/ruby_1_9_3/lib/rdoc/context.rb
deleted file mode 100644
index abdab2026d..0000000000
--- a/ruby_1_9_3/lib/rdoc/context.rb
+++ /dev/null
@@ -1,1191 +0,0 @@
-require 'rdoc/code_object'
-
-##
-# A Context is something that can hold modules, classes, methods, attributes,
-# aliases, requires, and includes. Classes, modules, and files are all
-# Contexts.
-
-class RDoc::Context < RDoc::CodeObject
-
- include Comparable
-
- ##
- # Types of methods
-
- TYPES = %w[class instance]
-
- ##
- # Class/module aliases
-
- attr_reader :aliases
-
- ##
- # All attr* methods
-
- attr_reader :attributes
-
- ##
- # Constants defined
-
- attr_reader :constants
-
- ##
- # Sets the current documentation section of documentation
-
- attr_writer :current_section
-
- ##
- # Files this context is found in
-
- attr_reader :in_files
-
- ##
- # Modules this context includes
-
- attr_reader :includes
-
- ##
- # Methods defined in this context
-
- attr_reader :method_list
-
- ##
- # Name of this class excluding namespace. See also full_name
-
- attr_reader :name
-
- ##
- # Files this context requires
-
- attr_reader :requires
-
- ##
- # Use this section for the next method, attribute or constant added.
-
- attr_accessor :temporary_section
-
- ##
- # Hash <tt>old_name => [aliases]</tt>, for aliases
- # that haven't (yet) been resolved to a method/attribute.
- # (Not to be confused with the aliases of the context.)
-
- attr_accessor :unmatched_alias_lists
-
- ##
- # Aliases that could not eventually be resolved.
-
- attr_reader :external_aliases
-
- ##
- # Current visibility of this context
-
- attr_accessor :visibility
-
- ##
- # Hash of registered methods. Attributes are also registered here,
- # twice if they are RW.
-
- attr_reader :methods_hash
-
- ##
- # Hash of registered constants.
-
- attr_reader :constants_hash
-
- ##
- # A section of documentation like:
- #
- # # :section: The title
- # # The body
- #
- # Sections can be referenced multiple times and will be collapsed into a
- # single section.
-
- class Section
-
- include RDoc::Text
-
- ##
- # Section comment
-
- attr_reader :comment
-
- ##
- # Context this Section lives in
-
- attr_reader :parent
-
- ##
- # Section title
-
- attr_reader :title
-
- @@sequence = "SEC00000"
-
- ##
- # Creates a new section with +title+ and +comment+
-
- def initialize parent, title, comment
- @parent = parent
- @title = title ? title.strip : title
-
- @@sequence.succ!
- @sequence = @@sequence.dup
-
- @comment = extract_comment comment
- end
-
- ##
- # Sections are equal when they have the same #title
-
- def == other
- self.class === other and @title == other.title
- end
-
- ##
- # Anchor reference for linking to this section
-
- def aref
- title = @title || '[untitled]'
-
- CGI.escape(title).gsub('%', '-').sub(/^-/, '')
- end
-
- ##
- # Appends +comment+ to the current comment separated by a rule.
-
- def comment= comment
- comment = extract_comment comment
-
- return if comment.empty?
-
- if @comment then
- @comment += "\n# ---\n#{comment}"
- else
- @comment = comment
- end
- end
-
- ##
- # Extracts 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 extract_comment comment
- if comment =~ /^#[ \t]*:section:.*\n/ then
- start = $`
- rest = $'
-
- if start.empty? then
- rest
- else
- rest.sub(/#{start.chomp}\Z/, '')
- end
- else
- comment
- end
- end
-
- def inspect # :nodoc:
- "#<%s:0x%x %p>" % [self.class, object_id, title]
- end
-
- ##
- # Section sequence number (deprecated)
-
- def sequence
- warn "RDoc::Context::Section#sequence is deprecated, use #aref"
- @sequence
- end
-
- end
-
- ##
- # Creates an unnamed empty context with public current visibility
-
- def initialize
- super
-
- @in_files = []
-
- @name ||= "unknown"
- @parent = nil
- @visibility = :public
-
- @current_section = Section.new self, nil, nil
- @sections = { nil => @current_section }
- @temporary_section = nil
-
- @classes = {}
- @modules = {}
-
- initialize_methods_etc
- end
-
- ##
- # Sets the defaults for methods and so-forth
-
- def initialize_methods_etc
- @method_list = []
- @attributes = []
- @aliases = []
- @requires = []
- @includes = []
- @constants = []
- @external_aliases = []
-
- # This Hash maps a method name to a list of unmatched aliases (aliases of
- # a method not yet encountered).
- @unmatched_alias_lists = {}
-
- @methods_hash = {}
- @constants_hash = {}
- end
-
- ##
- # Contexts are sorted by full_name
-
- def <=>(other)
- full_name <=> other.full_name
- end
-
- ##
- # Adds +an_alias+ that is automatically resolved
-
- def add_alias an_alias
- return an_alias unless @document_self
-
- method_attr = find_method(an_alias.old_name, an_alias.singleton) ||
- find_attribute(an_alias.old_name, an_alias.singleton)
-
- if method_attr then
- method_attr.add_alias an_alias, self
- else
- add_to @external_aliases, an_alias
- unmatched_alias_list =
- @unmatched_alias_lists[an_alias.pretty_old_name] ||= []
- unmatched_alias_list.push an_alias
- end
-
- an_alias
- end
-
- ##
- # Adds +attribute+ if not already there. If it is (as method(s) or attribute),
- # updates the comment if it was empty.
- #
- # The attribute is registered only if it defines a new method.
- # For instance, <tt>attr_reader :foo</tt> will not be registered
- # if method +foo+ exists, but <tt>attr_accessor :foo</tt> will be registered
- # if method +foo+ exists, but <tt>foo=</tt> does not.
-
- def add_attribute attribute
- return attribute unless @document_self
-
- # mainly to check for redefinition of an attribute as a method
- # TODO find a policy for 'attr_reader :foo' + 'def foo=()'
- register = false
-
- key = nil
-
- if attribute.rw.index 'R' then
- key = attribute.pretty_name
- known = @methods_hash[key]
-
- if known then
- known.comment = attribute.comment if known.comment.empty?
- elsif registered = @methods_hash[attribute.pretty_name << '='] and
- RDoc::Attr === registered then
- registered.rw = 'RW'
- else
- @methods_hash[key] = attribute
- register = true
- end
- end
-
- if attribute.rw.index 'W' then
- key = attribute.pretty_name << '='
- known = @methods_hash[key]
-
- if known then
- known.comment = attribute.comment if known.comment.empty?
- elsif registered = @methods_hash[attribute.pretty_name] and
- RDoc::Attr === registered then
- registered.rw = 'RW'
- else
- @methods_hash[key] = attribute
- register = true
- end
- end
-
- if register then
- attribute.visibility = @visibility
- add_to @attributes, attribute
- resolve_aliases attribute
- end
-
- attribute
- end
-
- ##
- # Adds a class named +given_name+ with +superclass+.
- #
- # Both +given_name+ and +superclass+ may contain '::', and are
- # interpreted relative to the +self+ context. This allows handling correctly
- # examples like these:
- # class RDoc::Gauntlet < Gauntlet
- # module Mod
- # class Object # implies < ::Object
- # class SubObject < Object # this is _not_ ::Object
- #
- # Given <tt>class Container::Item</tt> RDoc assumes +Container+ is a module
- # unless it later sees <tt>class Container</tt>. +add_class+ automatically
- # upgrades +given_name+ to a class in this case.
-
- def add_class class_type, given_name, superclass = '::Object'
- # superclass +nil+ is passed by the C parser in the following cases:
- # - registering Object in 1.8 (correct)
- # - registering BasicObject in 1.9 (correct)
- # - registering RubyVM in 1.9 in iseq.c (incorrect: < Object in vm.c)
- #
- # If we later find a superclass for a registered class with a nil
- # superclass, we must honor it.
-
- # find the name & enclosing context
- if given_name =~ /^:+(\w+)$/ then
- full_name = $1
- enclosing = top_level
- name = full_name.split(/:+/).last
- else
- full_name = child_name given_name
-
- if full_name =~ /^(.+)::(\w+)$/ then
- name = $2
- ename = $1
- enclosing = RDoc::TopLevel.classes_hash[ename] ||
- RDoc::TopLevel.modules_hash[ename]
- # HACK: crashes in actionpack/lib/action_view/helpers/form_helper.rb (metaprogramming)
- unless enclosing then
- # try the given name at top level (will work for the above example)
- enclosing = RDoc::TopLevel.classes_hash[given_name] || RDoc::TopLevel.modules_hash[given_name]
- return enclosing if enclosing
- # not found: create the parent(s)
- names = ename.split('::')
- enclosing = self
- names.each do |n|
- enclosing = enclosing.classes_hash[n] ||
- enclosing.modules_hash[n] ||
- enclosing.add_module(RDoc::NormalModule, n)
- end
- end
- else
- name = full_name
- enclosing = self
- end
- end
-
- # fix up superclass
- superclass = nil if full_name == 'BasicObject'
- superclass = nil if full_name == 'Object' and defined?(::BasicObject)
- superclass = '::BasicObject' if
- defined?(::BasicObject) and full_name == 'Object'
-
- # find the superclass full name
- if superclass then
- if superclass =~ /^:+/ then
- superclass = $' #'
- else
- if superclass =~ /^(\w+):+(.+)$/ then
- suffix = $2
- mod = find_module_named($1)
- superclass = mod.full_name + '::' + suffix if mod
- else
- mod = find_module_named(superclass)
- superclass = mod.full_name if mod
- end
- end
-
- # did we believe it was a module?
- mod = RDoc::TopLevel.modules_hash.delete superclass
-
- upgrade_to_class mod, RDoc::NormalClass, mod.parent if mod
-
- # e.g., Object < Object
- superclass = nil if superclass == full_name
- end
-
- klass = RDoc::TopLevel.classes_hash[full_name]
-
- if klass then
- # if TopLevel, it may not be registered in the classes:
- enclosing.classes_hash[name] = klass
-
- # update the superclass if needed
- if superclass then
- existing = klass.superclass
- existing = existing.full_name unless existing.is_a?(String) if existing
- if existing.nil? ||
- (existing == 'Object' && superclass != 'Object') then
- klass.superclass = superclass
- end
- end
- else
- # this is a new class
- mod = RDoc::TopLevel.modules_hash.delete full_name
-
- if mod then
- klass = upgrade_to_class mod, RDoc::NormalClass, enclosing
-
- klass.superclass = superclass unless superclass.nil?
- else
- klass = class_type.new name, superclass
-
- enclosing.add_class_or_module(klass, enclosing.classes_hash,
- RDoc::TopLevel.classes_hash)
- end
- end
-
- klass
- end
-
- ##
- # Adds the class or module +mod+ to the modules or
- # classes Hash +self_hash+, and to +all_hash+ (either
- # <tt>TopLevel::modules_hash</tt> or <tt>TopLevel::classes_hash</tt>),
- # unless #done_documenting is +true+. Sets the #parent of +mod+
- # to +self+, and its #section to #current_section. Returns +mod+.
-
- def add_class_or_module mod, self_hash, all_hash
- mod.section = current_section # TODO declaring context? something is
- # wrong here...
- mod.parent = self
-
- unless @done_documenting then
- self_hash[mod.name] = mod
- # this must be done AFTER adding mod to its parent, so that the full
- # name is correct:
- all_hash[mod.full_name] = mod
- end
-
- mod
- end
-
- ##
- # Adds +constant+ if not already there. If it is, updates the comment,
- # value and/or is_alias_for of the known constant if they were empty/nil.
-
- def add_constant constant
- return constant unless @document_self
-
- # HACK: avoid duplicate 'PI' & 'E' in math.c (1.8.7 source code)
- # (this is a #ifdef: should be handled by the C parser)
- known = @constants_hash[constant.name]
-
- if known then
- known.comment = constant.comment if known.comment.empty?
-
- known.value = constant.value if
- known.value.nil? or known.value.strip.empty?
-
- known.is_alias_for ||= constant.is_alias_for
- else
- @constants_hash[constant.name] = constant
- add_to @constants, constant
- end
-
- constant
- end
-
- ##
- # Adds included module +include+ which should be an RDoc::Include
-
- def add_include include
- add_to @includes, include unless
- @includes.map { |i| i.full_name }.include? include.full_name
-
- include
- end
-
- ##
- # Adds +method+ if not already there. If it is (as method or attribute),
- # updates the comment if it was empty.
-
- def add_method method
- return method unless @document_self
-
- # HACK: avoid duplicate 'new' in io.c & struct.c (1.8.7 source code)
- key = method.pretty_name
- known = @methods_hash[key]
-
- if known then
- known.comment = method.comment if known.comment.empty?
- else
- @methods_hash[key] = method
- method.visibility = @visibility
- add_to @method_list, method
- resolve_aliases method
- end
-
- method
- end
-
- ##
- # Adds a module named +name+. If RDoc already knows +name+ is a class then
- # that class is returned instead. See also #add_class.
-
- def add_module(class_type, name)
- mod = @classes[name] || @modules[name]
- return mod if mod
-
- full_name = child_name name
- mod = RDoc::TopLevel.modules_hash[full_name] || class_type.new(name)
-
- add_class_or_module(mod, @modules, RDoc::TopLevel.modules_hash)
- end
-
- ##
- # Adds an alias from +from+ (a class or module) to +name+ which was defined
- # in +file+.
-
- def add_module_alias from, name, file
- return from if @done_documenting
-
- to_name = child_name(name)
-
- # if we already know this name, don't register an alias:
- # see the metaprogramming in lib/active_support/basic_object.rb,
- # where we already know BasicObject as a class when we find
- # BasicObject = BlankSlate
- return from if RDoc::TopLevel.find_class_or_module(to_name)
-
- if from.module? then
- RDoc::TopLevel.modules_hash[to_name] = from
- @modules[name] = from
- else
- RDoc::TopLevel.classes_hash[to_name] = from
- @classes[name] = from
- end
-
- # HACK: register a constant for this alias:
- # constant value and comment will be updated after,
- # when the Ruby parser adds the constant
- const = RDoc::Constant.new name, nil, ''
- const.record_location file
- const.is_alias_for = from
- add_constant const
-
- from
- end
-
- ##
- # Adds +require+ to this context's top level
-
- def add_require(require)
- return require unless @document_self
-
- if RDoc::TopLevel === self then
- add_to @requires, require
- else
- parent.add_require require
- end
- end
-
- ##
- # Returns a section with +title+, creating it if it doesn't already exist.
- # +comment+ will be appended to the section's comment.
- #
- # A section with a +title+ of +nil+ will return the default section.
- #
- # See also RDoc::Context::Section
-
- def add_section title, comment
- if section = @sections[title] then
- section.comment = comment
- else
- section = Section.new self, title, comment
- @sections[title] = section
- end
-
- section
- end
-
- ##
- # Adds +thing+ to the collection +array+
-
- def add_to(array, thing)
- array << thing if @document_self
- thing.parent = self
- thing.section = current_section
- end
-
- ##
- # Is there any content?
- #
- # This means any of: comment, aliases, methods, attributes, external
- # aliases, require, constant.
- #
- # Includes are also checked unless <tt>includes == false</tt>.
-
- def any_content(includes = true)
- @any_content ||= !(
- @comment.empty? &&
- @method_list.empty? &&
- @attributes.empty? &&
- @aliases.empty? &&
- @external_aliases.empty? &&
- @requires.empty? &&
- @constants.empty?
- )
- @any_content || (includes && !@includes.empty?)
- end
-
- ##
- # Creates the full name for a child with +name+
-
- def child_name name
- if name =~ /^:+/
- $' #'
- elsif RDoc::TopLevel === self then
- name
- else
- "#{self.full_name}::#{name}"
- end
- end
-
- ##
- # Class attributes
-
- def class_attributes
- @class_attributes ||= attributes.select { |a| a.singleton }
- end
-
- ##
- # Class methods
-
- def class_method_list
- @class_method_list ||= method_list.select { |a| a.singleton }
- end
-
- ##
- # Array of classes in this context
-
- def classes
- @classes.values
- end
-
- ##
- # All classes and modules in this namespace
-
- def classes_and_modules
- classes + modules
- end
-
- ##
- # Hash of classes keyed by class name
-
- def classes_hash
- @classes
- end
-
- ##
- # The current documentation section that new items will be added to. If
- # temporary_section is available it will be used.
-
- def current_section
- if section = @temporary_section then
- @temporary_section = nil
- else
- section = @current_section
- end
-
- section
- end
-
- ##
- # Is part of this thing was defined in +file+?
-
- def defined_in?(file)
- @in_files.include?(file)
- end
-
- def display(method_attr) # :nodoc:
- if method_attr.is_a? RDoc::Attr
- "#{method_attr.definition} #{method_attr.pretty_name}"
- else
- "method #{method_attr.pretty_name}"
- end
- end
-
- ##
- # Iterator for ancestors for duck-typing. Does nothing. See
- # RDoc::ClassModule#each_ancestor.
-
- def each_ancestor # :nodoc:
- end
-
- ##
- # Iterator for attributes
-
- def each_attribute # :yields: attribute
- @attributes.each { |a| yield a }
- end
-
- ##
- # Iterator for classes and modules
-
- def each_classmodule(&block) # :yields: module
- classes_and_modules.sort.each(&block)
- end
-
- ##
- # Iterator for constants
-
- def each_constant # :yields: constant
- @constants.each {|c| yield c}
- end
-
- ##
- # Iterator for included modules
-
- def each_include # :yields: include
- @includes.each do |i| yield i end
- end
-
- ##
- # Iterator for methods
-
- def each_method # :yields: method
- @method_list.sort.each {|m| yield m}
- end
-
- ##
- # Iterator for each section's contents sorted by title. The +section+, the
- # section's +constants+ and the sections +attributes+ are yielded. The
- # +constants+ and +attributes+ collections are sorted.
- #
- # To retrieve methods in a section use #methods_by_type with the optional
- # +section+ parameter.
- #
- # NOTE: Do not edit collections yielded by this method
-
- def each_section # :yields: section, constants, attributes
- constants = @constants.group_by do |constant| constant.section end
- constants.default = []
-
- attributes = @attributes.group_by do |attribute| attribute.section end
- attributes.default = []
-
- @sections.sort_by { |title, _| title.to_s }.each do |_, section|
- yield section, constants[section].sort, attributes[section].sort
- end
- end
-
- ##
- # Finds an attribute +name+ with singleton value +singleton+.
-
- def find_attribute(name, singleton)
- name = $1 if name =~ /^(.*)=$/
- @attributes.find { |a| a.name == name && a.singleton == singleton }
- end
-
- ##
- # Finds an attribute with +name+ in this context
-
- def find_attribute_named(name)
- case name
- when /\A#/ then
- find_attribute name[1..-1], false
- when /\A::/ then
- find_attribute name[2..-1], true
- else
- @attributes.find { |a| a.name == name }
- end
- end
-
- ##
- # Finds a class method with +name+ in this context
-
- def find_class_method_named(name)
- @method_list.find { |meth| meth.singleton && meth.name == name }
- end
-
- ##
- # Finds a constant with +name+ in this context
-
- def find_constant_named(name)
- @constants.find {|m| m.name == name}
- end
-
- ##
- # Find a module at a higher scope
-
- def find_enclosing_module_named(name)
- parent && parent.find_module_named(name)
- end
-
- ##
- # Finds an external alias +name+ with singleton value +singleton+.
-
- def find_external_alias(name, singleton)
- @external_aliases.find { |m| m.name == name && m.singleton == singleton }
- end
-
- ##
- # Finds an external alias with +name+ in this context
-
- def find_external_alias_named(name)
- case name
- when /\A#/ then
- find_external_alias name[1..-1], false
- when /\A::/ then
- find_external_alias name[2..-1], true
- else
- @external_aliases.find { |a| a.name == name }
- end
- end
-
- ##
- # Finds a file with +name+ in this context
-
- def find_file_named(name)
- top_level.class.find_file_named(name)
- end
-
- ##
- # Finds an instance method with +name+ in this context
-
- def find_instance_method_named(name)
- @method_list.find { |meth| !meth.singleton && meth.name == name }
- end
-
- ##
- # Finds a method, constant, attribute, external alias, module or file
- # named +symbol+ in this context.
-
- def find_local_symbol(symbol)
- find_method_named(symbol) or
- find_constant_named(symbol) or
- find_attribute_named(symbol) or
- find_external_alias_named(symbol) or
- find_module_named(symbol) or
- find_file_named(symbol)
- end
-
- ##
- # Finds a method named +name+ with singleton value +singleton+.
-
- def find_method(name, singleton)
- @method_list.find { |m| m.name == name && m.singleton == singleton }
- end
-
- ##
- # Finds a instance or module method with +name+ in this context
-
- def find_method_named(name)
- case name
- when /\A#/ then
- find_method name[1..-1], false
- when /\A::/ then
- find_method name[2..-1], true
- else
- @method_list.find { |meth| meth.name == name }
- end
- end
-
- ##
- # Find a module with +name+ using ruby's scoping rules
-
- def find_module_named(name)
- res = @modules[name] || @classes[name]
- return res if res
- return self if self.name == name
- find_enclosing_module_named name
- end
-
- ##
- # Look up +symbol+, first as a module, then as a local symbol.
-
- def find_symbol(symbol)
- find_symbol_module(symbol) || find_local_symbol(symbol)
- end
-
- ##
- # Look up a module named +symbol+.
-
- def find_symbol_module(symbol)
- result = nil
-
- # look for a class or module 'symbol'
- case symbol
- when /^::/ then
- result = RDoc::TopLevel.find_class_or_module(symbol)
- when /^(\w+):+(.+)$/
- suffix = $2
- top = $1
- searched = self
- loop do
- mod = searched.find_module_named(top)
- break unless mod
- result = RDoc::TopLevel.find_class_or_module(mod.full_name + '::' + suffix)
- break if result || searched.is_a?(RDoc::TopLevel)
- searched = searched.parent
- end
- else
- searched = self
- loop do
- result = searched.find_module_named(symbol)
- break if result || searched.is_a?(RDoc::TopLevel)
- searched = searched.parent
- end
- end
-
- result
- end
-
- ##
- # The full name for this context. This method is overridden by subclasses.
-
- def full_name
- '(unknown)'
- end
-
- ##
- # Does this context and its methods and constants all have documentation?
- #
- # (Yes, fully documented doesn't mean everything.)
-
- def fully_documented?
- documented? and
- attributes.all? { |a| a.documented? } and
- method_list.all? { |m| m.documented? } and
- constants.all? { |c| c.documented? }
- end
-
- ##
- # URL for this with a +prefix+
-
- def http_url(prefix)
- path = name_for_path
- path = path.gsub(/<<\s*(\w*)/, 'from-\1') if path =~ /<</
- path = [prefix] + path.split('::')
-
- File.join(*path.compact) + '.html'
- end
-
- ##
- # Instance attributes
-
- def instance_attributes
- @instance_attributes ||= attributes.reject { |a| a.singleton }
- end
-
- ##
- # Instance methods
-
- def instance_method_list
- @instance_method_list ||= method_list.reject { |a| a.singleton }
- end
-
- ##
- # Breaks method_list into a nested hash by type (<tt>'class'</tt> or
- # <tt>'instance'</tt>) and visibility (+:public+, +:protected+, +:private+).
- #
- # If +section+ is provided only methods in that RDoc::Context::Section will
- # be returned.
-
- def methods_by_type section = nil
- methods = {}
-
- TYPES.each do |type|
- visibilities = {}
- RDoc::VISIBILITIES.each do |vis|
- visibilities[vis] = []
- end
-
- methods[type] = visibilities
- end
-
- each_method do |method|
- next if section and not method.section == section
- methods[method.type][method.visibility] << method
- end
-
- methods
- end
-
- ##
- # Yields AnyMethod and Attr entries matching the list of names in +methods+.
-
- def methods_matching(methods, singleton = false, &block)
- (@method_list + @attributes).each do |m|
- yield m if methods.include?(m.name) and m.singleton == singleton
- end
-
- each_ancestor do |parent|
- parent.methods_matching(methods, singleton, &block)
- end
- end
-
- ##
- # Array of modules in this context
-
- def modules
- @modules.values
- end
-
- ##
- # Hash of modules keyed by module name
-
- def modules_hash
- @modules
- end
-
- ##
- # Name to use to generate the url.
- # <tt>#full_name</tt> by default.
-
- def name_for_path
- full_name
- end
-
- ##
- # Changes the visibility for new methods to +visibility+
-
- def ongoing_visibility=(visibility)
- @visibility = visibility
- end
-
- ##
- # Record +top_level+ as a file +self+ is in.
-
- def record_location(top_level)
- @in_files << top_level unless @in_files.include?(top_level)
- end
-
- ##
- # Should we remove this context from the documentation?
- #
- # The answer is yes if:
- # * #received_nodoc is +true+
- # * #any_content is +false+ (not counting includes)
- # * All #includes are modules (not a string), and their module has
- # <tt>#remove_from_documentation? == true</tt>
- # * All classes and modules have <tt>#remove_from_documentation? == true</tt>
-
- def remove_from_documentation?
- @remove_from_documentation ||=
- @received_nodoc &&
- !any_content(false) &&
- @includes.all? { |i| !i.module.is_a?(String) && i.module.remove_from_documentation? } &&
- classes_and_modules.all? { |cm| cm.remove_from_documentation? }
- end
-
- ##
- # Removes methods and attributes with a visibility less than +min_visibility+.
- #--
- # TODO mark the visibility of attributes in the template (if not public?)
-
- def remove_invisible(min_visibility)
- return if min_visibility == :private
- remove_invisible_in @method_list, min_visibility
- remove_invisible_in @attributes, min_visibility
- end
-
- ##
- # Only called when min_visibility == :public or :private
-
- def remove_invisible_in(array, min_visibility) # :nodoc:
- if min_visibility == :public
- array.reject! { |e|
- e.visibility != :public and not e.force_documentation
- }
- else
- array.reject! { |e|
- e.visibility == :private and
- not e.force_documentation
- }
- end
- end
-
- ##
- # Tries to resolve unmatched aliases when a method
- # or attribute has just been added.
-
- def resolve_aliases(added)
- # resolve any pending unmatched aliases
- key = added.pretty_name
- unmatched_alias_list = @unmatched_alias_lists[key]
- return unless unmatched_alias_list
- unmatched_alias_list.each do |unmatched_alias|
- added.add_alias unmatched_alias, self
- @external_aliases.delete unmatched_alias
- end
- @unmatched_alias_lists.delete key
- end
-
- ##
- # Sections in this context
-
- def sections
- @sections.values
- end
-
- def sections_hash # :nodoc:
- @sections
- end
-
- ##
- # Sets the current section to a section with +title+. See also #add_section
-
- def set_current_section title, comment
- @current_section = add_section title, comment
- end
-
- ##
- # Given an array +methods+ of method names, set the visibility of each to
- # +visibility+
-
- def set_visibility_for(methods, visibility, singleton = false)
- methods_matching methods, singleton do |m|
- m.visibility = visibility
- end
- end
-
- def to_s # :nodoc:
- "#{self.class.name} #{self.full_name}"
- end
-
- ##
- # Return the TopLevel that owns us
- #--
- # FIXME we can be 'owned' by several TopLevel (see #record_location &
- # #in_files)
-
- def top_level
- return @top_level if defined? @top_level
- @top_level = self
- @top_level = @top_level.parent until RDoc::TopLevel === @top_level
- @top_level
- end
-
- ##
- # Upgrades NormalModule +mod+ in +enclosing+ to a +class_type+
-
- def upgrade_to_class mod, class_type, enclosing
- enclosing.modules_hash.delete mod.name
-
- klass = RDoc::ClassModule.from_module class_type, mod
-
- # if it was there, then we keep it even if done_documenting
- RDoc::TopLevel.classes_hash[mod.full_name] = klass
- enclosing.classes_hash[mod.name] = klass
-
- klass
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/cross_reference.rb b/ruby_1_9_3/lib/rdoc/cross_reference.rb
deleted file mode 100644
index adeef2661a..0000000000
--- a/ruby_1_9_3/lib/rdoc/cross_reference.rb
+++ /dev/null
@@ -1,173 +0,0 @@
-##
-# RDoc::CrossReference is a reusable way to create cross references for names.
-
-class RDoc::CrossReference
-
- ##
- # Regular expression to match class references
- #
- # 1. There can be a '\\' in front of text to suppress the cross-reference
- # 2. There can be a '::' in front of class names to reference from the
- # top-level namespace.
- # 3. The method can be followed by parenthesis (not recommended)
-
- CLASS_REGEXP_STR = '\\\\?((?:\:{2})?[A-Z]\w*(?:\:\:\w+)*)'
-
- ##
- # Regular expression to match method references.
- #
- # See CLASS_REGEXP_STR
-
- METHOD_REGEXP_STR = '([a-z]\w*[!?=]?)(?:\([\w.+*/=<>-]*\))?'
-
- ##
- # Regular expressions matching text that should potentially have
- # cross-reference links generated are passed to add_special. Note that
- # these expressions are meant to pick up text for which cross-references
- # have been suppressed, since the suppression characters are removed by the
- # code that is triggered.
-
- CROSSREF_REGEXP = /(
- # A::B::C.meth
- #{CLASS_REGEXP_STR}(?:[.#]|::)#{METHOD_REGEXP_STR}
-
- # Stand-alone method (preceded by a #)
- | \\?\##{METHOD_REGEXP_STR}
-
- # Stand-alone method (preceded by ::)
- | ::#{METHOD_REGEXP_STR}
-
- # A::B::C
- # The stuff after CLASS_REGEXP_STR is a
- # nasty hack. CLASS_REGEXP_STR unfortunately matches
- # words like dog and cat (these are legal "class"
- # names in Fortran 95). When a word is flagged as a
- # potential cross-reference, limitations in the markup
- # engine suppress other processing, such as typesetting.
- # This is particularly noticeable for contractions.
- # In order that words like "can't" not
- # be flagged as potential cross-references, only
- # flag potential class cross-references if the character
- # after the cross-reference is a space, sentence
- # punctuation, tag start character, or attribute
- # marker.
- | #{CLASS_REGEXP_STR}(?=[\s\)\.\?\!\,\;<\000]|\z)
-
- # Things that look like filenames
- # The key thing is that there must be at least
- # one special character (period, slash, or
- # underscore).
- | (?:\.\.\/)*[-\/\w]+[_\/\.][-\w\/\.]+
-
- # Things that have markup suppressed
- # Don't process things like '\<' in \<tt>, though.
- # TODO: including < is a hack, not very satisfying.
- | \\[^\s<]
- )/x
-
- ##
- # Version of CROSSREF_REGEXP used when <tt>--hyperlink-all</tt> is specified.
-
- ALL_CROSSREF_REGEXP = /(
- # A::B::C.meth
- #{CLASS_REGEXP_STR}(?:[.#]|::)#{METHOD_REGEXP_STR}
-
- # Stand-alone method
- | \\?#{METHOD_REGEXP_STR}
-
- # A::B::C
- | #{CLASS_REGEXP_STR}(?=[\s\)\.\?\!\,\;<\000]|\z)
-
- # Things that look like filenames
- | (?:\.\.\/)*[-\/\w]+[_\/\.][-\w\/\.]+
-
- # Things that have markup suppressed
- | \\[^\s<]
- )/x
-
- attr_accessor :seen
-
- ##
- # Allows cross-references to be created based on the given +context+
- # (RDoc::Context).
-
- def initialize context
- @context = context
-
- @seen = {}
- end
-
- ##
- # Returns a reference to +name+.
- #
- # If the reference is found and +name+ is not documented +text+ will be
- # returned. If +name+ is escaped +name+ is returned. If +name+ is not
- # found +text+ is returned.
-
- def resolve name, text
- return @seen[name] if @seen.include? name
-
- # Find class, module, or method in class or module.
- #
- # Do not, however, use an if/elsif/else chain to do so. Instead, test
- # each possible pattern until one matches. The reason for this is that a
- # string like "YAML.txt" could be the txt() class method of class YAML (in
- # which case it would match the first pattern, which splits the string
- # into container and method components and looks up both) or a filename
- # (in which case it would match the last pattern, which just checks
- # whether the string as a whole is a known symbol).
-
- if /#{CLASS_REGEXP_STR}([.#]|::)#{METHOD_REGEXP_STR}/o =~ name then
- type = $2
- type = '' if type == '.' # will find either #method or ::method
- method = "#{type}#{$3}"
- container = @context.find_symbol_module($1)
- elsif /^([.#]|::)#{METHOD_REGEXP_STR}/o =~ name then
- type = $1
- type = '' if type == '.'
- method = "#{type}#{$2}"
- container = @context
- else
- container = nil
- end
-
- if container then
- ref = container.find_local_symbol method
-
- unless ref || RDoc::TopLevel === container then
- ref = container.find_ancestor_local_symbol method
- end
- end
-
- ref = case name
- when /^\\(#{CLASS_REGEXP_STR})$/o then
- ref = @context.find_symbol $1
- else
- ref = @context.find_symbol name
- end unless ref
-
- ref = nil if RDoc::Alias === ref # external alias: can't link to it
-
- out = if name == '\\' then
- name
- elsif name =~ /^\\/ then
- # we remove the \ only in front of what we know:
- # other backslashes are treated later, only outside of <tt>
- ref ? $' : name
- elsif ref then
- if ref.display? then
- ref
- else
- text
- end
- else
- text
- end
-
- @seen[name] = out
-
- out
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/encoding.rb b/ruby_1_9_3/lib/rdoc/encoding.rb
deleted file mode 100644
index ab752ee665..0000000000
--- a/ruby_1_9_3/lib/rdoc/encoding.rb
+++ /dev/null
@@ -1,92 +0,0 @@
-# coding: US-ASCII
-
-require 'rdoc'
-
-##
-# This class is a wrapper around File IO and Encoding that helps RDoc load
-# files and convert them to the correct encoding.
-
-module RDoc::Encoding
-
- ##
- # Reads the contents of +filename+ and handles any encoding directives in
- # the file.
- #
- # The content will be converted to the +encoding+. If the file cannot be
- # converted a warning will be printed and nil will be returned.
- #
- # If +force_transcode+ is true the document will be transcoded and any
- # unknown character in the target encoding will be replaced with '?'
-
- def self.read_file filename, encoding, force_transcode = false
- content = open filename, "rb" do |f| f.read end
- content.gsub!("\r\n", "\n") if RUBY_PLATFORM =~ /mswin|mingw/
-
- utf8 = content.sub!(/\A\xef\xbb\xbf/, '')
-
- RDoc::Encoding.set_encoding content
-
- if Object.const_defined? :Encoding then
- encoding ||= Encoding.default_external
- orig_encoding = content.encoding
-
- if utf8 then
- content.force_encoding Encoding::UTF_8
- content.encode! encoding
- else
- # assume the content is in our output encoding
- content.force_encoding encoding
- end
-
- unless content.valid_encoding? then
- # revert and try to transcode
- content.force_encoding orig_encoding
- content.encode! encoding
- end
-
- unless content.valid_encoding? then
- warn "unable to convert #{filename} to #{encoding}, skipping"
- content = nil
- end
- end
-
- content
- rescue ArgumentError => e
- raise unless e.message =~ /unknown encoding name - (.*)/
- warn "unknown encoding name \"#{$1}\" for #{filename}, skipping"
- nil
- rescue Encoding::UndefinedConversionError => e
- if force_transcode then
- content.force_encoding orig_encoding
- content.encode! encoding, :undef => :replace, :replace => '?'
- content
- else
- warn "unable to convert #{e.message} for #{filename}, skipping"
- nil
- end
- rescue Errno::EISDIR, Errno::ENOENT
- nil
- end
-
- ##
- # Sets the encoding of +string+ based on the magic comment
-
- def self.set_encoding string
- first_line = string[/\A(?:#!.*\n)?.*\n/]
-
- name = case first_line
- when /^<\?xml[^?]*encoding=(["'])(.*?)\1/ then $2
- when /\b(?:en)?coding[=:]\s*([^\s;]+)/i then $1
- else return
- end
-
- string.sub! first_line, ''
-
- return unless Object.const_defined? :Encoding
-
- enc = Encoding.find name
- string.force_encoding enc if enc
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/erbio.rb b/ruby_1_9_3/lib/rdoc/erbio.rb
deleted file mode 100644
index 04a89fbd34..0000000000
--- a/ruby_1_9_3/lib/rdoc/erbio.rb
+++ /dev/null
@@ -1,37 +0,0 @@
-require 'erb'
-
-##
-# A subclass of ERB that writes directly to an IO. Credit to Aaron Patterson
-# and Masatoshi SEKI.
-#
-# To use:
-#
-# erbio = RDoc::ERBIO.new '<%= "hello world" %>', nil, nil
-#
-# open 'hello.txt', 'w' do |io|
-# erbio.result binding
-# end
-#
-# Note that binding must enclose the io you wish to output on.
-
-class RDoc::ERBIO < ERB
-
- ##
- # Defaults +eoutvar+ to 'io', otherwise is identical to ERB's initialize
-
- def initialize str, safe_level = nil, trim_mode = nil, eoutvar = 'io'
- super
- end
-
- ##
- # Instructs +compiler+ how to write to +io_variable+
-
- def set_eoutvar compiler, io_variable
- compiler.put_cmd = "#{io_variable}.write"
- compiler.insert_cmd = "#{io_variable}.write"
- compiler.pre_cmd = []
- compiler.post_cmd = []
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/generator.rb b/ruby_1_9_3/lib/rdoc/generator.rb
deleted file mode 100644
index 2fa891f533..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator.rb
+++ /dev/null
@@ -1,40 +0,0 @@
-require 'rdoc'
-
-##
-# RDoc uses generators to turn parsed source code in the form of an
-# RDoc::CodeObject tree into some form of output. RDoc comes with the HTML
-# generator RDoc::Generator::Darkfish and an ri data generator
-# RDoc::Generator::RI.
-#
-# = Registering a Generator
-#
-# Generators are registered by calling RDoc::RDoc.add_generator with the class
-# of the generator:
-#
-# class My::Awesome::Generator
-# RDoc::RDoc.add_generator self
-# end
-#
-# = Adding Options to +rdoc+
-#
-# Before option processing in +rdoc+, RDoc::Options will call ::setup_options
-# on the generator class with an RDoc::Options instance. The generator can
-# use RDoc::Options#option_parser to add command-line options to the +rdoc+
-# tool. See OptionParser for details on how to add options.
-#
-# You can extend the RDoc::Options instance with additional accessors for your
-# generator.
-#
-# = Generator Instantiation
-#
-# After parsing, RDoc::RDoc will instantiate a generator by calling
-# #initialize with an RDoc::Options instance.
-#
-# RDoc will then call #generate on the generator instance and pass in an Array
-# of RDoc::TopLevel instances, each representing a parsed file. You can use
-# the various class methods on RDoc::TopLevel and in the RDoc::CodeObject tree
-# to create your desired output format.
-
-module RDoc::Generator
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/generator/darkfish.rb b/ruby_1_9_3/lib/rdoc/generator/darkfish.rb
deleted file mode 100644
index a3ffea0ce8..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/darkfish.rb
+++ /dev/null
@@ -1,390 +0,0 @@
-# -*- mode: ruby; ruby-indent-level: 2; tab-width: 2 -*-
-
-require 'pathname'
-require 'fileutils'
-require 'rdoc/erbio'
-
-require 'rdoc/generator/markup'
-
-##
-# Darkfish RDoc HTML Generator
-#
-# $Id: darkfish.rb 52 2009-01-07 02:08:11Z deveiant $
-#
-# == Author/s
-# * Michael Granger (ged@FaerieMUD.org)
-#
-# == Contributors
-# * Mahlon E. Smith (mahlon@martini.nu)
-# * Eric Hodel (drbrain@segment7.net)
-#
-# == License
-#
-# Copyright (c) 2007, 2008, Michael Granger. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are met:
-#
-# * Redistributions of source code must retain the above copyright notice,
-# this list of conditions and the following disclaimer.
-#
-# * Redistributions in binary form must reproduce the above copyright notice,
-# this list of conditions and the following disclaimer in the documentation
-# and/or other materials provided with the distribution.
-#
-# * Neither the name of the author/s, nor the names of the project's
-# contributors may be used to endorse or promote products derived from this
-# software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
-# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-class RDoc::Generator::Darkfish
-
- RDoc::RDoc.add_generator self
-
- include ERB::Util
-
- # Path to this file's parent directory. Used to find templates and other
- # resources.
-
- GENERATOR_DIR = File.join 'rdoc', 'generator'
-
- ##
- # Release Version
-
- VERSION = '2'
-
- ##
- # Description of this generator
-
- DESCRIPTION = 'HTML generator, written by Michael Granger'
-
- ##
- # Initialize a few instance variables before we start
-
- def initialize options
- @options = options
-
- @template_dir = Pathname.new options.template_dir
- @template_cache = {}
-
- @files = nil
- @classes = nil
-
- @basedir = Pathname.pwd.expand_path
- end
-
- ##
- # The output directory
-
- attr_reader :outputdir
-
- ##
- # Output progress information if debugging is enabled
-
- def debug_msg *msg
- return unless $DEBUG_RDOC
- $stderr.puts(*msg)
- end
-
- ##
- # Directory where generated class HTML files live relative to the output
- # dir.
-
- def class_dir
- nil
- end
-
- ##
- # Directory where generated class HTML files live relative to the output
- # dir.
-
- def file_dir
- nil
- end
-
- ##
- # Create the directories the generated docs will live in if they don't
- # already exist.
-
- def gen_sub_directories
- @outputdir.mkpath
- end
-
- ##
- # Copy over the stylesheet into the appropriate place in the output
- # directory.
-
- def write_style_sheet
- debug_msg "Copying static files"
- options = { :verbose => $DEBUG_RDOC, :noop => @options.dry_run }
-
- FileUtils.cp @template_dir + 'rdoc.css', '.', options
-
- Dir[(@template_dir + "{js,images}/**/*").to_s].each do |path|
- next if File.directory? path
- next if File.basename(path) =~ /^\./
-
- dst = Pathname.new(path).relative_path_from @template_dir
-
- # I suck at glob
- dst_dir = dst.dirname
- FileUtils.mkdir_p dst_dir, options unless File.exist? dst_dir
-
- FileUtils.cp @template_dir + path, dst, options
- end
- end
-
- ##
- # Build the initial indices and output objects based on an array of TopLevel
- # objects containing the extracted information.
-
- def generate top_levels
- @outputdir = Pathname.new(@options.op_dir).expand_path(@basedir)
-
- @files = top_levels.sort
- @classes = RDoc::TopLevel.all_classes_and_modules.sort
- @methods = @classes.map { |m| m.method_list }.flatten.sort
- @modsort = get_sorted_module_list(@classes)
-
- # Now actually write the output
- write_style_sheet
- generate_index
- generate_class_files
- generate_file_files
-
- rescue => e
- debug_msg "%s: %s\n %s" % [
- e.class.name, e.message, e.backtrace.join("\n ")
- ]
-
- raise
- end
-
- protected
-
- ##
- # Return a list of the documented modules sorted by salience first, then
- # by name.
-
- def get_sorted_module_list(classes)
- nscounts = classes.inject({}) do |counthash, klass|
- top_level = klass.full_name.gsub(/::.*/, '')
- counthash[top_level] ||= 0
- counthash[top_level] += 1
-
- counthash
- end
-
- # Sort based on how often the top level namespace occurs, and then on the
- # name of the module -- this works for projects that put their stuff into
- # a namespace, of course, but doesn't hurt if they don't.
- classes.sort_by do |klass|
- top_level = klass.full_name.gsub( /::.*/, '' )
- [nscounts[top_level] * -1, klass.full_name]
- end.select do |klass|
- klass.display?
- end
- end
-
- ##
- # Generate an index page which lists all the classes which are documented.
-
- def generate_index
- template_file = @template_dir + 'index.rhtml'
- return unless template_file.exist?
-
- debug_msg "Rendering the index page..."
-
- out_file = @basedir + @options.op_dir + 'index.html'
-
- render_template template_file, out_file do |io| binding end
- rescue => e
- error = RDoc::Error.new \
- "error generating index.html: #{e.message} (#{e.class})"
- error.set_backtrace e.backtrace
-
- raise error
- end
-
- ##
- # Generate a documentation file for each class
-
- def generate_class_files
- template_file = @template_dir + 'classpage.rhtml'
- return unless template_file.exist?
- debug_msg "Generating class documentation in #{@outputdir}"
-
- current = nil
-
- @classes.each do |klass|
- current = klass
- debug_msg " working on %s (%s)" % [klass.full_name, klass.path]
- out_file = @outputdir + klass.path
- # suppress 1.9.3 warning
- rel_prefix = rel_prefix = @outputdir.relative_path_from(out_file.dirname)
- svninfo = svninfo = self.get_svninfo(klass)
-
- debug_msg " rendering #{out_file}"
- render_template template_file, out_file do |io| binding end
- end
- rescue => e
- error = RDoc::Error.new \
- "error generating #{current.path}: #{e.message} (#{e.class})"
- error.set_backtrace e.backtrace
-
- raise error
- end
-
- ##
- # Generate a documentation file for each file
-
- def generate_file_files
- template_file = @template_dir + 'filepage.rhtml'
- return unless template_file.exist?
- debug_msg "Generating file documentation in #{@outputdir}"
-
- out_file = nil
-
- @files.each do |file|
- out_file = @outputdir + file.path
- debug_msg " working on %s (%s)" % [file.full_name, out_file]
- # suppress 1.9.3 warning
- rel_prefix = rel_prefix = @outputdir.relative_path_from(out_file.dirname)
-
- debug_msg " rendering #{out_file}"
- render_template template_file, out_file do |io| binding end
- end
- rescue => e
- error =
- RDoc::Error.new "error generating #{out_file}: #{e.message} (#{e.class})"
- error.set_backtrace e.backtrace
-
- raise error
- end
-
- ##
- # Return a string describing the amount of time in the given number of
- # seconds in terms a human can understand easily.
-
- def time_delta_string seconds
- return 'less than a minute' if seconds < 60
- return "#{seconds / 60} minute#{seconds / 60 == 1 ? '' : 's'}" if
- seconds < 3000 # 50 minutes
- return 'about one hour' if seconds < 5400 # 90 minutes
- return "#{seconds / 3600} hours" if seconds < 64800 # 18 hours
- return 'one day' if seconds < 86400 # 1 day
- return 'about one day' if seconds < 172800 # 2 days
- return "#{seconds / 86400} days" if seconds < 604800 # 1 week
- return 'about one week' if seconds < 1209600 # 2 week
- return "#{seconds / 604800} weeks" if seconds < 7257600 # 3 months
- return "#{seconds / 2419200} months" if seconds < 31536000 # 1 year
- return "#{seconds / 31536000} years"
- end
-
- # %q$Id: darkfish.rb 52 2009-01-07 02:08:11Z deveiant $"
- SVNID_PATTERN = /
- \$Id:\s
- (\S+)\s # filename
- (\d+)\s # rev
- (\d{4}-\d{2}-\d{2})\s # Date (YYYY-MM-DD)
- (\d{2}:\d{2}:\d{2}Z)\s # Time (HH:MM:SSZ)
- (\w+)\s # committer
- \$$
- /x
-
- ##
- # Try to extract Subversion information out of the first constant whose
- # value looks like a subversion Id tag. If no matching constant is found,
- # and empty hash is returned.
-
- def get_svninfo klass
- constants = klass.constants or return {}
-
- constants.find { |c| c.value =~ SVNID_PATTERN } or return {}
-
- filename, rev, date, time, committer = $~.captures
- commitdate = Time.parse "#{date} #{time}"
-
- return {
- :filename => filename,
- :rev => Integer(rev),
- :commitdate => commitdate,
- :commitdelta => time_delta_string(Time.now - commitdate),
- :committer => committer,
- }
- end
-
- ##
- # Load and render the erb template in the given +template_file+ and write
- # it out to +out_file+.
- #
- # Both +template_file+ and +out_file+ should be Pathname-like objects.
- #
- # An io will be yielded which must be captured by binding in the caller.
-
- def render_template template_file, out_file # :yield: io
- template = template_for template_file
-
- unless @options.dry_run then
- debug_msg "Outputting to %s" % [out_file.expand_path]
-
- out_file.dirname.mkpath
- out_file.open 'w', 0644 do |io|
- io.set_encoding @options.encoding if Object.const_defined? :Encoding
-
- context = yield io
-
- template_result template, context, template_file
- end
- else
- context = yield nil
-
- output = template_result template, context, template_file
-
- debug_msg " would have written %d characters to %s" % [
- output.length, out_file.expand_path
- ]
- end
- end
-
- ##
- # Creates the result for +template+ with +context+. If an error is raised a
- # Pathname +template_file+ will indicate the file where the error occurred.
-
- def template_result template, context, template_file
- template.filename = template_file.to_s
- template.result context
- rescue NoMethodError => e
- raise RDoc::Error, "Error while evaluating %s: %s" % [
- template_file.expand_path,
- e.message,
- ], e.backtrace
- end
-
- ##
- # Retrieves a cache template for +file+, if present, or fills the cache.
-
- def template_for file
- template = @template_cache[file]
-
- return template if template
-
- klass = @options.dry_run ? ERB : RDoc::ERBIO
-
- template = klass.new file.read, nil, '<>'
- @template_cache[file] = template
- template
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/generator/markup.rb b/ruby_1_9_3/lib/rdoc/generator/markup.rb
deleted file mode 100644
index c267bb1c13..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/markup.rb
+++ /dev/null
@@ -1,208 +0,0 @@
-# This file is loaded by generators. It allows RDoc's CodeObject tree to
-# avoid loading generator code to increase startup time (for ri).
-
-require 'rdoc/text'
-require 'rdoc/code_objects'
-require 'rdoc/generator'
-require 'rdoc/markup/to_html_crossref'
-require 'rdoc/ruby_token'
-
-##
-# Handle common RDoc::Markup tasks for various CodeObjects
-
-module RDoc::Generator::Markup
-
- ##
- # Generates a relative URL from this object's path to +target_path+
-
- def aref_to(target_path)
- RDoc::Markup::ToHtml.gen_relative_url path, target_path
- end
-
- ##
- # Generates a relative URL from +from_path+ to this object's path
-
- def as_href(from_path)
- RDoc::Markup::ToHtml.gen_relative_url from_path, path
- end
-
- ##
- # Handy wrapper for marking up this object's comment
-
- def description
- markup @comment
- end
-
- ##
- # Creates an RDoc::Markup::ToHtmlCrossref formatter
-
- def formatter
- return @formatter if defined? @formatter
-
- show_hash = RDoc::RDoc.current.options.show_hash
- hyperlink_all = RDoc::RDoc.current.options.hyperlink_all
- this = RDoc::Context === self ? self : @parent
-
- @formatter = RDoc::Markup::ToHtmlCrossref.new(this.path, this, show_hash,
- hyperlink_all)
- end
-
- ##
- # Build a webcvs URL starting for the given +url+ with +full_path+ appended
- # as the destination path. If +url+ contains '%s' +full_path+ will be
- # sprintf'd into +url+ instead.
-
- def cvs_url(url, full_path)
- if /%s/ =~ url then
- sprintf url, full_path
- else
- url + full_path
- end
- end
-
-end
-
-class RDoc::AnyMethod
-
- include RDoc::Generator::Markup
-
- @add_line_numbers = false
-
- class << self
- ##
- # Allows controlling whether <tt>#markup_code</tt> adds line numbers to
- # the source code.
-
- attr_accessor :add_line_numbers
- end
-
- ##
- # Prepend +src+ with line numbers. Relies on the first line of a source
- # code listing having:
- #
- # # File xxxxx, line dddd
- #
- # If it has, line numbers are added an ', line dddd' is removed.
-
- def add_line_numbers(src)
- return unless src.sub!(/\A(.*)(, line (\d+))/, '\1')
- first = $3.to_i - 1
- last = first + src.count("\n")
- size = last.to_s.length
-
- line = first
- src.gsub!(/^/) do
- res = if line == first then
- " " * (size + 1)
- else
- "<span class=\"line-num\">%2$*1$d</span> " % [size, line]
- end
-
- line += 1
- res
- end
- end
-
- ##
- # Turns the method's token stream into HTML.
- #
- # Prepends line numbers if +add_line_numbers+ is true.
-
- def markup_code
- return '' unless @token_stream
-
- src = ""
-
- @token_stream.each do |t|
- next unless t
-
- style = case t
- when RDoc::RubyToken::TkCONSTANT then 'ruby-constant'
- when RDoc::RubyToken::TkKW then 'ruby-keyword'
- when RDoc::RubyToken::TkIVAR then 'ruby-ivar'
- when RDoc::RubyToken::TkOp then 'ruby-operator'
- when RDoc::RubyToken::TkId then 'ruby-identifier'
- when RDoc::RubyToken::TkNode then 'ruby-node'
- when RDoc::RubyToken::TkCOMMENT then 'ruby-comment'
- when RDoc::RubyToken::TkREGEXP then 'ruby-regexp'
- when RDoc::RubyToken::TkSTRING then 'ruby-string'
- when RDoc::RubyToken::TkVal then 'ruby-value'
- end
-
- text = CGI.escapeHTML t.text
-
- if style then
- src << "<span class=\"#{style}\">#{text}</span>"
- else
- src << text
- end
- end
-
- # dedent the source
- indent = src.length
- lines = src.lines.to_a
- lines.shift if src =~ /\A.*#\ *File/i # remove '# File' comment
- lines.each do |line|
- if line =~ /^ *(?=\S)/
- n = $&.length
- indent = n if n < indent
- break if n == 0
- end
- end
- src.gsub!(/^#{' ' * indent}/, '') if indent > 0
-
- add_line_numbers(src) if self.class.add_line_numbers
-
- src
- end
-
-end
-
-class RDoc::Attr
-
- include RDoc::Generator::Markup
-
-end
-
-class RDoc::Alias
-
- include RDoc::Generator::Markup
-
-end
-
-class RDoc::Constant
-
- include RDoc::Generator::Markup
-
-end
-
-class RDoc::Context
-
- include RDoc::Generator::Markup
-
-end
-
-class RDoc::Context::Section
-
- include RDoc::Generator::Markup
-
-end
-
-class RDoc::TopLevel
-
- ##
- # Returns a URL for this source file on some web repository. Use the -W
- # command line option to set.
-
- def cvs_url
- url = RDoc::RDoc.current.options.webcvs
-
- if /%s/ =~ url then
- url % @absolute_name
- else
- url + @absolute_name
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/generator/ri.rb b/ruby_1_9_3/lib/rdoc/generator/ri.rb
deleted file mode 100644
index 939a165cfb..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/ri.rb
+++ /dev/null
@@ -1,86 +0,0 @@
-require 'rdoc/generator'
-require 'rdoc/ri'
-
-##
-# Generates ri data files
-
-class RDoc::Generator::RI
-
- RDoc::RDoc.add_generator self
-
- ##
- # Description of this generator
-
- DESCRIPTION = 'creates ri data files'
-
- ##
- # Set up a new ri generator
-
- def initialize options #:not-new:
- @options = options
- @old_siginfo = nil
- @current = nil
-
- @store = RDoc::RI::Store.new '.'
- @store.dry_run = @options.dry_run
- @store.encoding = @options.encoding if @options.respond_to? :encoding
- end
-
- ##
- # Build the initial indices and output objects based on an array of TopLevel
- # objects containing the extracted information.
-
- def generate top_levels
- install_siginfo_handler
-
- @store.load_cache
-
- RDoc::TopLevel.all_classes_and_modules.each do |klass|
- @current = "#{klass.class}: #{klass.full_name}"
-
- @store.save_class klass
-
- klass.each_method do |method|
- @current = "#{method.class}: #{method.full_name}"
- @store.save_method klass, method
- end
-
- klass.each_attribute do |attribute|
- @store.save_method klass, attribute
- end
- end
-
- @current = 'saving cache'
-
- @store.save_cache
-
- ensure
- @current = nil
-
- remove_siginfo_handler
- end
-
- ##
- # Installs a siginfo handler that prints the current filename.
-
- def install_siginfo_handler
- return unless Signal.list.key? 'INFO'
-
- @old_siginfo = trap 'INFO' do
- puts @current if @current
- end
- end
-
- ##
- # Removes a siginfo handler and replaces the previous
-
- def remove_siginfo_handler
- return unless Signal.list.key? 'INFO'
-
- handler = @old_siginfo || 'DEFAULT'
-
- trap 'INFO', handler
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/.document b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/.document
deleted file mode 100644
index e69de29bb2..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/.document
+++ /dev/null
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/classpage.rhtml b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/classpage.rhtml
deleted file mode 100644
index 9c74cacf0f..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/classpage.rhtml
+++ /dev/null
@@ -1,321 +0,0 @@
-<?xml version="1.0" encoding="<%= @options.charset %>"?>
-<!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>
- <meta content="text/html; charset=<%= @options.charset %>" http-equiv="Content-Type" />
-
- <title><%= klass.type.capitalize %>: <%= klass.full_name %></title>
-
- <link rel="stylesheet" href="<%= rel_prefix %>/rdoc.css" type="text/css" media="screen" />
-
- <script src="<%= rel_prefix %>/js/jquery.js" type="text/javascript" charset="utf-8"></script>
- <script src="<%= rel_prefix %>/js/thickbox-compressed.js" type="text/javascript" charset="utf-8"></script>
- <script src="<%= rel_prefix %>/js/quicksearch.js" type="text/javascript" charset="utf-8"></script>
- <script src="<%= rel_prefix %>/js/darkfish.js" type="text/javascript" charset="utf-8"></script>
-
-</head>
-<body id="top" class="<%= klass.type %>">
-
- <div id="metadata">
- <div id="home-metadata">
- <div id="home-section" class="section">
- <h3 class="section-header">
- <a href="<%= rel_prefix %>/index.html">Home</a>
- <a href="<%= rel_prefix %>/index.html#classes">Classes</a>
- <a href="<%= rel_prefix %>/index.html#methods">Methods</a>
- </h3>
- </div>
- </div>
-
- <div id="file-metadata">
- <div id="file-list-section" class="section">
- <h3 class="section-header">In Files</h3>
- <div class="section-body">
- <ul>
- <% klass.in_files.each do |tl| %>
- <li><a href="<%= rel_prefix %>/<%= h tl.path %>?TB_iframe=true&amp;height=550&amp;width=785"
- class="thickbox" title="<%= h tl.absolute_name %>"><%= h tl.absolute_name %></a></li>
- <% end %>
- </ul>
- </div>
- </div>
-
- <% if !svninfo.empty? then %>
- <div id="file-svninfo-section" class="section">
- <h3 class="section-header">Subversion Info</h3>
- <div class="section-body">
- <dl class="svninfo">
- <dt>Rev</dt>
- <dd><%= svninfo[:rev] %></dd>
-
- <dt>Last Checked In</dt>
- <dd><%= svninfo[:commitdate].strftime('%Y-%m-%d %H:%M:%S') %>
- (<%= svninfo[:commitdelta] %> ago)</dd>
-
- <dt>Checked in by</dt>
- <dd><%= svninfo[:committer] %></dd>
- </dl>
- </div>
- </div>
- <% end %>
- </div>
-
- <div id="class-metadata">
- <% if klass.type == 'class' then %>
- <!-- Parent Class -->
- <div id="parent-class-section" class="section">
- <h3 class="section-header">Parent</h3>
- <% if klass.superclass and not String === klass.superclass then %>
- <p class="link"><a href="<%= klass.aref_to klass.superclass.path %>"><%= klass.superclass.full_name %></a></p>
- <% else %>
- <p class="link"><%= klass.superclass %></p>
- <% end %>
- </div>
- <% end %>
-
- <% unless klass.sections.length == 1 then %>
- <!-- Sections -->
- <div id="sections-section" class="section">
- <h3 class="section-header">Sections</h3>
- <ul class="link-list">
- <% klass.sections.sort_by { |s| s.title.to_s }.each do |section| %>
- <li><a href="#<%= section.aref %>"><%= h section.title %></a></li>
- <% end %>
- </ul>
- </div>
- <% end %>
-
- <% unless klass.classes_and_modules.empty? then %>
- <!-- Namespace Contents -->
- <div id="namespace-list-section" class="section">
- <h3 class="section-header">Namespace</h3>
- <ul class="link-list">
- <% (klass.modules.sort + klass.classes.sort).each do |mod| %>
- <li><span class="type"><%= mod.type.upcase %></span> <a href="<%= klass.aref_to mod.path %>"><%= mod.full_name %></a></li>
- <% end %>
- </ul>
- </div>
- <% end %>
-
- <% unless klass.method_list.empty? then %>
- <!-- Method Quickref -->
- <div id="method-list-section" class="section">
- <h3 class="section-header">Methods</h3>
- <ul class="link-list">
- <% klass.each_method do |meth| %>
- <li><a href="#<%= meth.aref %>"><%= meth.singleton ? '::' : '#' %><%= meth.name %></a></li>
- <% end %>
- </ul>
- </div>
- <% end %>
-
- <% unless klass.includes.empty? then %>
- <!-- Included Modules -->
- <div id="includes-section" class="section">
- <h3 class="section-header">Included Modules</h3>
- <ul class="link-list">
- <% klass.each_include do |inc| %>
- <% unless String === inc.module then %>
- <li><a class="include" href="<%= klass.aref_to inc.module.path %>"><%= inc.module.full_name %></a></li>
- <% else %>
- <li><span class="include"><%= inc.name %></span></li>
- <% end %>
- <% end %>
- </ul>
- </div>
- <% end %>
- </div>
-
- <div id="project-metadata">
- <% simple_files = @files.select {|tl| tl.parser == RDoc::Parser::Simple } %>
- <% unless simple_files.empty? then %>
- <div id="fileindex-section" class="section project-section">
- <h3 class="section-header">Files</h3>
- <ul>
- <% simple_files.each do |file| %>
- <li class="file"><a href="<%= rel_prefix %>/<%= file.path %>"><%= h file.base_name %></a></li>
- <% end %>
- </ul>
- </div>
- <% end %>
-
- <div id="classindex-section" class="section project-section">
- <h3 class="section-header">Class/Module Index
- <span class="search-toggle"><img src="<%= rel_prefix %>/images/find.png"
- height="16" width="16" alt="[+]"
- title="show/hide quicksearch" /></span></h3>
- <form action="#" method="get" accept-charset="utf-8" class="initially-hidden">
- <fieldset>
- <legend>Quicksearch</legend>
- <input type="text" name="quicksearch" value=""
- class="quicksearch-field" />
- </fieldset>
- </form>
-
- <ul class="link-list">
- <% @modsort.each do |index_klass| %>
- <li><a href="<%= rel_prefix %>/<%= index_klass.path %>"><%= index_klass.full_name %></a></li>
- <% end %>
- </ul>
- <div id="no-class-search-results" style="display: none;">No matching classes.</div>
- </div>
-
- <% if $DEBUG_RDOC then %>
- <div id="debugging-toggle"><img src="<%= rel_prefix %>/images/bug.png"
- alt="toggle debugging" height="16" width="16" /></div>
- <% end %>
- </div>
- </div>
-
- <div id="documentation">
- <h1 class="<%= klass.type %>"><%= klass.full_name %></h1>
-
- <div id="description" class="description">
- <%= klass.description %>
- </div><!-- description -->
-
- <% klass.each_section do |section, constants, attributes| %>
- <% constants = constants.select { |const| const.display? } %>
- <% attributes = attributes.select { |attr| attr.display? } %>
- <div id="<%= section.aref %>" class="documentation-section">
- <% if section.title then %>
- <h2 class="section-header">
- <%= section.title %>
- <a href="#top">&uarr; top</a>
- </h2>
- <% end %>
-
- <% if section.comment then %>
- <div class="description">
- <%= section.description %>
- </div>
- <% end %>
-
- <% unless constants.empty? then %>
- <!-- Constants -->
- <div id="constants-list" class="section">
- <h3 class="section-header">Constants</h3>
- <dl>
- <% constants.each do |const| %>
- <dt><a name="<%= const.name %>"><%= const.name %></a></dt>
- <% if const.comment then %>
- <dd class="description"><%= const.description.strip %></dd>
- <% else %>
- <dd class="description missing-docs">(Not documented)</dd>
- <% end %>
- <% end %>
- </dl>
- </div>
- <% end %>
-
- <% unless attributes.empty? then %>
- <!-- Attributes -->
- <div id="attribute-method-details" class="method-section section">
- <h3 class="section-header">Attributes</h3>
-
- <% attributes.each do |attrib| %>
- <div id="<%= attrib.html_name %>-attribute-method" class="method-detail">
- <a name="<%= h attrib.name %>"></a>
- <% if attrib.rw =~ /w/i then %>
- <a name="<%= h attrib.name %>="></a>
- <% end %>
- <div class="method-heading attribute-method-heading">
- <span class="method-name"><%= h attrib.name %></span><span
- class="attribute-access-type">[<%= attrib.rw %>]</span>
- </div>
-
- <div class="method-description">
- <% if attrib.comment then %>
- <%= attrib.description.strip %>
- <% else %>
- <p class="missing-docs">(Not documented)</p>
- <% end %>
- </div>
- </div>
- <% end %>
- </div><!-- attribute-method-details -->
- <% end %>
-
- <!-- Methods -->
- <% klass.methods_by_type(section).each do |type, visibilities|
- next if visibilities.empty?
- visibilities.each do |visibility, methods|
- next if methods.empty? %>
- <div id="<%= visibility %>-<%= type %>-method-details" class="method-section section">
- <h3 class="section-header"><%= visibility.to_s.capitalize %> <%= type.capitalize %> Methods</h3>
-
- <% methods.each do |method| %>
- <div id="<%= method.html_name %>-method" class="method-detail <%= method.is_alias_for ? "method-alias" : '' %>">
- <a name="<%= h method.aref %>"></a>
-
- <% if method.call_seq then %>
- <% method.call_seq.strip.split("\n").each_with_index do |call_seq, i| %>
- <div class="method-heading">
- <span class="method-callseq"><%= call_seq.strip.gsub(/->/, '&rarr;').gsub( /^\w+\./m, '') %></span>
- <% if i == 0 then %>
- <span class="method-click-advice">click to toggle source</span>
- <% end %>
- </div>
- <% end %>
- <% else %>
- <div class="method-heading">
- <span class="method-name"><%= h method.name %></span><span
- class="method-args"><%= method.params %></span>
- <span class="method-click-advice">click to toggle source</span>
- </div>
- <% end %>
-
- <div class="method-description">
- <% if method.comment then %>
- <%= method.description.strip %>
- <% else %>
- <p class="missing-docs">(Not documented)</p>
- <% end %>
-
- <% if method.token_stream then %>
- <div class="method-source-code" id="<%= method.html_name %>-source">
-<pre>
-<%= method.markup_code %>
-</pre>
- </div><!-- <%= method.html_name %>-source -->
- <% end %>
- </div>
-
- <% unless method.aliases.empty? then %>
- <div class="aliases">
- Also aliased as: <%= method.aliases.map do |aka|
- if aka.parent then # HACK lib/rexml/encodings
- %{<a href="#{klass.aref_to aka.path}">#{h aka.name}</a>}
- else
- h aka.name
- end
- end.join ", " %>
- </div>
- <% end %>
-
- <% if method.is_alias_for then %>
- <div class="aliases">
- Alias for: <a href="<%= klass.aref_to method.is_alias_for.path %>"><%= h method.is_alias_for.name %></a>
- </div>
- <% end %>
- </div><!-- <%= method.html_name %>-method -->
-
- <% end %>
- </div><!-- <%= visibility %>-<%= type %>-method-details -->
- <% end
- end %>
- </div><!-- <%= section.aref %> -->
- <% end %>
-
- </div><!-- documentation -->
-
- <div id="validator-badges">
- <p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
- <p><small>Generated with the <a href="http://deveiate.org/projects/Darkfish-Rdoc/">Darkfish
- Rdoc Generator</a> <%= RDoc::Generator::Darkfish::VERSION %></small>.</p>
- </div>
-
-</body>
-</html>
-
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/filepage.rhtml b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/filepage.rhtml
deleted file mode 100644
index b230a456a3..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/filepage.rhtml
+++ /dev/null
@@ -1,124 +0,0 @@
-<?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>
- <meta content="text/html; charset=<%= @options.charset %>" http-equiv="Content-Type" />
-
- <title>File: <%= file.base_name %> [<%= @options.title %>]</title>
-
- <link type="text/css" media="screen" href="<%= rel_prefix %>/rdoc.css" rel="stylesheet" />
-
- <script src="<%= rel_prefix %>/js/jquery.js" type="text/javascript"
- charset="utf-8"></script>
- <script src="<%= rel_prefix %>/js/thickbox-compressed.js" type="text/javascript"
- charset="utf-8"></script>
- <script src="<%= rel_prefix %>/js/quicksearch.js" type="text/javascript"
- charset="utf-8"></script>
- <script src="<%= rel_prefix %>/js/darkfish.js" type="text/javascript"
- charset="utf-8"></script>
-</head>
-
-<% if file.parser == RDoc::Parser::Simple %>
-<body class="file">
- <div id="metadata">
- <div id="home-metadata">
- <div id="home-section" class="section">
- <h3 class="section-header">
- <a href="<%= rel_prefix %>/index.html">Home</a>
- <a href="<%= rel_prefix %>/index.html#classes">Classes</a>
- <a href="<%= rel_prefix %>/index.html#methods">Methods</a>
- </h3>
- </div>
- </div>
-
- <div id="project-metadata">
- <% simple_files = @files.select { |f| f.parser == RDoc::Parser::Simple } %>
- <% unless simple_files.empty? then %>
- <div id="fileindex-section" class="section project-section">
- <h3 class="section-header">Files</h3>
- <ul>
- <% simple_files.each do |f| %>
- <li class="file"><a href="<%= rel_prefix %>/<%= f.path %>"><%= h f.base_name %></a></li>
- <% end %>
- </ul>
- </div>
- <% end %>
-
- <div id="classindex-section" class="section project-section">
- <h3 class="section-header">Class Index
- <span class="search-toggle"><img src="<%= rel_prefix %>/images/find.png"
- height="16" width="16" alt="[+]"
- title="show/hide quicksearch" /></span></h3>
- <form action="#" method="get" accept-charset="utf-8" class="initially-hidden">
- <fieldset>
- <legend>Quicksearch</legend>
- <input type="text" name="quicksearch" value=""
- class="quicksearch-field" />
- </fieldset>
- </form>
-
- <ul class="link-list">
- <% @modsort.each do |index_klass| %>
- <li><a href="<%= rel_prefix %>/<%= index_klass.path %>"><%= index_klass.full_name %></a></li>
- <% end %>
- </ul>
- <div id="no-class-search-results" style="display: none;">No matching classes.</div>
- </div>
-
- <% if $DEBUG_RDOC %>
- <div id="debugging-toggle"><img src="<%= rel_prefix %>/images/bug.png"
- alt="toggle debugging" height="16" width="16" /></div>
- <% end %>
- </div>
- </div>
-
- <div id="documentation">
- <%= file.description %>
- </div>
-
- <div id="validator-badges">
- <p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
- <p><small>Generated with the <a href="http://deveiate.org/projects/Darkfish-Rdoc/">Darkfish
- Rdoc Generator</a> <%= RDoc::Generator::Darkfish::VERSION %></small>.</p>
- </div>
-</body>
-<% else %>
-<body class="file file-popup">
- <div id="metadata">
- <dl>
- <dt class="modified-date">Last Modified</dt>
- <dd class="modified-date"><%= file.last_modified %></dd>
-
- <% if file.requires %>
- <dt class="requires">Requires</dt>
- <dd class="requires">
- <ul>
- <% file.requires.each do |require| %>
- <li><%= require.name %></li>
- <% end %>
- </ul>
- </dd>
- <% end %>
-
- <% if @options.webcvs %>
- <dt class="scs-url">Trac URL</dt>
- <dd class="scs-url"><a target="_top"
- href="<%= file.cvs_url %>"><%= file.cvs_url %></a></dd>
- <% end %>
- </dl>
- </div>
-
- <div id="documentation">
- <% if file.comment %>
- <div class="description">
- <h2>Description</h2>
- <%= file.description %>
- </div>
- <% end %>
- </div>
-</body>
-<% end %>
-</html>
-
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/brick.png b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/brick.png
deleted file mode 100644
index 7851cf34c9..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/brick.png
+++ /dev/null
Binary files differ
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/brick_link.png b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/brick_link.png
deleted file mode 100644
index 9ebf013a23..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/brick_link.png
+++ /dev/null
Binary files differ
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/bug.png b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/bug.png
deleted file mode 100644
index 2d5fb90ec6..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/bug.png
+++ /dev/null
Binary files differ
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/bullet_black.png b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/bullet_black.png
deleted file mode 100644
index 57619706d1..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/bullet_black.png
+++ /dev/null
Binary files differ
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/bullet_toggle_minus.png b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/bullet_toggle_minus.png
deleted file mode 100644
index b47ce55f68..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/bullet_toggle_minus.png
+++ /dev/null
Binary files differ
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/bullet_toggle_plus.png b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/bullet_toggle_plus.png
deleted file mode 100644
index 9ab4a89664..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/bullet_toggle_plus.png
+++ /dev/null
Binary files differ
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/date.png b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/date.png
deleted file mode 100644
index 783c83357f..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/date.png
+++ /dev/null
Binary files differ
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/find.png b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/find.png
deleted file mode 100644
index 1547479646..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/find.png
+++ /dev/null
Binary files differ
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/loadingAnimation.gif b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/loadingAnimation.gif
deleted file mode 100644
index 82290f4833..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/loadingAnimation.gif
+++ /dev/null
Binary files differ
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/macFFBgHack.png b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/macFFBgHack.png
deleted file mode 100644
index c6473b324e..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/macFFBgHack.png
+++ /dev/null
Binary files differ
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/package.png b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/package.png
deleted file mode 100644
index da3c2a2d74..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/package.png
+++ /dev/null
Binary files differ
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/page_green.png b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/page_green.png
deleted file mode 100644
index de8e003f9f..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/page_green.png
+++ /dev/null
Binary files differ
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/page_white_text.png b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/page_white_text.png
deleted file mode 100644
index 813f712f72..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/page_white_text.png
+++ /dev/null
Binary files differ
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/page_white_width.png b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/page_white_width.png
deleted file mode 100644
index 1eb880947d..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/page_white_width.png
+++ /dev/null
Binary files differ
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/plugin.png b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/plugin.png
deleted file mode 100644
index 6187b15aec..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/plugin.png
+++ /dev/null
Binary files differ
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/ruby.png b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/ruby.png
deleted file mode 100644
index f763a16880..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/ruby.png
+++ /dev/null
Binary files differ
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/tag_green.png b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/tag_green.png
deleted file mode 100644
index 83ec984bd7..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/tag_green.png
+++ /dev/null
Binary files differ
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/wrench.png b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/wrench.png
deleted file mode 100644
index 5c8213fef5..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/wrench.png
+++ /dev/null
Binary files differ
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/wrench_orange.png b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/wrench_orange.png
deleted file mode 100644
index 565a9330e0..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/wrench_orange.png
+++ /dev/null
Binary files differ
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/zoom.png b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/zoom.png
deleted file mode 100644
index 908612e394..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/images/zoom.png
+++ /dev/null
Binary files differ
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/index.rhtml b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/index.rhtml
deleted file mode 100644
index 3198246f8a..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/index.rhtml
+++ /dev/null
@@ -1,64 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
- "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
-
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
-<head>
- <meta content="text/html; charset=<%= @options.charset %>" http-equiv="Content-Type" />
-
- <title><%= h @options.title %></title>
-
- <link type="text/css" media="screen" href="rdoc.css" rel="stylesheet" />
-
- <script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
- <script src="js/thickbox-compressed.js" type="text/javascript" charset="utf-8"></script>
- <script src="js/quicksearch.js" type="text/javascript" charset="utf-8"></script>
- <script src="js/darkfish.js" type="text/javascript" charset="utf-8"></script>
-
-</head>
-<body class="indexpage">
-
- <% $stderr.sync = true %>
- <h1><%= h @options.title %></h1>
-
- <% if @options.main_page && main_page = @files.find { |f| f.full_name == @options.main_page } then %>
- <div id="main">
- <%= main_page.description.sub(%r{^\s*<h1.*?/h1>}i, '') %>
- </div>
- <% else %>
- <p>This is the API documentation for '<%= @options.title %>'.</p>
- <% end %>
-
- <% simple_files = @files.select {|tl| tl.parser == RDoc::Parser::Simple } %>
- <% unless simple_files.empty? then %>
- <h2>Files</h2>
- <ul>
- <% simple_files.sort.each do |file| %>
- <li class="file"><a href="<%= file.path %>"><%= h file.base_name %></a></li>
- <% end %>
- </ul>
- <% end %>
-
- <h2 id="classes">Classes/Modules</h2>
- <ul>
- <% @modsort.each do |klass| %>
- <li class="<%= klass.type %>"><a href="<%= klass.path %>"><%= klass.full_name %></a></li>
- <% end %>
- </ul>
-
- <h2 id="methods">Methods</h2>
- <ul>
- <% RDoc::TopLevel.all_classes_and_modules.map do |mod|
- mod.method_list
- end.flatten.sort.each do |method| %>
- <li><a href="<%= method.path %>"><%= method.pretty_name %> &mdash; <%= method.parent.full_name %></a></li>
- <% end %>
- </ul>
-
- <div id="validator-badges">
- <p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
- <p><small>Generated with the <a href="http://deveiate.org/projects/Darkfish-Rdoc/">Darkfish
- Rdoc Generator</a> <%= RDoc::Generator::Darkfish::VERSION %></small>.</p>
- </div>
-</body>
-</html>
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/js/darkfish.js b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/js/darkfish.js
deleted file mode 100644
index 7a2f44c765..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/js/darkfish.js
+++ /dev/null
@@ -1,118 +0,0 @@
-/**
- *
- * Darkfish Page Functions
- * $Id: darkfish.js 53 2009-01-07 02:52:03Z deveiant $
- *
- * Author: Michael Granger <mgranger@laika.com>
- *
- */
-
-/* Provide console simulation for firebug-less environments */
-if (!("console" in window) || !("firebug" in console)) {
- var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
- "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
-
- window.console = {};
- for (var i = 0; i < names.length; ++i)
- window.console[names[i]] = function() {};
-};
-
-
-/**
- * Unwrap the first element that matches the given @expr@ from the targets and return them.
- */
-$.fn.unwrap = function( expr ) {
- return this.each( function() {
- $(this).parents( expr ).eq( 0 ).after( this ).remove();
- });
-};
-
-
-function showSource( e ) {
- var target = e.target;
- var codeSections = $(target).
- parents('.method-detail').
- find('.method-source-code');
-
- $(target).
- parents('.method-detail').
- find('.method-source-code').
- slideToggle();
-};
-
-function hookSourceViews() {
- $('.method-description,.method-heading').click( showSource );
-};
-
-function toggleDebuggingSection() {
- $('.debugging-section').slideToggle();
-};
-
-function hookDebuggingToggle() {
- $('#debugging-toggle img').click( toggleDebuggingSection );
-};
-
-function hookQuickSearch() {
- $('.quicksearch-field').each( function() {
- var searchElems = $(this).parents('.section').find( 'li' );
- var toggle = $(this).parents('.section').find('h3 .search-toggle');
- // console.debug( "Toggle is: %o", toggle );
- var qsbox = $(this).parents('form').get( 0 );
-
- $(this).quicksearch( this, searchElems, {
- noSearchResultsIndicator: 'no-class-search-results',
- focusOnLoad: false
- });
- $(toggle).click( function() {
- // console.debug( "Toggling qsbox: %o", qsbox );
- $(qsbox).toggle();
- });
- });
-};
-
-function highlightTarget( anchor ) {
- console.debug( "Highlighting target '%s'.", anchor );
-
- $("a[name]").each( function() {
- if ( $(this).attr("name") == anchor ) {
- if ( !$(this).parent().parent().hasClass('target-section') ) {
- console.debug( "Wrapping the target-section" );
- $('div.method-detail').unwrap( 'div.target-section' );
- $(this).parent().wrap( '<div class="target-section"></div>' );
- } else {
- console.debug( "Already wrapped." );
- }
- }
- });
-};
-
-function highlightLocationTarget() {
- console.debug( "Location hash: %s", window.location.hash );
- if ( ! window.location.hash || window.location.hash.length == 0 ) return;
-
- var anchor = window.location.hash.substring(1);
- console.debug( "Found anchor: %s; matching %s", anchor, "a[name=" + anchor + "]" );
-
- highlightTarget( anchor );
-};
-
-function highlightClickTarget( event ) {
- console.debug( "Highlighting click target for event %o", event.target );
- try {
- var anchor = $(event.target).attr( 'href' ).substring(1);
- console.debug( "Found target anchor: %s", anchor );
- highlightTarget( anchor );
- } catch ( err ) {
- console.error( "Exception while highlighting: %o", err );
- };
-};
-
-
-$(document).ready( function() {
- hookSourceViews();
- hookDebuggingToggle();
- hookQuickSearch();
- highlightLocationTarget();
-
- $('ul.link-list a').bind( "click", highlightClickTarget );
-});
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/js/jquery.js b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/js/jquery.js
deleted file mode 100644
index afe9e74c90..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/js/jquery.js
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * jQuery 1.2.6 - New Wave Javascript
- *
- * Copyright (c) 2008 John Resig (jquery.com)
- * Dual licensed under the MIT (MIT-LICENSE.txt)
- * and GPL (GPL-LICENSE.txt) licenses.
- *
- * $Date: 2008-09-25 09:50:52 -0700 (Thu, 25 Sep 2008) $
- * $Rev: 38 $
- */
-(function(){var _jQuery=window.jQuery,_$=window.$;var jQuery=window.jQuery=window.$=function(selector,context){return new jQuery.fn.init(selector,context);};var quickExpr=/^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/,isSimple=/^.[^:#\[\.]*$/,undefined;jQuery.fn=jQuery.prototype={init:function(selector,context){selector=selector||document;if(selector.nodeType){this[0]=selector;this.length=1;return this;}if(typeof selector=="string"){var match=quickExpr.exec(selector);if(match&&(match[1]||!context)){if(match[1])selector=jQuery.clean([match[1]],context);else{var elem=document.getElementById(match[3]);if(elem){if(elem.id!=match[3])return jQuery().find(selector);return jQuery(elem);}selector=[];}}else
-return jQuery(context).find(selector);}else if(jQuery.isFunction(selector))return jQuery(document)[jQuery.fn.ready?"ready":"load"](selector);return this.setArray(jQuery.makeArray(selector));},jquery:"1.2.6",size:function(){return this.length;},length:0,get:function(num){return num==undefined?jQuery.makeArray(this):this[num];},pushStack:function(elems){var ret=jQuery(elems);ret.prevObject=this;return ret;},setArray:function(elems){this.length=0;Array.prototype.push.apply(this,elems);return this;},each:function(callback,args){return jQuery.each(this,callback,args);},index:function(elem){var ret=-1;return jQuery.inArray(elem&&elem.jquery?elem[0]:elem,this);},attr:function(name,value,type){var options=name;if(name.constructor==String)if(value===undefined)return this[0]&&jQuery[type||"attr"](this[0],name);else{options={};options[name]=value;}return this.each(function(i){for(name in options)jQuery.attr(type?this.style:this,name,jQuery.prop(this,options[name],type,i,name));});},css:function(key,value){if((key=='width'||key=='height')&&parseFloat(value)<0)value=undefined;return this.attr(key,value,"curCSS");},text:function(text){if(typeof text!="object"&&text!=null)return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(text));var ret="";jQuery.each(text||this,function(){jQuery.each(this.childNodes,function(){if(this.nodeType!=8)ret+=this.nodeType!=1?this.nodeValue:jQuery.fn.text([this]);});});return ret;},wrapAll:function(html){if(this[0])jQuery(html,this[0].ownerDocument).clone().insertBefore(this[0]).map(function(){var elem=this;while(elem.firstChild)elem=elem.firstChild;return elem;}).append(this);return this;},wrapInner:function(html){return this.each(function(){jQuery(this).contents().wrapAll(html);});},wrap:function(html){return this.each(function(){jQuery(this).wrapAll(html);});},append:function(){return this.domManip(arguments,true,false,function(elem){if(this.nodeType==1)this.appendChild(elem);});},prepend:function(){return this.domManip(arguments,true,true,function(elem){if(this.nodeType==1)this.insertBefore(elem,this.firstChild);});},before:function(){return this.domManip(arguments,false,false,function(elem){this.parentNode.insertBefore(elem,this);});},after:function(){return this.domManip(arguments,false,true,function(elem){this.parentNode.insertBefore(elem,this.nextSibling);});},end:function(){return this.prevObject||jQuery([]);},find:function(selector){var elems=jQuery.map(this,function(elem){return jQuery.find(selector,elem);});return this.pushStack(/[^+>] [^+>]/.test(selector)||selector.indexOf("..")>-1?jQuery.unique(elems):elems);},clone:function(events){var ret=this.map(function(){if(jQuery.browser.msie&&!jQuery.isXMLDoc(this)){var clone=this.cloneNode(true),container=document.createElement("div");container.appendChild(clone);return jQuery.clean([container.innerHTML])[0];}else
-return this.cloneNode(true);});var clone=ret.find("*").andSelf().each(function(){if(this[expando]!=undefined)this[expando]=null;});if(events===true)this.find("*").andSelf().each(function(i){if(this.nodeType==3)return;var events=jQuery.data(this,"events");for(var type in events)for(var handler in events[type])jQuery.event.add(clone[i],type,events[type][handler],events[type][handler].data);});return ret;},filter:function(selector){return this.pushStack(jQuery.isFunction(selector)&&jQuery.grep(this,function(elem,i){return selector.call(elem,i);})||jQuery.multiFilter(selector,this));},not:function(selector){if(selector.constructor==String)if(isSimple.test(selector))return this.pushStack(jQuery.multiFilter(selector,this,true));else
-selector=jQuery.multiFilter(selector,this);var isArrayLike=selector.length&&selector[selector.length-1]!==undefined&&!selector.nodeType;return this.filter(function(){return isArrayLike?jQuery.inArray(this,selector)<0:this!=selector;});},add:function(selector){return this.pushStack(jQuery.unique(jQuery.merge(this.get(),typeof selector=='string'?jQuery(selector):jQuery.makeArray(selector))));},is:function(selector){return!!selector&&jQuery.multiFilter(selector,this).length>0;},hasClass:function(selector){return this.is("."+selector);},val:function(value){if(value==undefined){if(this.length){var elem=this[0];if(jQuery.nodeName(elem,"select")){var index=elem.selectedIndex,values=[],options=elem.options,one=elem.type=="select-one";if(index<0)return null;for(var i=one?index:0,max=one?index+1:options.length;i<max;i++){var option=options[i];if(option.selected){value=jQuery.browser.msie&&!option.attributes.value.specified?option.text:option.value;if(one)return value;values.push(value);}}return values;}else
-return(this[0].value||"").replace(/\r/g,"");}return undefined;}if(value.constructor==Number)value+='';return this.each(function(){if(this.nodeType!=1)return;if(value.constructor==Array&&/radio|checkbox/.test(this.type))this.checked=(jQuery.inArray(this.value,value)>=0||jQuery.inArray(this.name,value)>=0);else if(jQuery.nodeName(this,"select")){var values=jQuery.makeArray(value);jQuery("option",this).each(function(){this.selected=(jQuery.inArray(this.value,values)>=0||jQuery.inArray(this.text,values)>=0);});if(!values.length)this.selectedIndex=-1;}else
-this.value=value;});},html:function(value){return value==undefined?(this[0]?this[0].innerHTML:null):this.empty().append(value);},replaceWith:function(value){return this.after(value).remove();},eq:function(i){return this.slice(i,i+1);},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments));},map:function(callback){return this.pushStack(jQuery.map(this,function(elem,i){return callback.call(elem,i,elem);}));},andSelf:function(){return this.add(this.prevObject);},data:function(key,value){var parts=key.split(".");parts[1]=parts[1]?"."+parts[1]:"";if(value===undefined){var data=this.triggerHandler("getData"+parts[1]+"!",[parts[0]]);if(data===undefined&&this.length)data=jQuery.data(this[0],key);return data===undefined&&parts[1]?this.data(parts[0]):data;}else
-return this.trigger("setData"+parts[1]+"!",[parts[0],value]).each(function(){jQuery.data(this,key,value);});},removeData:function(key){return this.each(function(){jQuery.removeData(this,key);});},domManip:function(args,table,reverse,callback){var clone=this.length>1,elems;return this.each(function(){if(!elems){elems=jQuery.clean(args,this.ownerDocument);if(reverse)elems.reverse();}var obj=this;if(table&&jQuery.nodeName(this,"table")&&jQuery.nodeName(elems[0],"tr"))obj=this.getElementsByTagName("tbody")[0]||this.appendChild(this.ownerDocument.createElement("tbody"));var scripts=jQuery([]);jQuery.each(elems,function(){var elem=clone?jQuery(this).clone(true)[0]:this;if(jQuery.nodeName(elem,"script"))scripts=scripts.add(elem);else{if(elem.nodeType==1)scripts=scripts.add(jQuery("script",elem).remove());callback.call(obj,elem);}});scripts.each(evalScript);});}};jQuery.fn.init.prototype=jQuery.fn;function evalScript(i,elem){if(elem.src)jQuery.ajax({url:elem.src,async:false,dataType:"script"});else
-jQuery.globalEval(elem.text||elem.textContent||elem.innerHTML||"");if(elem.parentNode)elem.parentNode.removeChild(elem);}function now(){return+new Date;}jQuery.extend=jQuery.fn.extend=function(){var target=arguments[0]||{},i=1,length=arguments.length,deep=false,options;if(target.constructor==Boolean){deep=target;target=arguments[1]||{};i=2;}if(typeof target!="object"&&typeof target!="function")target={};if(length==i){target=this;--i;}for(;i<length;i++)if((options=arguments[i])!=null)for(var name in options){var src=target[name],copy=options[name];if(target===copy)continue;if(deep&&copy&&typeof copy=="object"&&!copy.nodeType)target[name]=jQuery.extend(deep,src||(copy.length!=null?[]:{}),copy);else if(copy!==undefined)target[name]=copy;}return target;};var expando="jQuery"+now(),uuid=0,windowData={},exclude=/z-?index|font-?weight|opacity|zoom|line-?height/i,defaultView=document.defaultView||{};jQuery.extend({noConflict:function(deep){window.$=_$;if(deep)window.jQuery=_jQuery;return jQuery;},isFunction:function(fn){return!!fn&&typeof fn!="string"&&!fn.nodeName&&fn.constructor!=Array&&/^[\s[]?function/.test(fn+"");},isXMLDoc:function(elem){return elem.documentElement&&!elem.body||elem.tagName&&elem.ownerDocument&&!elem.ownerDocument.body;},globalEval:function(data){data=jQuery.trim(data);if(data){var head=document.getElementsByTagName("head")[0]||document.documentElement,script=document.createElement("script");script.type="text/javascript";if(jQuery.browser.msie)script.text=data;else
-script.appendChild(document.createTextNode(data));head.insertBefore(script,head.firstChild);head.removeChild(script);}},nodeName:function(elem,name){return elem.nodeName&&elem.nodeName.toUpperCase()==name.toUpperCase();},cache:{},data:function(elem,name,data){elem=elem==window?windowData:elem;var id=elem[expando];if(!id)id=elem[expando]=++uuid;if(name&&!jQuery.cache[id])jQuery.cache[id]={};if(data!==undefined)jQuery.cache[id][name]=data;return name?jQuery.cache[id][name]:id;},removeData:function(elem,name){elem=elem==window?windowData:elem;var id=elem[expando];if(name){if(jQuery.cache[id]){delete jQuery.cache[id][name];name="";for(name in jQuery.cache[id])break;if(!name)jQuery.removeData(elem);}}else{try{delete elem[expando];}catch(e){if(elem.removeAttribute)elem.removeAttribute(expando);}delete jQuery.cache[id];}},each:function(object,callback,args){var name,i=0,length=object.length;if(args){if(length==undefined){for(name in object)if(callback.apply(object[name],args)===false)break;}else
-for(;i<length;)if(callback.apply(object[i++],args)===false)break;}else{if(length==undefined){for(name in object)if(callback.call(object[name],name,object[name])===false)break;}else
-for(var value=object[0];i<length&&callback.call(value,i,value)!==false;value=object[++i]){}}return object;},prop:function(elem,value,type,i,name){if(jQuery.isFunction(value))value=value.call(elem,i);return value&&value.constructor==Number&&type=="curCSS"&&!exclude.test(name)?value+"px":value;},className:{add:function(elem,classNames){jQuery.each((classNames||"").split(/\s+/),function(i,className){if(elem.nodeType==1&&!jQuery.className.has(elem.className,className))elem.className+=(elem.className?" ":"")+className;});},remove:function(elem,classNames){if(elem.nodeType==1)elem.className=classNames!=undefined?jQuery.grep(elem.className.split(/\s+/),function(className){return!jQuery.className.has(classNames,className);}).join(" "):"";},has:function(elem,className){return jQuery.inArray(className,(elem.className||elem).toString().split(/\s+/))>-1;}},swap:function(elem,options,callback){var old={};for(var name in options){old[name]=elem.style[name];elem.style[name]=options[name];}callback.call(elem);for(var name in options)elem.style[name]=old[name];},css:function(elem,name,force){if(name=="width"||name=="height"){var val,props={position:"absolute",visibility:"hidden",display:"block"},which=name=="width"?["Left","Right"]:["Top","Bottom"];function getWH(){val=name=="width"?elem.offsetWidth:elem.offsetHeight;var padding=0,border=0;jQuery.each(which,function(){padding+=parseFloat(jQuery.curCSS(elem,"padding"+this,true))||0;border+=parseFloat(jQuery.curCSS(elem,"border"+this+"Width",true))||0;});val-=Math.round(padding+border);}if(jQuery(elem).is(":visible"))getWH();else
-jQuery.swap(elem,props,getWH);return Math.max(0,val);}return jQuery.curCSS(elem,name,force);},curCSS:function(elem,name,force){var ret,style=elem.style;function color(elem){if(!jQuery.browser.safari)return false;var ret=defaultView.getComputedStyle(elem,null);return!ret||ret.getPropertyValue("color")=="";}if(name=="opacity"&&jQuery.browser.msie){ret=jQuery.attr(style,"opacity");return ret==""?"1":ret;}if(jQuery.browser.opera&&name=="display"){var save=style.outline;style.outline="0 solid black";style.outline=save;}if(name.match(/float/i))name=styleFloat;if(!force&&style&&style[name])ret=style[name];else if(defaultView.getComputedStyle){if(name.match(/float/i))name="float";name=name.replace(/([A-Z])/g,"-$1").toLowerCase();var computedStyle=defaultView.getComputedStyle(elem,null);if(computedStyle&&!color(elem))ret=computedStyle.getPropertyValue(name);else{var swap=[],stack=[],a=elem,i=0;for(;a&&color(a);a=a.parentNode)stack.unshift(a);for(;i<stack.length;i++)if(color(stack[i])){swap[i]=stack[i].style.display;stack[i].style.display="block";}ret=name=="display"&&swap[stack.length-1]!=null?"none":(computedStyle&&computedStyle.getPropertyValue(name))||"";for(i=0;i<swap.length;i++)if(swap[i]!=null)stack[i].style.display=swap[i];}if(name=="opacity"&&ret=="")ret="1";}else if(elem.currentStyle){var camelCase=name.replace(/\-(\w)/g,function(all,letter){return letter.toUpperCase();});ret=elem.currentStyle[name]||elem.currentStyle[camelCase];if(!/^\d+(px)?$/i.test(ret)&&/^\d/.test(ret)){var left=style.left,rsLeft=elem.runtimeStyle.left;elem.runtimeStyle.left=elem.currentStyle.left;style.left=ret||0;ret=style.pixelLeft+"px";style.left=left;elem.runtimeStyle.left=rsLeft;}}return ret;},clean:function(elems,context){var ret=[];context=context||document;if(typeof context.createElement=='undefined')context=context.ownerDocument||context[0]&&context[0].ownerDocument||document;jQuery.each(elems,function(i,elem){if(!elem)return;if(elem.constructor==Number)elem+='';if(typeof elem=="string"){elem=elem.replace(/(<(\w+)[^>]*?)\/>/g,function(all,front,tag){return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?all:front+"></"+tag+">";});var tags=jQuery.trim(elem).toLowerCase(),div=context.createElement("div");var wrap=!tags.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!tags.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||tags.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!tags.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!tags.indexOf("<td")||!tags.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!tags.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||jQuery.browser.msie&&[1,"div<div>","</div>"]||[0,"",""];div.innerHTML=wrap[1]+elem+wrap[2];while(wrap[0]--)div=div.lastChild;if(jQuery.browser.msie){var tbody=!tags.indexOf("<table")&&tags.indexOf("<tbody")<0?div.firstChild&&div.firstChild.childNodes:wrap[1]=="<table>"&&tags.indexOf("<tbody")<0?div.childNodes:[];for(var j=tbody.length-1;j>=0;--j)if(jQuery.nodeName(tbody[j],"tbody")&&!tbody[j].childNodes.length)tbody[j].parentNode.removeChild(tbody[j]);if(/^\s/.test(elem))div.insertBefore(context.createTextNode(elem.match(/^\s*/)[0]),div.firstChild);}elem=jQuery.makeArray(div.childNodes);}if(elem.length===0&&(!jQuery.nodeName(elem,"form")&&!jQuery.nodeName(elem,"select")))return;if(elem[0]==undefined||jQuery.nodeName(elem,"form")||elem.options)ret.push(elem);else
-ret=jQuery.merge(ret,elem);});return ret;},attr:function(elem,name,value){if(!elem||elem.nodeType==3||elem.nodeType==8)return undefined;var notxml=!jQuery.isXMLDoc(elem),set=value!==undefined,msie=jQuery.browser.msie;name=notxml&&jQuery.props[name]||name;if(elem.tagName){var special=/href|src|style/.test(name);if(name=="selected"&&jQuery.browser.safari)elem.parentNode.selectedIndex;if(name in elem&&notxml&&!special){if(set){if(name=="type"&&jQuery.nodeName(elem,"input")&&elem.parentNode)throw"type property can't be changed";elem[name]=value;}if(jQuery.nodeName(elem,"form")&&elem.getAttributeNode(name))return elem.getAttributeNode(name).nodeValue;return elem[name];}if(msie&&notxml&&name=="style")return jQuery.attr(elem.style,"cssText",value);if(set)elem.setAttribute(name,""+value);var attr=msie&&notxml&&special?elem.getAttribute(name,2):elem.getAttribute(name);return attr===null?undefined:attr;}if(msie&&name=="opacity"){if(set){elem.zoom=1;elem.filter=(elem.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(value)+''=="NaN"?"":"alpha(opacity="+value*100+")");}return elem.filter&&elem.filter.indexOf("opacity=")>=0?(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1])/100)+'':"";}name=name.replace(/-([a-z])/ig,function(all,letter){return letter.toUpperCase();});if(set)elem[name]=value;return elem[name];},trim:function(text){return(text||"").replace(/^\s+|\s+$/g,"");},makeArray:function(array){var ret=[];if(array!=null){var i=array.length;if(i==null||array.split||array.setInterval||array.call)ret[0]=array;else
-while(i)ret[--i]=array[i];}return ret;},inArray:function(elem,array){for(var i=0,length=array.length;i<length;i++)if(array[i]===elem)return i;return-1;},merge:function(first,second){var i=0,elem,pos=first.length;if(jQuery.browser.msie){while(elem=second[i++])if(elem.nodeType!=8)first[pos++]=elem;}else
-while(elem=second[i++])first[pos++]=elem;return first;},unique:function(array){var ret=[],done={};try{for(var i=0,length=array.length;i<length;i++){var id=jQuery.data(array[i]);if(!done[id]){done[id]=true;ret.push(array[i]);}}}catch(e){ret=array;}return ret;},grep:function(elems,callback,inv){var ret=[];for(var i=0,length=elems.length;i<length;i++)if(!inv!=!callback(elems[i],i))ret.push(elems[i]);return ret;},map:function(elems,callback){var ret=[];for(var i=0,length=elems.length;i<length;i++){var value=callback(elems[i],i);if(value!=null)ret[ret.length]=value;}return ret.concat.apply([],ret);}});var userAgent=navigator.userAgent.toLowerCase();jQuery.browser={version:(userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[])[1],safari:/webkit/.test(userAgent),opera:/opera/.test(userAgent),msie:/msie/.test(userAgent)&&!/opera/.test(userAgent),mozilla:/mozilla/.test(userAgent)&&!/(compatible|webkit)/.test(userAgent)};var styleFloat=jQuery.browser.msie?"styleFloat":"cssFloat";jQuery.extend({boxModel:!jQuery.browser.msie||document.compatMode=="CSS1Compat",props:{"for":"htmlFor","class":"className","float":styleFloat,cssFloat:styleFloat,styleFloat:styleFloat,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing"}});jQuery.each({parent:function(elem){return elem.parentNode;},parents:function(elem){return jQuery.dir(elem,"parentNode");},next:function(elem){return jQuery.nth(elem,2,"nextSibling");},prev:function(elem){return jQuery.nth(elem,2,"previousSibling");},nextAll:function(elem){return jQuery.dir(elem,"nextSibling");},prevAll:function(elem){return jQuery.dir(elem,"previousSibling");},siblings:function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},children:function(elem){return jQuery.sibling(elem.firstChild);},contents:function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}},function(name,fn){jQuery.fn[name]=function(selector){var ret=jQuery.map(this,fn);if(selector&&typeof selector=="string")ret=jQuery.multiFilter(selector,ret);return this.pushStack(jQuery.unique(ret));};});jQuery.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(name,original){jQuery.fn[name]=function(){var args=arguments;return this.each(function(){for(var i=0,length=args.length;i<length;i++)jQuery(args[i])[original](this);});};});jQuery.each({removeAttr:function(name){jQuery.attr(this,name,"");if(this.nodeType==1)this.removeAttribute(name);},addClass:function(classNames){jQuery.className.add(this,classNames);},removeClass:function(classNames){jQuery.className.remove(this,classNames);},toggleClass:function(classNames){jQuery.className[jQuery.className.has(this,classNames)?"remove":"add"](this,classNames);},remove:function(selector){if(!selector||jQuery.filter(selector,[this]).r.length){jQuery("*",this).add(this).each(function(){jQuery.event.remove(this);jQuery.removeData(this);});if(this.parentNode)this.parentNode.removeChild(this);}},empty:function(){jQuery(">*",this).remove();while(this.firstChild)this.removeChild(this.firstChild);}},function(name,fn){jQuery.fn[name]=function(){return this.each(fn,arguments);};});jQuery.each(["Height","Width"],function(i,name){var type=name.toLowerCase();jQuery.fn[type]=function(size){return this[0]==window?jQuery.browser.opera&&document.body["client"+name]||jQuery.browser.safari&&window["inner"+name]||document.compatMode=="CSS1Compat"&&document.documentElement["client"+name]||document.body["client"+name]:this[0]==document?Math.max(Math.max(document.body["scroll"+name],document.documentElement["scroll"+name]),Math.max(document.body["offset"+name],document.documentElement["offset"+name])):size==undefined?(this.length?jQuery.css(this[0],type):null):this.css(type,size.constructor==String?size:size+"px");};});function num(elem,prop){return elem[0]&&parseInt(jQuery.curCSS(elem[0],prop,true),10)||0;}var chars=jQuery.browser.safari&&parseInt(jQuery.browser.version)<417?"(?:[\\w*_-]|\\\\.)":"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",quickChild=new RegExp("^>\\s*("+chars+"+)"),quickID=new RegExp("^("+chars+"+)(#)("+chars+"+)"),quickClass=new RegExp("^([#.]?)("+chars+"*)");jQuery.extend({expr:{"":function(a,i,m){return m[2]=="*"||jQuery.nodeName(a,m[2]);},"#":function(a,i,m){return a.getAttribute("id")==m[2];},":":{lt:function(a,i,m){return i<m[3]-0;},gt:function(a,i,m){return i>m[3]-0;},nth:function(a,i,m){return m[3]-0==i;},eq:function(a,i,m){return m[3]-0==i;},first:function(a,i){return i==0;},last:function(a,i,m,r){return i==r.length-1;},even:function(a,i){return i%2==0;},odd:function(a,i){return i%2;},"first-child":function(a){return a.parentNode.getElementsByTagName("*")[0]==a;},"last-child":function(a){return jQuery.nth(a.parentNode.lastChild,1,"previousSibling")==a;},"only-child":function(a){return!jQuery.nth(a.parentNode.lastChild,2,"previousSibling");},parent:function(a){return a.firstChild;},empty:function(a){return!a.firstChild;},contains:function(a,i,m){return(a.textContent||a.innerText||jQuery(a).text()||"").indexOf(m[3])>=0;},visible:function(a){return"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden";},hidden:function(a){return"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden";},enabled:function(a){return!a.disabled;},disabled:function(a){return a.disabled;},checked:function(a){return a.checked;},selected:function(a){return a.selected||jQuery.attr(a,"selected");},text:function(a){return"text"==a.type;},radio:function(a){return"radio"==a.type;},checkbox:function(a){return"checkbox"==a.type;},file:function(a){return"file"==a.type;},password:function(a){return"password"==a.type;},submit:function(a){return"submit"==a.type;},image:function(a){return"image"==a.type;},reset:function(a){return"reset"==a.type;},button:function(a){return"button"==a.type||jQuery.nodeName(a,"button");},input:function(a){return/input|select|textarea|button/i.test(a.nodeName);},has:function(a,i,m){return jQuery.find(m[3],a).length;},header:function(a){return/h\d/i.test(a.nodeName);},animated:function(a){return jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length;}}},parse:[/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,new RegExp("^([:.#]*)("+chars+"+)")],multiFilter:function(expr,elems,not){var old,cur=[];while(expr&&expr!=old){old=expr;var f=jQuery.filter(expr,elems,not);expr=f.t.replace(/^\s*,\s*/,"");cur=not?elems=f.r:jQuery.merge(cur,f.r);}return cur;},find:function(t,context){if(typeof t!="string")return[t];if(context&&context.nodeType!=1&&context.nodeType!=9)return[];context=context||document;var ret=[context],done=[],last,nodeName;while(t&&last!=t){var r=[];last=t;t=jQuery.trim(t);var foundToken=false,re=quickChild,m=re.exec(t);if(m){nodeName=m[1].toUpperCase();for(var i=0;ret[i];i++)for(var c=ret[i].firstChild;c;c=c.nextSibling)if(c.nodeType==1&&(nodeName=="*"||c.nodeName.toUpperCase()==nodeName))r.push(c);ret=r;t=t.replace(re,"");if(t.indexOf(" ")==0)continue;foundToken=true;}else{re=/^([>+~])\s*(\w*)/i;if((m=re.exec(t))!=null){r=[];var merge={};nodeName=m[2].toUpperCase();m=m[1];for(var j=0,rl=ret.length;j<rl;j++){var n=m=="~"||m=="+"?ret[j].nextSibling:ret[j].firstChild;for(;n;n=n.nextSibling)if(n.nodeType==1){var id=jQuery.data(n);if(m=="~"&&merge[id])break;if(!nodeName||n.nodeName.toUpperCase()==nodeName){if(m=="~")merge[id]=true;r.push(n);}if(m=="+")break;}}ret=r;t=jQuery.trim(t.replace(re,""));foundToken=true;}}if(t&&!foundToken){if(!t.indexOf(",")){if(context==ret[0])ret.shift();done=jQuery.merge(done,ret);r=ret=[context];t=" "+t.substr(1,t.length);}else{var re2=quickID;var m=re2.exec(t);if(m){m=[0,m[2],m[3],m[1]];}else{re2=quickClass;m=re2.exec(t);}m[2]=m[2].replace(/\\/g,"");var elem=ret[ret.length-1];if(m[1]=="#"&&elem&&elem.getElementById&&!jQuery.isXMLDoc(elem)){var oid=elem.getElementById(m[2]);if((jQuery.browser.msie||jQuery.browser.opera)&&oid&&typeof oid.id=="string"&&oid.id!=m[2])oid=jQuery('[@id="'+m[2]+'"]',elem)[0];ret=r=oid&&(!m[3]||jQuery.nodeName(oid,m[3]))?[oid]:[];}else{for(var i=0;ret[i];i++){var tag=m[1]=="#"&&m[3]?m[3]:m[1]!=""||m[0]==""?"*":m[2];if(tag=="*"&&ret[i].nodeName.toLowerCase()=="object")tag="param";r=jQuery.merge(r,ret[i].getElementsByTagName(tag));}if(m[1]==".")r=jQuery.classFilter(r,m[2]);if(m[1]=="#"){var tmp=[];for(var i=0;r[i];i++)if(r[i].getAttribute("id")==m[2]){tmp=[r[i]];break;}r=tmp;}ret=r;}t=t.replace(re2,"");}}if(t){var val=jQuery.filter(t,r);ret=r=val.r;t=jQuery.trim(val.t);}}if(t)ret=[];if(ret&&context==ret[0])ret.shift();done=jQuery.merge(done,ret);return done;},classFilter:function(r,m,not){m=" "+m+" ";var tmp=[];for(var i=0;r[i];i++){var pass=(" "+r[i].className+" ").indexOf(m)>=0;if(!not&&pass||not&&!pass)tmp.push(r[i]);}return tmp;},filter:function(t,r,not){var last;while(t&&t!=last){last=t;var p=jQuery.parse,m;for(var i=0;p[i];i++){m=p[i].exec(t);if(m){t=t.substring(m[0].length);m[2]=m[2].replace(/\\/g,"");break;}}if(!m)break;if(m[1]==":"&&m[2]=="not")r=isSimple.test(m[3])?jQuery.filter(m[3],r,true).r:jQuery(r).not(m[3]);else if(m[1]==".")r=jQuery.classFilter(r,m[2],not);else if(m[1]=="["){var tmp=[],type=m[3];for(var i=0,rl=r.length;i<rl;i++){var a=r[i],z=a[jQuery.props[m[2]]||m[2]];if(z==null||/href|src|selected/.test(m[2]))z=jQuery.attr(a,m[2])||'';if((type==""&&!!z||type=="="&&z==m[5]||type=="!="&&z!=m[5]||type=="^="&&z&&!z.indexOf(m[5])||type=="$="&&z.substr(z.length-m[5].length)==m[5]||(type=="*="||type=="~=")&&z.indexOf(m[5])>=0)^not)tmp.push(a);}r=tmp;}else if(m[1]==":"&&m[2]=="nth-child"){var merge={},tmp=[],test=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(m[3]=="even"&&"2n"||m[3]=="odd"&&"2n+1"||!/\D/.test(m[3])&&"0n+"+m[3]||m[3]),first=(test[1]+(test[2]||1))-0,last=test[3]-0;for(var i=0,rl=r.length;i<rl;i++){var node=r[i],parentNode=node.parentNode,id=jQuery.data(parentNode);if(!merge[id]){var c=1;for(var n=parentNode.firstChild;n;n=n.nextSibling)if(n.nodeType==1)n.nodeIndex=c++;merge[id]=true;}var add=false;if(first==0){if(node.nodeIndex==last)add=true;}else if((node.nodeIndex-last)%first==0&&(node.nodeIndex-last)/first>=0)add=true;if(add^not)tmp.push(node);}r=tmp;}else{var fn=jQuery.expr[m[1]];if(typeof fn=="object")fn=fn[m[2]];if(typeof fn=="string")fn=eval("false||function(a,i){return "+fn+";}");r=jQuery.grep(r,function(elem,i){return fn(elem,i,m,r);},not);}}return{r:r,t:t};},dir:function(elem,dir){var matched=[],cur=elem[dir];while(cur&&cur!=document){if(cur.nodeType==1)matched.push(cur);cur=cur[dir];}return matched;},nth:function(cur,result,dir,elem){result=result||1;var num=0;for(;cur;cur=cur[dir])if(cur.nodeType==1&&++num==result)break;return cur;},sibling:function(n,elem){var r=[];for(;n;n=n.nextSibling){if(n.nodeType==1&&n!=elem)r.push(n);}return r;}});jQuery.event={add:function(elem,types,handler,data){if(elem.nodeType==3||elem.nodeType==8)return;if(jQuery.browser.msie&&elem.setInterval)elem=window;if(!handler.guid)handler.guid=this.guid++;if(data!=undefined){var fn=handler;handler=this.proxy(fn,function(){return fn.apply(this,arguments);});handler.data=data;}var events=jQuery.data(elem,"events")||jQuery.data(elem,"events",{}),handle=jQuery.data(elem,"handle")||jQuery.data(elem,"handle",function(){if(typeof jQuery!="undefined"&&!jQuery.event.triggered)return jQuery.event.handle.apply(arguments.callee.elem,arguments);});handle.elem=elem;jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];handler.type=parts[1];var handlers=events[type];if(!handlers){handlers=events[type]={};if(!jQuery.event.special[type]||jQuery.event.special[type].setup.call(elem)===false){if(elem.addEventListener)elem.addEventListener(type,handle,false);else if(elem.attachEvent)elem.attachEvent("on"+type,handle);}}handlers[handler.guid]=handler;jQuery.event.global[type]=true;});elem=null;},guid:1,global:{},remove:function(elem,types,handler){if(elem.nodeType==3||elem.nodeType==8)return;var events=jQuery.data(elem,"events"),ret,index;if(events){if(types==undefined||(typeof types=="string"&&types.charAt(0)=="."))for(var type in events)this.remove(elem,type+(types||""));else{if(types.type){handler=types.handler;types=types.type;}jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];if(events[type]){if(handler)delete events[type][handler.guid];else
-for(handler in events[type])if(!parts[1]||events[type][handler].type==parts[1])delete events[type][handler];for(ret in events[type])break;if(!ret){if(!jQuery.event.special[type]||jQuery.event.special[type].teardown.call(elem)===false){if(elem.removeEventListener)elem.removeEventListener(type,jQuery.data(elem,"handle"),false);else if(elem.detachEvent)elem.detachEvent("on"+type,jQuery.data(elem,"handle"));}ret=null;delete events[type];}}});}for(ret in events)break;if(!ret){var handle=jQuery.data(elem,"handle");if(handle)handle.elem=null;jQuery.removeData(elem,"events");jQuery.removeData(elem,"handle");}}},trigger:function(type,data,elem,donative,extra){data=jQuery.makeArray(data);if(type.indexOf("!")>=0){type=type.slice(0,-1);var exclusive=true;}if(!elem){if(this.global[type])jQuery("*").add([window,document]).trigger(type,data);}else{if(elem.nodeType==3||elem.nodeType==8)return undefined;var val,ret,fn=jQuery.isFunction(elem[type]||null),event=!data[0]||!data[0].preventDefault;if(event){data.unshift({type:type,target:elem,preventDefault:function(){},stopPropagation:function(){},timeStamp:now()});data[0][expando]=true;}data[0].type=type;if(exclusive)data[0].exclusive=true;var handle=jQuery.data(elem,"handle");if(handle)val=handle.apply(elem,data);if((!fn||(jQuery.nodeName(elem,'a')&&type=="click"))&&elem["on"+type]&&elem["on"+type].apply(elem,data)===false)val=false;if(event)data.shift();if(extra&&jQuery.isFunction(extra)){ret=extra.apply(elem,val==null?data:data.concat(val));if(ret!==undefined)val=ret;}if(fn&&donative!==false&&val!==false&&!(jQuery.nodeName(elem,'a')&&type=="click")){this.triggered=true;try{elem[type]();}catch(e){}}this.triggered=false;}return val;},handle:function(event){var val,ret,namespace,all,handlers;event=arguments[0]=jQuery.event.fix(event||window.event);namespace=event.type.split(".");event.type=namespace[0];namespace=namespace[1];all=!namespace&&!event.exclusive;handlers=(jQuery.data(this,"events")||{})[event.type];for(var j in handlers){var handler=handlers[j];if(all||handler.type==namespace){event.handler=handler;event.data=handler.data;ret=handler.apply(this,arguments);if(val!==false)val=ret;if(ret===false){event.preventDefault();event.stopPropagation();}}}return val;},fix:function(event){if(event[expando]==true)return event;var originalEvent=event;event={originalEvent:originalEvent};var props="altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target timeStamp toElement type view wheelDelta which".split(" ");for(var i=props.length;i;i--)event[props[i]]=originalEvent[props[i]];event[expando]=true;event.preventDefault=function(){if(originalEvent.preventDefault)originalEvent.preventDefault();originalEvent.returnValue=false;};event.stopPropagation=function(){if(originalEvent.stopPropagation)originalEvent.stopPropagation();originalEvent.cancelBubble=true;};event.timeStamp=event.timeStamp||now();if(!event.target)event.target=event.srcElement||document;if(event.target.nodeType==3)event.target=event.target.parentNode;if(!event.relatedTarget&&event.fromElement)event.relatedTarget=event.fromElement==event.target?event.toElement:event.fromElement;if(event.pageX==null&&event.clientX!=null){var doc=document.documentElement,body=document.body;event.pageX=event.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc.clientLeft||0);event.pageY=event.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc.clientTop||0);}if(!event.which&&((event.charCode||event.charCode===0)?event.charCode:event.keyCode))event.which=event.charCode||event.keyCode;if(!event.metaKey&&event.ctrlKey)event.metaKey=event.ctrlKey;if(!event.which&&event.button)event.which=(event.button&1?1:(event.button&2?3:(event.button&4?2:0)));return event;},proxy:function(fn,proxy){proxy.guid=fn.guid=fn.guid||proxy.guid||this.guid++;return proxy;},special:{ready:{setup:function(){bindReady();return;},teardown:function(){return;}},mouseenter:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseover",jQuery.event.special.mouseenter.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseover",jQuery.event.special.mouseenter.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseenter";return jQuery.event.handle.apply(this,arguments);}},mouseleave:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseout",jQuery.event.special.mouseleave.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseout",jQuery.event.special.mouseleave.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseleave";return jQuery.event.handle.apply(this,arguments);}}}};jQuery.fn.extend({bind:function(type,data,fn){return type=="unload"?this.one(type,data,fn):this.each(function(){jQuery.event.add(this,type,fn||data,fn&&data);});},one:function(type,data,fn){var one=jQuery.event.proxy(fn||data,function(event){jQuery(this).unbind(event,one);return(fn||data).apply(this,arguments);});return this.each(function(){jQuery.event.add(this,type,one,fn&&data);});},unbind:function(type,fn){return this.each(function(){jQuery.event.remove(this,type,fn);});},trigger:function(type,data,fn){return this.each(function(){jQuery.event.trigger(type,data,this,true,fn);});},triggerHandler:function(type,data,fn){return this[0]&&jQuery.event.trigger(type,data,this[0],false,fn);},toggle:function(fn){var args=arguments,i=1;while(i<args.length)jQuery.event.proxy(fn,args[i++]);return this.click(jQuery.event.proxy(fn,function(event){this.lastToggle=(this.lastToggle||0)%i;event.preventDefault();return args[this.lastToggle++].apply(this,arguments)||false;}));},hover:function(fnOver,fnOut){return this.bind('mouseenter',fnOver).bind('mouseleave',fnOut);},ready:function(fn){bindReady();if(jQuery.isReady)fn.call(document,jQuery);else
-jQuery.readyList.push(function(){return fn.call(this,jQuery);});return this;}});jQuery.extend({isReady:false,readyList:[],ready:function(){if(!jQuery.isReady){jQuery.isReady=true;if(jQuery.readyList){jQuery.each(jQuery.readyList,function(){this.call(document);});jQuery.readyList=null;}jQuery(document).triggerHandler("ready");}}});var readyBound=false;function bindReady(){if(readyBound)return;readyBound=true;if(document.addEventListener&&!jQuery.browser.opera)document.addEventListener("DOMContentLoaded",jQuery.ready,false);if(jQuery.browser.msie&&window==top)(function(){if(jQuery.isReady)return;try{document.documentElement.doScroll("left");}catch(error){setTimeout(arguments.callee,0);return;}jQuery.ready();})();if(jQuery.browser.opera)document.addEventListener("DOMContentLoaded",function(){if(jQuery.isReady)return;for(var i=0;i<document.styleSheets.length;i++)if(document.styleSheets[i].disabled){setTimeout(arguments.callee,0);return;}jQuery.ready();},false);if(jQuery.browser.safari){var numStyles;(function(){if(jQuery.isReady)return;if(document.readyState!="loaded"&&document.readyState!="complete"){setTimeout(arguments.callee,0);return;}if(numStyles===undefined)numStyles=jQuery("style, link[rel=stylesheet]").length;if(document.styleSheets.length!=numStyles){setTimeout(arguments.callee,0);return;}jQuery.ready();})();}jQuery.event.add(window,"load",jQuery.ready);}jQuery.each(("blur,focus,load,resize,scroll,unload,click,dblclick,"+"mousedown,mouseup,mousemove,mouseover,mouseout,change,select,"+"submit,keydown,keypress,keyup,error").split(","),function(i,name){jQuery.fn[name]=function(fn){return fn?this.bind(name,fn):this.trigger(name);};});var withinElement=function(event,elem){var parent=event.relatedTarget;while(parent&&parent!=elem)try{parent=parent.parentNode;}catch(error){parent=elem;}return parent==elem;};jQuery(window).bind("unload",function(){jQuery("*").add(document).unbind();});jQuery.fn.extend({_load:jQuery.fn.load,load:function(url,params,callback){if(typeof url!='string')return this._load(url);var off=url.indexOf(" ");if(off>=0){var selector=url.slice(off,url.length);url=url.slice(0,off);}callback=callback||function(){};var type="GET";if(params)if(jQuery.isFunction(params)){callback=params;params=null;}else{params=jQuery.param(params);type="POST";}var self=this;jQuery.ajax({url:url,type:type,dataType:"html",data:params,complete:function(res,status){if(status=="success"||status=="notmodified")self.html(selector?jQuery("<div/>").append(res.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(selector):res.responseText);self.each(callback,[res.responseText,status,res]);}});return this;},serialize:function(){return jQuery.param(this.serializeArray());},serializeArray:function(){return this.map(function(){return jQuery.nodeName(this,"form")?jQuery.makeArray(this.elements):this;}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password/i.test(this.type));}).map(function(i,elem){var val=jQuery(this).val();return val==null?null:val.constructor==Array?jQuery.map(val,function(val,i){return{name:elem.name,value:val};}):{name:elem.name,value:val};}).get();}});jQuery.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(i,o){jQuery.fn[o]=function(f){return this.bind(o,f);};});var jsc=now();jQuery.extend({get:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data=null;}return jQuery.ajax({type:"GET",url:url,data:data,success:callback,dataType:type});},getScript:function(url,callback){return jQuery.get(url,null,callback,"script");},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json");},post:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data={};}return jQuery.ajax({type:"POST",url:url,data:data,success:callback,dataType:type});},ajaxSetup:function(settings){jQuery.extend(jQuery.ajaxSettings,settings);},ajaxSettings:{url:location.href,global:true,type:"GET",timeout:0,contentType:"application/x-www-form-urlencoded",processData:true,async:true,data:null,username:null,password:null,accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(s){s=jQuery.extend(true,s,jQuery.extend(true,{},jQuery.ajaxSettings,s));var jsonp,jsre=/=\?(&|$)/g,status,data,type=s.type.toUpperCase();if(s.data&&s.processData&&typeof s.data!="string")s.data=jQuery.param(s.data);if(s.dataType=="jsonp"){if(type=="GET"){if(!s.url.match(jsre))s.url+=(s.url.match(/\?/)?"&":"?")+(s.jsonp||"callback")+"=?";}else if(!s.data||!s.data.match(jsre))s.data=(s.data?s.data+"&":"")+(s.jsonp||"callback")+"=?";s.dataType="json";}if(s.dataType=="json"&&(s.data&&s.data.match(jsre)||s.url.match(jsre))){jsonp="jsonp"+jsc++;if(s.data)s.data=(s.data+"").replace(jsre,"="+jsonp+"$1");s.url=s.url.replace(jsre,"="+jsonp+"$1");s.dataType="script";window[jsonp]=function(tmp){data=tmp;success();complete();window[jsonp]=undefined;try{delete window[jsonp];}catch(e){}if(head)head.removeChild(script);};}if(s.dataType=="script"&&s.cache==null)s.cache=false;if(s.cache===false&&type=="GET"){var ts=now();var ret=s.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+ts+"$2");s.url=ret+((ret==s.url)?(s.url.match(/\?/)?"&":"?")+"_="+ts:"");}if(s.data&&type=="GET"){s.url+=(s.url.match(/\?/)?"&":"?")+s.data;s.data=null;}if(s.global&&!jQuery.active++)jQuery.event.trigger("ajaxStart");var remote=/^(?:\w+:)?\/\/([^\/?#]+)/;if(s.dataType=="script"&&type=="GET"&&remote.test(s.url)&&remote.exec(s.url)[1]!=location.host){var head=document.getElementsByTagName("head")[0];var script=document.createElement("script");script.src=s.url;if(s.scriptCharset)script.charset=s.scriptCharset;if(!jsonp){var done=false;script.onload=script.onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){done=true;success();complete();head.removeChild(script);}};}head.appendChild(script);return undefined;}var requestDone=false;var xhr=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();if(s.username)xhr.open(type,s.url,s.async,s.username,s.password);else
-xhr.open(type,s.url,s.async);try{if(s.data)xhr.setRequestHeader("Content-Type",s.contentType);if(s.ifModified)xhr.setRequestHeader("If-Modified-Since",jQuery.lastModified[s.url]||"Thu, 01 Jan 1970 00:00:00 GMT");xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");xhr.setRequestHeader("Accept",s.dataType&&s.accepts[s.dataType]?s.accepts[s.dataType]+", */*":s.accepts._default);}catch(e){}if(s.beforeSend&&s.beforeSend(xhr,s)===false){s.global&&jQuery.active--;xhr.abort();return false;}if(s.global)jQuery.event.trigger("ajaxSend",[xhr,s]);var onreadystatechange=function(isTimeout){if(!requestDone&&xhr&&(xhr.readyState==4||isTimeout=="timeout")){requestDone=true;if(ival){clearInterval(ival);ival=null;}status=isTimeout=="timeout"&&"timeout"||!jQuery.httpSuccess(xhr)&&"error"||s.ifModified&&jQuery.httpNotModified(xhr,s.url)&&"notmodified"||"success";if(status=="success"){try{data=jQuery.httpData(xhr,s.dataType,s.dataFilter);}catch(e){status="parsererror";}}if(status=="success"){var modRes;try{modRes=xhr.getResponseHeader("Last-Modified");}catch(e){}if(s.ifModified&&modRes)jQuery.lastModified[s.url]=modRes;if(!jsonp)success();}else
-jQuery.handleError(s,xhr,status);complete();if(s.async)xhr=null;}};if(s.async){var ival=setInterval(onreadystatechange,13);if(s.timeout>0)setTimeout(function(){if(xhr){xhr.abort();if(!requestDone)onreadystatechange("timeout");}},s.timeout);}try{xhr.send(s.data);}catch(e){jQuery.handleError(s,xhr,null,e);}if(!s.async)onreadystatechange();function success(){if(s.success)s.success(data,status);if(s.global)jQuery.event.trigger("ajaxSuccess",[xhr,s]);}function complete(){if(s.complete)s.complete(xhr,status);if(s.global)jQuery.event.trigger("ajaxComplete",[xhr,s]);if(s.global&&!--jQuery.active)jQuery.event.trigger("ajaxStop");}return xhr;},handleError:function(s,xhr,status,e){if(s.error)s.error(xhr,status,e);if(s.global)jQuery.event.trigger("ajaxError",[xhr,s,e]);},active:0,httpSuccess:function(xhr){try{return!xhr.status&&location.protocol=="file:"||(xhr.status>=200&&xhr.status<300)||xhr.status==304||xhr.status==1223||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpNotModified:function(xhr,url){try{var xhrRes=xhr.getResponseHeader("Last-Modified");return xhr.status==304||xhrRes==jQuery.lastModified[url]||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpData:function(xhr,type,filter){var ct=xhr.getResponseHeader("content-type"),xml=type=="xml"||!type&&ct&&ct.indexOf("xml")>=0,data=xml?xhr.responseXML:xhr.responseText;if(xml&&data.documentElement.tagName=="parsererror")throw"parsererror";if(filter)data=filter(data,type);if(type=="script")jQuery.globalEval(data);if(type=="json")data=eval("("+data+")");return data;},param:function(a){var s=[];if(a.constructor==Array||a.jquery)jQuery.each(a,function(){s.push(encodeURIComponent(this.name)+"="+encodeURIComponent(this.value));});else
-for(var j in a)if(a[j]&&a[j].constructor==Array)jQuery.each(a[j],function(){s.push(encodeURIComponent(j)+"="+encodeURIComponent(this));});else
-s.push(encodeURIComponent(j)+"="+encodeURIComponent(jQuery.isFunction(a[j])?a[j]():a[j]));return s.join("&").replace(/%20/g,"+");}});jQuery.fn.extend({show:function(speed,callback){return speed?this.animate({height:"show",width:"show",opacity:"show"},speed,callback):this.filter(":hidden").each(function(){this.style.display=this.oldblock||"";if(jQuery.css(this,"display")=="none"){var elem=jQuery("<"+this.tagName+" />").appendTo("body");this.style.display=elem.css("display");if(this.style.display=="none")this.style.display="block";elem.remove();}}).end();},hide:function(speed,callback){return speed?this.animate({height:"hide",width:"hide",opacity:"hide"},speed,callback):this.filter(":visible").each(function(){this.oldblock=this.oldblock||jQuery.css(this,"display");this.style.display="none";}).end();},_toggle:jQuery.fn.toggle,toggle:function(fn,fn2){return jQuery.isFunction(fn)&&jQuery.isFunction(fn2)?this._toggle.apply(this,arguments):fn?this.animate({height:"toggle",width:"toggle",opacity:"toggle"},fn,fn2):this.each(function(){jQuery(this)[jQuery(this).is(":hidden")?"show":"hide"]();});},slideDown:function(speed,callback){return this.animate({height:"show"},speed,callback);},slideUp:function(speed,callback){return this.animate({height:"hide"},speed,callback);},slideToggle:function(speed,callback){return this.animate({height:"toggle"},speed,callback);},fadeIn:function(speed,callback){return this.animate({opacity:"show"},speed,callback);},fadeOut:function(speed,callback){return this.animate({opacity:"hide"},speed,callback);},fadeTo:function(speed,to,callback){return this.animate({opacity:to},speed,callback);},animate:function(prop,speed,easing,callback){var optall=jQuery.speed(speed,easing,callback);return this[optall.queue===false?"each":"queue"](function(){if(this.nodeType!=1)return false;var opt=jQuery.extend({},optall),p,hidden=jQuery(this).is(":hidden"),self=this;for(p in prop){if(prop[p]=="hide"&&hidden||prop[p]=="show"&&!hidden)return opt.complete.call(this);if(p=="height"||p=="width"){opt.display=jQuery.css(this,"display");opt.overflow=this.style.overflow;}}if(opt.overflow!=null)this.style.overflow="hidden";opt.curAnim=jQuery.extend({},prop);jQuery.each(prop,function(name,val){var e=new jQuery.fx(self,opt,name);if(/toggle|show|hide/.test(val))e[val=="toggle"?hidden?"show":"hide":val](prop);else{var parts=val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),start=e.cur(true)||0;if(parts){var end=parseFloat(parts[2]),unit=parts[3]||"px";if(unit!="px"){self.style[name]=(end||1)+unit;start=((end||1)/e.cur(true))*start;self.style[name]=start+unit;}if(parts[1])end=((parts[1]=="-="?-1:1)*end)+start;e.custom(start,end,unit);}else
-e.custom(start,val,"");}});return true;});},queue:function(type,fn){if(jQuery.isFunction(type)||(type&&type.constructor==Array)){fn=type;type="fx";}if(!type||(typeof type=="string"&&!fn))return queue(this[0],type);return this.each(function(){if(fn.constructor==Array)queue(this,type,fn);else{queue(this,type).push(fn);if(queue(this,type).length==1)fn.call(this);}});},stop:function(clearQueue,gotoEnd){var timers=jQuery.timers;if(clearQueue)this.queue([]);this.each(function(){for(var i=timers.length-1;i>=0;i--)if(timers[i].elem==this){if(gotoEnd)timers[i](true);timers.splice(i,1);}});if(!gotoEnd)this.dequeue();return this;}});var queue=function(elem,type,array){if(elem){type=type||"fx";var q=jQuery.data(elem,type+"queue");if(!q||array)q=jQuery.data(elem,type+"queue",jQuery.makeArray(array));}return q;};jQuery.fn.dequeue=function(type){type=type||"fx";return this.each(function(){var q=queue(this,type);q.shift();if(q.length)q[0].call(this);});};jQuery.extend({speed:function(speed,easing,fn){var opt=speed&&speed.constructor==Object?speed:{complete:fn||!fn&&easing||jQuery.isFunction(speed)&&speed,duration:speed,easing:fn&&easing||easing&&easing.constructor!=Function&&easing};opt.duration=(opt.duration&&opt.duration.constructor==Number?opt.duration:jQuery.fx.speeds[opt.duration])||jQuery.fx.speeds.def;opt.old=opt.complete;opt.complete=function(){if(opt.queue!==false)jQuery(this).dequeue();if(jQuery.isFunction(opt.old))opt.old.call(this);};return opt;},easing:{linear:function(p,n,firstNum,diff){return firstNum+diff*p;},swing:function(p,n,firstNum,diff){return((-Math.cos(p*Math.PI)/2)+0.5)*diff+firstNum;}},timers:[],timerId:null,fx:function(elem,options,prop){this.options=options;this.elem=elem;this.prop=prop;if(!options.orig)options.orig={};}});jQuery.fx.prototype={update:function(){if(this.options.step)this.options.step.call(this.elem,this.now,this);(jQuery.fx.step[this.prop]||jQuery.fx.step._default)(this);if(this.prop=="height"||this.prop=="width")this.elem.style.display="block";},cur:function(force){if(this.elem[this.prop]!=null&&this.elem.style[this.prop]==null)return this.elem[this.prop];var r=parseFloat(jQuery.css(this.elem,this.prop,force));return r&&r>-10000?r:parseFloat(jQuery.curCSS(this.elem,this.prop))||0;},custom:function(from,to,unit){this.startTime=now();this.start=from;this.end=to;this.unit=unit||this.unit||"px";this.now=this.start;this.pos=this.state=0;this.update();var self=this;function t(gotoEnd){return self.step(gotoEnd);}t.elem=this.elem;jQuery.timers.push(t);if(jQuery.timerId==null){jQuery.timerId=setInterval(function(){var timers=jQuery.timers;for(var i=0;i<timers.length;i++)if(!timers[i]())timers.splice(i--,1);if(!timers.length){clearInterval(jQuery.timerId);jQuery.timerId=null;}},13);}},show:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.show=true;this.custom(0,this.cur());if(this.prop=="width"||this.prop=="height")this.elem.style[this.prop]="1px";jQuery(this.elem).show();},hide:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0);},step:function(gotoEnd){var t=now();if(gotoEnd||t>this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var done=true;for(var i in this.options.curAnim)if(this.options.curAnim[i]!==true)done=false;if(done){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(jQuery.css(this.elem,"display")=="none")this.elem.style.display="block";}if(this.options.hide)this.elem.style.display="none";if(this.options.hide||this.options.show)for(var p in this.options.curAnim)jQuery.attr(this.elem.style,p,this.options.orig[p]);}if(done)this.options.complete.call(this.elem);return false;}else{var n=t-this.startTime;this.state=n/this.options.duration;this.pos=jQuery.easing[this.options.easing||(jQuery.easing.swing?"swing":"linear")](this.state,n,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update();}return true;}};jQuery.extend(jQuery.fx,{speeds:{slow:600,fast:200,def:400},step:{scrollLeft:function(fx){fx.elem.scrollLeft=fx.now;},scrollTop:function(fx){fx.elem.scrollTop=fx.now;},opacity:function(fx){jQuery.attr(fx.elem.style,"opacity",fx.now);},_default:function(fx){fx.elem.style[fx.prop]=fx.now+fx.unit;}}});jQuery.fn.offset=function(){var left=0,top=0,elem=this[0],results;if(elem)with(jQuery.browser){var parent=elem.parentNode,offsetChild=elem,offsetParent=elem.offsetParent,doc=elem.ownerDocument,safari2=safari&&parseInt(version)<522&&!/adobeair/i.test(userAgent),css=jQuery.curCSS,fixed=css(elem,"position")=="fixed";if(elem.getBoundingClientRect){var box=elem.getBoundingClientRect();add(box.left+Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),box.top+Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));add(-doc.documentElement.clientLeft,-doc.documentElement.clientTop);}else{add(elem.offsetLeft,elem.offsetTop);while(offsetParent){add(offsetParent.offsetLeft,offsetParent.offsetTop);if(mozilla&&!/^t(able|d|h)$/i.test(offsetParent.tagName)||safari&&!safari2)border(offsetParent);if(!fixed&&css(offsetParent,"position")=="fixed")fixed=true;offsetChild=/^body$/i.test(offsetParent.tagName)?offsetChild:offsetParent;offsetParent=offsetParent.offsetParent;}while(parent&&parent.tagName&&!/^body|html$/i.test(parent.tagName)){if(!/^inline|table.*$/i.test(css(parent,"display")))add(-parent.scrollLeft,-parent.scrollTop);if(mozilla&&css(parent,"overflow")!="visible")border(parent);parent=parent.parentNode;}if((safari2&&(fixed||css(offsetChild,"position")=="absolute"))||(mozilla&&css(offsetChild,"position")!="absolute"))add(-doc.body.offsetLeft,-doc.body.offsetTop);if(fixed)add(Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));}results={top:top,left:left};}function border(elem){add(jQuery.curCSS(elem,"borderLeftWidth",true),jQuery.curCSS(elem,"borderTopWidth",true));}function add(l,t){left+=parseInt(l,10)||0;top+=parseInt(t,10)||0;}return results;};jQuery.fn.extend({position:function(){var left=0,top=0,results;if(this[0]){var offsetParent=this.offsetParent(),offset=this.offset(),parentOffset=/^body|html$/i.test(offsetParent[0].tagName)?{top:0,left:0}:offsetParent.offset();offset.top-=num(this,'marginTop');offset.left-=num(this,'marginLeft');parentOffset.top+=num(offsetParent,'borderTopWidth');parentOffset.left+=num(offsetParent,'borderLeftWidth');results={top:offset.top-parentOffset.top,left:offset.left-parentOffset.left};}return results;},offsetParent:function(){var offsetParent=this[0].offsetParent;while(offsetParent&&(!/^body|html$/i.test(offsetParent.tagName)&&jQuery.css(offsetParent,'position')=='static'))offsetParent=offsetParent.offsetParent;return jQuery(offsetParent);}});jQuery.each(['Left','Top'],function(i,name){var method='scroll'+name;jQuery.fn[method]=function(val){if(!this[0])return;return val!=undefined?this.each(function(){this==window||this==document?window.scrollTo(!i?val:jQuery(window).scrollLeft(),i?val:jQuery(window).scrollTop()):this[method]=val;}):this[0]==window||this[0]==document?self[i?'pageYOffset':'pageXOffset']||jQuery.boxModel&&document.documentElement[method]||document.body[method]:this[0][method];};});jQuery.each(["Height","Width"],function(i,name){var tl=i?"Left":"Top",br=i?"Right":"Bottom";jQuery.fn["inner"+name]=function(){return this[name.toLowerCase()]()+num(this,"padding"+tl)+num(this,"padding"+br);};jQuery.fn["outer"+name]=function(margin){return this["inner"+name]()+num(this,"border"+tl+"Width")+num(this,"border"+br+"Width")+(margin?num(this,"margin"+tl)+num(this,"margin"+br):0);};});})(); \ No newline at end of file
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/js/quicksearch.js b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/js/quicksearch.js
deleted file mode 100644
index 70dbd33cd9..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/js/quicksearch.js
+++ /dev/null
@@ -1,114 +0,0 @@
-/**
- *
- * JQuery QuickSearch - Hook up a form field to hide non-matching elements.
- * $Id: quicksearch.js 53 2009-01-07 02:52:03Z deveiant $
- *
- * Author: Michael Granger <mgranger@laika.com>
- *
- */
-jQuery.fn.quicksearch = function( target, searchElems, options ) {
- // console.debug( "Quicksearch fn" );
-
- var settings = {
- delay: 250,
- clearButton: false,
- highlightMatches: false,
- focusOnLoad: false,
- noSearchResultsIndicator: null
- };
- if ( options ) $.extend( settings, options );
-
- return jQuery(this).each( function() {
- // console.debug( "Creating a new quicksearch on %o for %o", this, searchElems );
- new jQuery.quicksearch( this, searchElems, settings );
- });
-};
-
-
-jQuery.quicksearch = function( searchBox, searchElems, settings ) {
- var timeout;
- var boxdiv = $(searchBox).parents('div').eq(0);
-
- function init() {
- setupKeyEventHandlers();
- focusOnLoad();
- };
-
- function setupKeyEventHandlers() {
- // console.debug( "Hooking up the 'keypress' event to %o", searchBox );
- $(searchBox).
- unbind( 'keyup' ).
- keyup( function(e) { return onSearchKey( e.keyCode ); });
- $(searchBox).
- unbind( 'keypress' ).
- keypress( function(e) {
- switch( e.which ) {
- // Execute the search on Enter, Tab, or Newline
- case 9:
- case 13:
- case 10:
- clearTimeout( timeout );
- e.preventDefault();
- doQuickSearch();
- break;
-
- // Allow backspace
- case 8:
- return true;
- break;
-
- // Only allow valid search characters
- default:
- return validQSChar( e.charCode );
- }
- });
- };
-
- function focusOnLoad() {
- if ( !settings.focusOnLoad ) return false;
- $(searchBox).focus();
- };
-
- function onSearchKey ( code ) {
- clearTimeout( timeout );
- // console.debug( "...scheduling search." );
- timeout = setTimeout( doQuickSearch, settings.delay );
- };
-
- function validQSChar( code ) {
- var c = String.fromCharCode( code );
- return (
- (c == ':') ||
- (c >= 'a' && c <= 'z') ||
- (c >= 'A' && c <= 'Z')
- );
- };
-
- function doQuickSearch() {
- var searchText = searchBox.value;
- var pat = new RegExp( searchText, "im" );
- var shownCount = 0;
-
- if ( settings.noSearchResultsIndicator ) {
- $('#' + settings.noSearchResultsIndicator).hide();
- }
-
- // All elements start out hidden
- $(searchElems).each( function(index) {
- var str = $(this).text();
-
- if ( pat.test(str) ) {
- shownCount += 1;
- $(this).fadeIn();
- } else {
- $(this).hide();
- }
- });
-
- if ( shownCount == 0 && settings.noSearchResultsIndicator ) {
- $('#' + settings.noSearchResultsIndicator).slideDown();
- }
- };
-
- init();
-};
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/js/thickbox-compressed.js b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/js/thickbox-compressed.js
deleted file mode 100644
index 3a3fdae1fb..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/js/thickbox-compressed.js
+++ /dev/null
@@ -1,10 +0,0 @@
-/*
- * Thickbox 3 - One Box To Rule Them All.
- * By Cody Lindley (http://www.codylindley.com)
- * Copyright (c) 2007 cody lindley
- * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
-*/
-
-var tb_pathToImage = "../images/loadingAnimation.gif";
-
-eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('$(o).2S(9(){1u(\'a.18, 3n.18, 3i.18\');1w=1p 1t();1w.L=2H});9 1u(b){$(b).s(9(){6 t=X.Q||X.1v||M;6 a=X.u||X.23;6 g=X.1N||P;19(t,a,g);X.2E();H P})}9 19(d,f,g){3m{3(2t o.v.J.2i==="2g"){$("v","11").r({A:"28%",z:"28%"});$("11").r("22","2Z");3(o.1Y("1F")===M){$("v").q("<U 5=\'1F\'></U><4 5=\'B\'></4><4 5=\'8\'></4>");$("#B").s(G)}}n{3(o.1Y("B")===M){$("v").q("<4 5=\'B\'></4><4 5=\'8\'></4>");$("#B").s(G)}}3(1K()){$("#B").1J("2B")}n{$("#B").1J("2z")}3(d===M){d=""}$("v").q("<4 5=\'K\'><1I L=\'"+1w.L+"\' /></4>");$(\'#K\').2y();6 h;3(f.O("?")!==-1){h=f.3l(0,f.O("?"))}n{h=f}6 i=/\\.2s$|\\.2q$|\\.2m$|\\.2l$|\\.2k$/;6 j=h.1C().2h(i);3(j==\'.2s\'||j==\'.2q\'||j==\'.2m\'||j==\'.2l\'||j==\'.2k\'){1D="";1G="";14="";1z="";1x="";R="";1n="";1r=P;3(g){E=$("a[@1N="+g+"]").36();25(D=0;((D<E.1c)&&(R===""));D++){6 k=E[D].u.1C().2h(i);3(!(E[D].u==f)){3(1r){1z=E[D].Q;1x=E[D].u;R="<1e 5=\'1X\'>&1d;&1d;<a u=\'#\'>2T &2R;</a></1e>"}n{1D=E[D].Q;1G=E[D].u;14="<1e 5=\'1U\'>&1d;&1d;<a u=\'#\'>&2O; 2N</a></1e>"}}n{1r=1b;1n="1t "+(D+1)+" 2L "+(E.1c)}}}S=1p 1t();S.1g=9(){S.1g=M;6 a=2x();6 x=a[0]-1M;6 y=a[1]-1M;6 b=S.z;6 c=S.A;3(b>x){c=c*(x/b);b=x;3(c>y){b=b*(y/c);c=y}}n 3(c>y){b=b*(y/c);c=y;3(b>x){c=c*(x/b);b=x}}13=b+30;1a=c+2G;$("#8").q("<a u=\'\' 5=\'1L\' Q=\'1o\'><1I 5=\'2F\' L=\'"+f+"\' z=\'"+b+"\' A=\'"+c+"\' 23=\'"+d+"\'/></a>"+"<4 5=\'2D\'>"+d+"<4 5=\'2C\'>"+1n+14+R+"</4></4><4 5=\'2A\'><a u=\'#\' 5=\'Z\' Q=\'1o\'>1l</a> 1k 1j 1s</4>");$("#Z").s(G);3(!(14==="")){9 12(){3($(o).N("s",12)){$(o).N("s",12)}$("#8").C();$("v").q("<4 5=\'8\'></4>");19(1D,1G,g);H P}$("#1U").s(12)}3(!(R==="")){9 1i(){$("#8").C();$("v").q("<4 5=\'8\'></4>");19(1z,1x,g);H P}$("#1X").s(1i)}o.1h=9(e){3(e==M){I=2w.2v}n{I=e.2u}3(I==27){G()}n 3(I==3k){3(!(R=="")){o.1h="";1i()}}n 3(I==3j){3(!(14=="")){o.1h="";12()}}};16();$("#K").C();$("#1L").s(G);$("#8").r({Y:"T"})};S.L=f}n{6 l=f.2r(/^[^\\?]+\\??/,\'\');6 m=2p(l);13=(m[\'z\']*1)+30||3h;1a=(m[\'A\']*1)+3g||3f;W=13-30;V=1a-3e;3(f.O(\'2j\')!=-1){1E=f.1B(\'3d\');$("#15").C();3(m[\'1A\']!="1b"){$("#8").q("<4 5=\'2f\'><4 5=\'1H\'>"+d+"</4><4 5=\'2e\'><a u=\'#\' 5=\'Z\' Q=\'1o\'>1l</a> 1k 1j 1s</4></4><U 1W=\'0\' 2d=\'0\' L=\'"+1E[0]+"\' 5=\'15\' 1v=\'15"+1f.2c(1f.1y()*2b)+"\' 1g=\'1m()\' J=\'z:"+(W+29)+"p;A:"+(V+17)+"p;\' > </U>")}n{$("#B").N();$("#8").q("<U 1W=\'0\' 2d=\'0\' L=\'"+1E[0]+"\' 5=\'15\' 1v=\'15"+1f.2c(1f.1y()*2b)+"\' 1g=\'1m()\' J=\'z:"+(W+29)+"p;A:"+(V+17)+"p;\'> </U>")}}n{3($("#8").r("Y")!="T"){3(m[\'1A\']!="1b"){$("#8").q("<4 5=\'2f\'><4 5=\'1H\'>"+d+"</4><4 5=\'2e\'><a u=\'#\' 5=\'Z\'>1l</a> 1k 1j 1s</4></4><4 5=\'F\' J=\'z:"+W+"p;A:"+V+"p\'></4>")}n{$("#B").N();$("#8").q("<4 5=\'F\' 3c=\'3b\' J=\'z:"+W+"p;A:"+V+"p;\'></4>")}}n{$("#F")[0].J.z=W+"p";$("#F")[0].J.A=V+"p";$("#F")[0].3a=0;$("#1H").11(d)}}$("#Z").s(G);3(f.O(\'37\')!=-1){$("#F").q($(\'#\'+m[\'26\']).1T());$("#8").24(9(){$(\'#\'+m[\'26\']).q($("#F").1T())});16();$("#K").C();$("#8").r({Y:"T"})}n 3(f.O(\'2j\')!=-1){16();3($.1q.35){$("#K").C();$("#8").r({Y:"T"})}}n{$("#F").34(f+="&1y="+(1p 33().32()),9(){16();$("#K").C();1u("#F a.18");$("#8").r({Y:"T"})})}}3(!m[\'1A\']){o.21=9(e){3(e==M){I=2w.2v}n{I=e.2u}3(I==27){G()}}}}31(e){}}9 1m(){$("#K").C();$("#8").r({Y:"T"})}9 G(){$("#2Y").N("s");$("#Z").N("s");$("#8").2X("2W",9(){$(\'#8,#B,#1F\').2V("24").N().C()});$("#K").C();3(2t o.v.J.2i=="2g"){$("v","11").r({A:"1Z",z:"1Z"});$("11").r("22","")}o.1h="";o.21="";H P}9 16(){$("#8").r({2U:\'-\'+20((13/2),10)+\'p\',z:13+\'p\'});3(!(1V.1q.2Q&&1V.1q.2P<7)){$("#8").r({38:\'-\'+20((1a/2),10)+\'p\'})}}9 2p(a){6 b={};3(!a){H b}6 c=a.1B(/[;&]/);25(6 i=0;i<c.1c;i++){6 d=c[i].1B(\'=\');3(!d||d.1c!=2){39}6 e=2a(d[0]);6 f=2a(d[1]);f=f.2r(/\\+/g,\' \');b[e]=f}H b}9 2x(){6 a=o.2M;6 w=1S.2o||1R.2o||(a&&a.1Q)||o.v.1Q;6 h=1S.1P||1R.1P||(a&&a.2n)||o.v.2n;1O=[w,h];H 1O}9 1K(){6 a=2K.2J.1C();3(a.O(\'2I\')!=-1&&a.O(\'3o\')!=-1){H 1b}}',62,211,'|||if|div|id|var||TB_window|function||||||||||||||else|document|px|append|css|click||href|body||||width|height|TB_overlay|remove|TB_Counter|TB_TempArray|TB_ajaxContent|tb_remove|return|keycode|style|TB_load|src|null|unbind|indexOf|false|title|TB_NextHTML|imgPreloader|block|iframe|ajaxContentH|ajaxContentW|this|display|TB_closeWindowButton||html|goPrev|TB_WIDTH|TB_PrevHTML|TB_iframeContent|tb_position||thickbox|tb_show|TB_HEIGHT|true|length|nbsp|span|Math|onload|onkeydown|goNext|Esc|or|close|tb_showIframe|TB_imageCount|Close|new|browser|TB_FoundURL|Key|Image|tb_init|name|imgLoader|TB_NextURL|random|TB_NextCaption|modal|split|toLowerCase|TB_PrevCaption|urlNoQuery|TB_HideSelect|TB_PrevURL|TB_ajaxWindowTitle|img|addClass|tb_detectMacXFF|TB_ImageOff|150|rel|arrayPageSize|innerHeight|clientWidth|self|window|children|TB_prev|jQuery|frameborder|TB_next|getElementById|auto|parseInt|onkeyup|overflow|alt|unload|for|inlineId||100||unescape|1000|round|hspace|TB_closeAjaxWindow|TB_title|undefined|match|maxHeight|TB_iframe|bmp|gif|png|clientHeight|innerWidth|tb_parseQuery|jpeg|replace|jpg|typeof|which|keyCode|event|tb_getPageSize|show|TB_overlayBG|TB_closeWindow|TB_overlayMacFFBGHack|TB_secondLine|TB_caption|blur|TB_Image|60|tb_pathToImage|mac|userAgent|navigator|of|documentElement|Prev|lt|version|msie|gt|ready|Next|marginLeft|trigger|fast|fadeOut|TB_imageOff|hidden||catch|getTime|Date|load|safari|get|TB_inline|marginTop|continue|scrollTop|TB_modal|class|TB_|45|440|40|630|input|188|190|substr|try|area|firefox'.split('|'),0,{})) \ No newline at end of file
diff --git a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/rdoc.css b/ruby_1_9_3/lib/rdoc/generator/template/darkfish/rdoc.css
deleted file mode 100644
index ea91421837..0000000000
--- a/ruby_1_9_3/lib/rdoc/generator/template/darkfish/rdoc.css
+++ /dev/null
@@ -1,763 +0,0 @@
-/*
- * "Darkfish" Rdoc CSS
- * $Id: rdoc.css 54 2009-01-27 01:09:48Z deveiant $
- *
- * Author: Michael Granger <ged@FaerieMUD.org>
- *
- */
-
-/* Base Green is: #6C8C22 */
-
-*{ padding: 0; margin: 0; }
-
-body {
- background: #efefef;
- font: 14px "Helvetica Neue", Helvetica, Tahoma, sans-serif;
-}
-body.class, body.module, body.file {
- margin-left: 40px;
-}
-body.file-popup {
- font-size: 90%;
- margin-left: 0;
-}
-
-h1 {
- font-size: 300%;
- text-shadow: rgba(135,145,135,0.65) 2px 2px 3px;
- color: #6C8C22;
-}
-h2,h3,h4 { margin-top: 1.5em; }
-
-:link,
-:visited {
- color: #6C8C22;
- text-decoration: none;
-}
-:link:hover,
-:visited:hover {
- border-bottom: 1px dotted #6C8C22;
-}
-
-pre {
- background: #ddd;
- padding: 0.5em 0;
-}
-
-
-/* @group Generic Classes */
-
-.initially-hidden {
- display: none;
-}
-
-.quicksearch-field {
- width: 98%;
- background: #ddd;
- border: 1px solid #aaa;
- height: 1.5em;
- -webkit-border-radius: 4px;
-}
-.quicksearch-field:focus {
- background: #f1edba;
-}
-
-.missing-docs {
- font-size: 120%;
- background: white url(images/wrench_orange.png) no-repeat 4px center;
- color: #ccc;
- line-height: 2em;
- border: 1px solid #d00;
- opacity: 1;
- padding-left: 20px;
- text-indent: 24px;
- letter-spacing: 3px;
- font-weight: bold;
- -webkit-border-radius: 5px;
- -moz-border-radius: 5px;
-}
-
-.target-section {
- border: 2px solid #dcce90;
- border-left-width: 8px;
- padding: 0 1em;
- background: #fff3c2;
-}
-
-/* @end */
-
-
-/* @group Index Page, Standalone file pages */
-body.indexpage {
- margin: 1em 3em;
-}
-body.indexpage p,
-body.indexpage div,
-body.file p {
- margin: 1em 0;
-}
-
-.indexpage .rdoc-list p, .file .rdoc-list p {
- margin: 0em 0;
-}
-
-.indexpage ol,
-.file #documentation ol {
- line-height: 160%;
-}
-
-.indexpage ul,
-.file #documentation ul {
- line-height: 160%;
- list-style: none;
-}
-.indexpage ul :link,
-.indexpage ul :visited {
- font-size: 16px;
-}
-
-.indexpage li,
-.file #documentation li {
- padding-left: 20px;
-}
-
-.indexpage ol,
-.file #documentation ol {
- margin-left: 20px;
-}
-
-.indexpage ol > li,
-.file #documentation ol > li {
- padding-left: 0;
-}
-
-.indexpage ul > li,
-.file #documentation ul > li {
- background: url(images/bullet_black.png) no-repeat left 4px;
-}
-.indexpage li.module {
- background: url(images/package.png) no-repeat left 4px;
-}
-.indexpage li.class {
- background: url(images/ruby.png) no-repeat left 4px;
-}
-.indexpage li.file {
- background: url(images/page_white_text.png) no-repeat left 4px;
-}
-.file li p,
-.indexpage li p {
- margin: 0 0;
-}
-
-/* @end */
-
-/* @group Top-Level Structure */
-
-.class #metadata,
-.file #metadata,
-.module #metadata {
- float: left;
- width: 260px;
-}
-
-.class #documentation,
-.file #documentation,
-.module #documentation {
- margin: 2em 1em 5em 300px;
- min-width: 340px;
-}
-
-.file #metadata {
- margin: 0.8em;
-}
-
-#validator-badges {
- clear: both;
- margin: 1em 1em 2em;
-}
-
-/* @end */
-
-/* @group Metadata Section */
-#metadata .section {
- background-color: #dedede;
- -moz-border-radius: 5px;
- -webkit-border-radius: 5px;
- border: 1px solid #aaa;
- margin: 0 8px 16px;
- font-size: 90%;
- overflow: hidden;
-}
-#metadata h3.section-header {
- margin: 0;
- padding: 2px 8px;
- background: #ccc;
- color: #666;
- -moz-border-radius-topleft: 4px;
- -moz-border-radius-topright: 4px;
- -webkit-border-top-left-radius: 4px;
- -webkit-border-top-right-radius: 4px;
- border-bottom: 1px solid #aaa;
-}
-#metadata #home-section h3.section-header {
- border-bottom: 0;
-}
-
-#metadata ul,
-#metadata dl,
-#metadata p {
- padding: 8px;
- list-style: none;
-}
-
-#file-metadata ul {
- padding-left: 28px;
- list-style-image: url(images/page_green.png);
-}
-
-dl.svninfo {
- color: #666;
- margin: 0;
-}
-dl.svninfo dt {
- font-weight: bold;
-}
-
-ul.link-list li {
- white-space: nowrap;
-}
-ul.link-list .type {
- font-size: 8px;
- text-transform: uppercase;
- color: white;
- background: #969696;
- padding: 2px 4px;
- -webkit-border-radius: 5px;
-}
-
-/* @end */
-
-
-/* @group Project Metadata Section */
-#project-metadata {
- margin-top: 3em;
-}
-
-.file #project-metadata {
- margin-top: 0em;
-}
-
-#project-metadata .section {
- border: 1px solid #aaa;
-}
-#project-metadata h3.section-header {
- border-bottom: 1px solid #aaa;
- position: relative;
-}
-#project-metadata h3.section-header .search-toggle {
- position: absolute;
- right: 5px;
-}
-
-
-#project-metadata form {
- color: #777;
- background: #ccc;
- padding: 8px 8px 16px;
- border-bottom: 1px solid #bbb;
-}
-#project-metadata fieldset {
- border: 0;
-}
-
-#no-class-search-results {
- margin: 0 auto 1em;
- text-align: center;
- font-size: 14px;
- font-weight: bold;
- color: #aaa;
-}
-
-/* @end */
-
-
-/* @group Documentation Section */
-.description {
- font-size: 100%;
- color: #333;
-}
-
-.description p {
- margin: 1em 0.4em;
-}
-
-.description li p {
- margin: 0;
-}
-
-.description ul {
- margin-left: 1.5em;
-}
-.description ul li {
- line-height: 1.4em;
-}
-
-.description dl,
-#documentation dl {
- margin: 8px 1.5em;
- border: 1px solid #ccc;
-}
-.description dl {
- font-size: 14px;
-}
-
-.description dt,
-#documentation dt {
- padding: 2px 4px;
- font-weight: bold;
- background: #ddd;
-}
-.description dd,
-#documentation dd {
- padding: 2px 12px;
-}
-.description dd + dt,
-#documentation dd + dt {
- margin-top: 0.7em;
-}
-
-#documentation .section {
- font-size: 90%;
-}
-
-#documentation h2.section-header {
- margin-top: 2em;
- padding: 0.75em 0.5em;
- background: #ccc;
- color: #333;
- font-size: 175%;
- border: 1px solid #bbb;
- -moz-border-radius: 3px;
- -webkit-border-radius: 3px;
-}
-
-#documentation h3.section-header {
- margin-top: 2em;
- padding: 0.25em 0.5em;
- background-color: #dedede;
- color: #333;
- font-size: 150%;
- border: 1px solid #bbb;
- -moz-border-radius: 3px;
- -webkit-border-radius: 3px;
-}
-
-#constants-list > dl,
-#attributes-list > dl {
- margin: 1em 0 2em;
- border: 0;
-}
-#constants-list > dl dt,
-#attributes-list > dl dt {
- padding-left: 0;
- font-weight: bold;
- font-family: Monaco, "Andale Mono";
- background: inherit;
-}
-#constants-list > dl dt a,
-#attributes-list > dl dt a {
- color: inherit;
-}
-#constants-list > dl dd,
-#attributes-list > dl dd {
- margin: 0 0 1em 0;
- padding: 0;
- color: #666;
-}
-
-.documentation-section h2 {
- position: relative;
-}
-
-.documentation-section h2 a {
- position: absolute;
- top: 8px;
- right: 10px;
- font-size: 12px;
- color: #9b9877;
- visibility: hidden;
-}
-
-.documentation-section h2:hover a {
- visibility: visible;
-}
-
-/* @group Method Details */
-
-#documentation .method-source-code {
- display: none;
-}
-
-#documentation .method-detail {
- margin: 0.5em 0;
- padding: 0.5em 0;
- cursor: pointer;
-}
-#documentation .method-detail:hover {
- background-color: #f1edba;
-}
-#documentation .method-heading {
- position: relative;
- padding: 2px 4px 0 20px;
- font-size: 125%;
- font-weight: bold;
- color: #333;
- background: url(images/brick.png) no-repeat left bottom;
-}
-#documentation .method-heading :link,
-#documentation .method-heading :visited {
- color: inherit;
-}
-#documentation .method-click-advice {
- position: absolute;
- top: 2px;
- right: 5px;
- font-size: 10px;
- color: #9b9877;
- visibility: hidden;
- padding-right: 20px;
- line-height: 20px;
- background: url(images/zoom.png) no-repeat right top;
-}
-#documentation .method-detail:hover .method-click-advice {
- visibility: visible;
-}
-
-#documentation .method-alias .method-heading {
- color: #666;
- background: url(images/brick_link.png) no-repeat left bottom;
-}
-
-#documentation .method-description,
-#documentation .aliases {
- margin: 0 20px;
- color: #666;
-}
-
-#documentation .method-description p,
-#documentation .aliases p {
- line-height: 1.2em;
-}
-
-#documentation .aliases {
- padding-top: 4px;
- font-style: italic;
- cursor: default;
-}
-#documentation .method-description p {
- padding: 0;
-}
-#documentation .method-description p + p {
- margin-bottom: 0.5em;
-}
-#documentation .method-description ul {
- margin-left: 1.5em;
-}
-
-#documentation .attribute-method-heading {
- background: url(images/tag_green.png) no-repeat left bottom;
-}
-#documentation #attribute-method-details .method-detail:hover {
- background-color: transparent;
- cursor: default;
-}
-#documentation .attribute-access-type {
- font-size: 60%;
- text-transform: uppercase;
- vertical-align: super;
- padding: 0 2px;
-}
-/* @end */
-
-/* @end */
-
-
-
-/* @group Source Code */
-
-div.method-source-code {
- background: #262626;
- color: #efefef;
- margin: 1em;
- padding: 0.5em;
- border: 1px dashed #999;
- overflow: hidden;
-}
-
-div.method-source-code pre {
- background: inherit;
- padding: 0;
- color: white;
- overflow: auto;
-}
-
-/* @group Ruby keyword styles */
-
-.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; }
-
-/* @end */
-/* @end */
-
-
-/* @group File Popup Contents */
-
-.file #metadata,
-.file-popup #metadata {
-}
-
-.file-popup dl {
- font-size: 80%;
- padding: 0.75em;
- background-color: #dedede;
- color: #333;
- border: 1px solid #bbb;
- -moz-border-radius: 3px;
- -webkit-border-radius: 3px;
-}
-.file dt {
- font-weight: bold;
- padding-left: 22px;
- line-height: 20px;
- background: url(images/page_white_width.png) no-repeat left top;
-}
-.file dt.modified-date {
- background: url(images/date.png) no-repeat left top;
-}
-.file dt.requires {
- background: url(images/plugin.png) no-repeat left top;
-}
-.file dt.scs-url {
- background: url(images/wrench.png) no-repeat left top;
-}
-
-.file dl dd {
- margin: 0 0 1em 0;
-}
-.file #metadata dl dd ul {
- list-style: circle;
- margin-left: 20px;
- padding-top: 0;
-}
-.file #metadata dl dd ul li {
-}
-
-
-.file h2 {
- margin-top: 2em;
- padding: 0.75em 0.5em;
- background-color: #dedede;
- color: #333;
- font-size: 120%;
- border: 1px solid #bbb;
- -moz-border-radius: 3px;
- -webkit-border-radius: 3px;
-}
-
-/* @end */
-
-
-
-
-/* @group ThickBox Styles */
-#TB_window {
- font: 12px Arial, Helvetica, sans-serif;
- color: #333333;
-}
-
-#TB_secondLine {
- font: 10px Arial, Helvetica, sans-serif;
- color:#666666;
-}
-
-#TB_window :link,
-#TB_window :visited { color: #666666; }
-#TB_window :link:hover,
-#TB_window :visited:hover { color: #000; }
-#TB_window :link:active,
-#TB_window :visited:active { color: #666666; }
-#TB_window :link:focus,
-#TB_window :visited:focus { color: #666666; }
-
-#TB_overlay {
- position: fixed;
- z-index:100;
- top: 0px;
- left: 0px;
- height:100%;
- width:100%;
-}
-
-.TB_overlayMacFFBGHack {background: url(images/macFFBgHack.png) repeat;}
-.TB_overlayBG {
- background-color:#000;
- filter:alpha(opacity=75);
- -moz-opacity: 0.75;
- opacity: 0.75;
-}
-
-* html #TB_overlay { /* ie6 hack */
- position: absolute;
- height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
-}
-
-#TB_window {
- position: fixed;
- background: #ffffff;
- z-index: 102;
- color:#000000;
- display:none;
- border: 4px solid #525252;
- text-align:left;
- top:50%;
- left:50%;
-}
-
-* html #TB_window { /* ie6 hack */
- position: absolute;
- margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px');
-}
-
-#TB_window img#TB_Image {
- display:block;
- margin: 15px 0 0 15px;
- border-right: 1px solid #ccc;
- border-bottom: 1px solid #ccc;
- border-top: 1px solid #666;
- border-left: 1px solid #666;
-}
-
-#TB_caption{
- height:25px;
- padding:7px 30px 10px 25px;
- float:left;
-}
-
-#TB_closeWindow{
- height:25px;
- padding:11px 25px 10px 0;
- float:right;
-}
-
-#TB_closeAjaxWindow{
- padding:7px 10px 5px 0;
- margin-bottom:1px;
- text-align:right;
- float:right;
-}
-
-#TB_ajaxWindowTitle{
- float:left;
- padding:7px 0 5px 10px;
- margin-bottom:1px;
- font-size: 22px;
-}
-
-#TB_title{
- background-color: #6C8C22;
- color: #dedede;
- height:40px;
-}
-#TB_title :link,
-#TB_title :visited {
- color: white !important;
- border-bottom: 1px dotted #dedede;
-}
-
-#TB_ajaxContent{
- clear:both;
- padding:2px 15px 15px 15px;
- overflow:auto;
- text-align:left;
- line-height:1.4em;
-}
-
-#TB_ajaxContent.TB_modal{
- padding:15px;
-}
-
-#TB_ajaxContent p{
- padding:5px 0px 5px 0px;
-}
-
-#TB_load{
- position: fixed;
- display:none;
- height:13px;
- width:208px;
- z-index:103;
- top: 50%;
- left: 50%;
- margin: -6px 0 0 -104px; /* -height/2 0 0 -width/2 */
-}
-
-* html #TB_load { /* ie6 hack */
- position: absolute;
- margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px');
-}
-
-#TB_HideSelect{
- z-index:99;
- position:fixed;
- top: 0;
- left: 0;
- background-color:#fff;
- border:none;
- filter:alpha(opacity=0);
- -moz-opacity: 0;
- opacity: 0;
- height:100%;
- width:100%;
-}
-
-* html #TB_HideSelect { /* ie6 hack */
- position: absolute;
- height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
-}
-
-#TB_iframeContent{
- clear:both;
- border:none;
- margin-bottom:-1px;
- margin-top:1px;
- _margin-bottom:1px;
-}
-
-/* @end */
-
-/* @group Debugging Section */
-
-#debugging-toggle {
- text-align: center;
-}
-#debugging-toggle img {
- cursor: pointer;
-}
-
-#rdoc-debugging-section-dump {
- display: none;
- margin: 0 2em 2em;
- background: #ccc;
- border: 1px solid #999;
-}
-
-
-
-/* @end */
diff --git a/ruby_1_9_3/lib/rdoc/ghost_method.rb b/ruby_1_9_3/lib/rdoc/ghost_method.rb
deleted file mode 100644
index 192b46f51f..0000000000
--- a/ruby_1_9_3/lib/rdoc/ghost_method.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-require 'rdoc/any_method'
-
-##
-# GhostMethod represents a method referenced only by a comment
-
-class RDoc::GhostMethod < RDoc::AnyMethod
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/include.rb b/ruby_1_9_3/lib/rdoc/include.rb
deleted file mode 100644
index 9cebd3d8ef..0000000000
--- a/ruby_1_9_3/lib/rdoc/include.rb
+++ /dev/null
@@ -1,100 +0,0 @@
-require 'rdoc/code_object'
-
-##
-# A Module include in a class with \#include
-
-class RDoc::Include < RDoc::CodeObject
-
- ##
- # Name of included module
-
- attr_accessor :name
-
- ##
- # Creates a new Include for +name+ with +comment+
-
- def initialize(name, comment)
- super()
- @name = name
- self.comment = comment
- @module = nil # cache for module if found
- end
-
- ##
- # Includes are sorted by name
-
- def <=> other
- return unless self.class === other
-
- name <=> other.name
- end
-
- def == other # :nodoc:
- self.class == other.class and
- self.name == other.name
- end
-
- ##
- # Full name based on #module
-
- def full_name
- m = self.module
- RDoc::ClassModule === m ? m.full_name : @name
- end
-
- def inspect # :nodoc:
- "#<%s:0x%x %s.include %s>" % [
- self.class,
- object_id,
- parent_name, @name,
- ]
- end
-
- ##
- # Attempts to locate the included module object. Returns the name if not
- # known.
- #
- # The scoping rules of Ruby to resolve the name of an included module are:
- # - first look into the children of the current context;
- # - if not found, look into the children of included modules,
- # in reverse inclusion order;
- # - if still not found, go up the hierarchy of names.
-
- def module
- return @module if @module
-
- # search the current context
- return @name unless parent
- full_name = parent.child_name(@name)
- @module = RDoc::TopLevel.modules_hash[full_name]
- return @module if @module
- return @name if @name =~ /^::/
-
- # search the includes before this one, in reverse order
- searched = parent.includes.take_while { |i| i != self }.reverse
- searched.each do |i|
- inc = i.module
- next if String === inc
- full_name = inc.child_name(@name)
- @module = RDoc::TopLevel.modules_hash[full_name]
- return @module if @module
- end
-
- # go up the hierarchy of names
- p = parent.parent
- while p
- full_name = p.child_name(@name)
- @module = RDoc::TopLevel.modules_hash[full_name]
- return @module if @module
- p = p.parent
- end
-
- @name
- end
-
- def to_s # :nodoc:
- "include #@name in: #{parent}"
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/known_classes.rb b/ruby_1_9_3/lib/rdoc/known_classes.rb
deleted file mode 100644
index 863be4bd5c..0000000000
--- a/ruby_1_9_3/lib/rdoc/known_classes.rb
+++ /dev/null
@@ -1,72 +0,0 @@
-module RDoc
-
- ##
- # Ruby's built-in classes, modules and exceptions
-
- KNOWN_CLASSES = {
- "rb_cArray" => "Array",
- "rb_cBasicObject" => "BasicObject",
- "rb_cBignum" => "Bignum",
- "rb_cClass" => "Class",
- "rb_cData" => "Data",
- "rb_cDir" => "Dir",
- "rb_cEncoding" => "Encoding",
- "rb_cFalseClass" => "FalseClass",
- "rb_cFile" => "File",
- "rb_cFixnum" => "Fixnum",
- "rb_cFloat" => "Float",
- "rb_cHash" => "Hash",
- "rb_cIO" => "IO",
- "rb_cInteger" => "Integer",
- "rb_cModule" => "Module",
- "rb_cNilClass" => "NilClass",
- "rb_cNumeric" => "Numeric",
- "rb_cObject" => "Object",
- "rb_cProc" => "Proc",
- "rb_cRange" => "Range",
- "rb_cRegexp" => "Regexp",
- "rb_cRubyVM" => "RubyVM",
- "rb_cSocket" => "Socket",
- "rb_cString" => "String",
- "rb_cStruct" => "Struct",
- "rb_cSymbol" => "Symbol",
- "rb_cThread" => "Thread",
- "rb_cTime" => "Time",
- "rb_cTrueClass" => "TrueClass",
-
- "rb_eArgError" => "ArgError",
- "rb_eEOFError" => "EOFError",
- "rb_eException" => "Exception",
- "rb_eFatal" => "fatal",
- "rb_eFloatDomainError" => "FloatDomainError",
- "rb_eIOError" => "IOError",
- "rb_eIndexError" => "IndexError",
- "rb_eInterrupt" => "Interrupt",
- "rb_eLoadError" => "LoadError",
- "rb_eNameError" => "NameError",
- "rb_eNoMemError" => "NoMemError",
- "rb_eNotImpError" => "NotImpError",
- "rb_eRangeError" => "RangeError",
- "rb_eRuntimeError" => "RuntimeError",
- "rb_eScriptError" => "ScriptError",
- "rb_eSecurityError" => "SecurityError",
- "rb_eSignal" => "SignalException",
- "rb_eStandardError" => "StandardError",
- "rb_eSyntaxError" => "SyntaxError",
- "rb_eSystemCallError" => "SystemCallError",
- "rb_eSystemExit" => "SystemExit",
- "rb_eTypeError" => "TypeError",
- "rb_eZeroDivError" => "ZeroDivError",
-
- "rb_mComparable" => "Comparable",
- "rb_mDL" => "DL",
- "rb_mEnumerable" => "Enumerable",
- "rb_mErrno" => "Errno",
- "rb_mFileTest" => "FileTest",
- "rb_mGC" => "GC",
- "rb_mKernel" => "Kernel",
- "rb_mMath" => "Math",
- "rb_mProcess" => "Process"
- }
-
-end
diff --git a/ruby_1_9_3/lib/rdoc/markup.rb b/ruby_1_9_3/lib/rdoc/markup.rb
deleted file mode 100644
index 07fd5493c8..0000000000
--- a/ruby_1_9_3/lib/rdoc/markup.rb
+++ /dev/null
@@ -1,652 +0,0 @@
-require 'rdoc'
-
-##
-# RDoc::Markup 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.
-#
-# RDoc::Markup itself does no output formatting: this is left to a different
-# set of classes.
-#
-# RDoc::Markup is extendable at runtime: you can add \new markup elements to
-# be recognised in the documents that RDoc::Markup parses.
-#
-# RDoc::Markup 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
-# RDoc::Markup could be the basis for formatting RDoc style comment blocks,
-# Wiki entries, and online FAQs.
-#
-# == Synopsis
-#
-# This code converts +input_string+ to HTML. The conversion takes place in
-# the +convert+ method, so you can use the same RDoc::Markup converter to
-# convert multiple input strings.
-#
-# require 'rdoc/markup/to_html'
-#
-# h = RDoc::Markup::ToHtml.new
-#
-# puts h.convert(input_string)
-#
-# You can extend the RDoc::Markup parser to recognise new markup
-# sequences, and to add special processing for text that matches a
-# regular expression. Here we make WikiWords significant to the parser,
-# and also make the sequences {word} and \<no>text...</no> signify
-# strike-through text. We then subclass the HTML output class to deal
-# with these:
-#
-# require 'rdoc/markup'
-# require 'rdoc/markup/to_html'
-#
-# class WikiHtml < RDoc::Markup::ToHtml
-# def handle_special_WIKIWORD(special)
-# "<font color=red>" + special.text + "</font>"
-# end
-# end
-#
-# markup = RDoc::Markup.new
-# markup.add_word_pair("{", "}", :STRIKE)
-# markup.add_html("no", :STRIKE)
-#
-# markup.add_special(/\b([A-Z][a-z]+[A-Z]\w+)/, :WIKIWORD)
-#
-# wh = WikiHtml.new markup
-# wh.add_tag(:STRIKE, "<strike>", "</strike>")
-#
-# puts "<body>#{wh.convert ARGF.read}</body>"
-#
-# == Encoding
-#
-# Where Encoding support is available, RDoc will automatically convert all
-# documents to the same output encoding. The output encoding can be set via
-# RDoc::Options#encoding and defaults to Encoding.default_external.
-#
-# = \RDoc Markup Reference
-#
-# == Block Markup
-#
-# === Paragraphs and Verbatim
-#
-# The markup engine looks for a document's natural left margin. This is
-# used as the initial margin for the document.
-#
-# Consecutive lines starting at this margin are considered to be a
-# paragraph. Empty lines separate paragraphs.
-#
-# Any line that starts to the right of the current margin is treated
-# as verbatim text. This is useful for code listings:
-#
-# 3.times { puts "Ruby" }
-#
-# In verbatim text, two or more blank lines are collapsed into one,
-# and trailing blank lines are removed:
-#
-# This is the first line
-#
-#
-# This is the second non-blank line,
-# after 2 blank lines in the source markup.
-#
-#
-# There were two trailing blank lines right above this paragraph, that
-# have been removed. In addition, the verbatim text has been shifted
-# left, so the amount of indentation of verbatim text is unimportant.
-#
-# === Headers and Rules
-#
-# A line starting with an equal sign (=) is treated as a
-# heading. Level one headings have one equals sign, level two headings
-# have two, and so on until level six, which is the maximum
-# (seven hyphens or more result in a level six heading).
-#
-# For example, the above header was obtained with:
-# == Headers and Rules
-#
-# 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).
-#
-# In the case of HTML output, three dashes generate a 1-pixel high rule,
-# four dashes result in 2 pixels, and so on. The actual height is limited
-# to 10 pixels:
-#
-# ---
-# -----
-# -----------------------------------------------------
-#
-# produces:
-#
-# ---
-# -----
-# -----------------------------------------------------
-#
-# === Simple Lists
-#
-# If a paragraph starts with a "*", "-", "<digit>." or "<letter>.",
-# then it is taken to be the start of a list. The margin is 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
-#
-# produces:
-#
-# * 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
-#
-# === Labeled Lists
-#
-# 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
-#
-# produces:
-#
-# [cat] a small furry mammal
-# that seems to sleep a lot
-#
-# [ant] a little insect that is known
-# to enjoy picnics
-#
-# If you want the list bodies to line up to the left of the labels,
-# use two colons:
-#
-# cat:: a small furry mammal
-# that seems to sleep a lot
-#
-# ant:: a little insect that is known
-# to enjoy picnics
-#
-# produces:
-#
-# cat:: a small furry mammal
-# that seems to sleep a lot
-#
-# ant:: a little insect that is known
-# to enjoy picnics
-#
-# Notice that blank lines right after the label are ignored in labeled lists:
-#
-# [one]
-#
-# definition 1
-#
-# [two]
-#
-# definition 2
-#
-# produces the same output as
-#
-# [one] definition 1
-# [two] definition 2
-#
-#
-# === Lists and Verbatim
-#
-# If you want to introduce a verbatim section right after a list, it has to be
-# less indented than the list item bodies, but more indented than the list
-# label, letter, digit or bullet. For instance:
-#
-# * point 1
-#
-# * point 2, first paragraph
-#
-# point 2, second paragraph
-# verbatim text inside point 2
-# point 2, third paragraph
-# verbatim text outside of the list (the list is therefore closed)
-# regular paragraph after the list
-#
-# produces:
-#
-# * point 1
-#
-# * point 2, first paragraph
-#
-# point 2, second paragraph
-# verbatim text inside point 2
-# point 2, third paragraph
-# verbatim text outside of the list (the list is therefore closed)
-# regular paragraph after the list
-#
-#
-# == Text Markup
-#
-# === Bold, Italic, Typewriter Text
-#
-# You can use markup within text (except verbatim) to change the
-# appearance of parts of that text. Out of the box, RDoc::Markup
-# supports word-based and general markup.
-#
-# Word-based markup uses flag characters around individual words:
-#
-# <tt>\*_word_\*</tt>:: displays _word_ in a *bold* font
-# <tt>\__word_\_</tt>:: displays _word_ in an _emphasized_ font
-# <tt>\+_word_\+</tt>:: displays _word_ in a +code+ font
-#
-# General markup affects text between a start delimiter and an end
-# delimiter. Not surprisingly, these delimiters look like HTML markup.
-#
-# <tt>\<b>_text_</b></tt>:: displays _text_ in a *bold* font
-# <tt>\<em>_text_</em></tt>:: displays _text_ in an _emphasized_ font
-# (alternate tag: <tt>\<i></tt>)
-# <tt>\<tt>_text_\</tt></tt>:: displays _text_ in a +code+ font
-# (alternate tag: <tt>\<code></tt>)
-#
-# 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 (see <i>Escaping
-# Text Markup</i>, below).
-#
-# === Links
-#
-# Links to starting with +http:+, +https:+, +mailto:+, +ftp:+ or +www.+
-# are recognized. An HTTP url that references an external image file is
-# converted into an inline image element.
-#
-# Links starting with <tt>rdoc-ref:</tt> will link to the referenced class,
-# module, method, file, etc. If the referenced item is not documented the
-# text will be and no link will be generated.
-#
-# Links starting with +link:+ refer to local files whose path is relative to
-# the <tt>--op</tt> directory.
-#
-# Links can also be of the form <tt>label[url]</tt>, in which case +label+ is
-# used in the displayed text, and +url+ is used as the target. If +label+
-# contains multiple words, put it in braces: <tt>{multi word label}[url]</tt>.
-# The +url+ may be an +http:+-type link or a cross-reference to a class,
-# module or method with a label.
-#
-# Links with the <tt>rdoc-ref:</tt> scheme will link to the referenced class,
-# module, method, file, etc. If the referenced item is does not exist
-# no link will be generated and <tt>rdoc-ref:</tt> will be removed from the
-# resulting text.
-#
-# Links starting with +link:+ refer to local files whose path is relative to
-# the <tt>--op</tt> directory. Use <tt>rdoc-ref:</tt> instead of
-# <tt>link:</tt> to link to files generated by RDoc as the link target may
-# be different across RDoc generators.
-#
-# Example links:
-#
-# https://github.com/rdoc/rdoc
-# mailto:user@example.com
-# {RDoc Documentation}[http://rdoc.rubyforge.org]
-# {RDoc Markup}[rdoc-ref:RDoc::Markup]
-#
-# === Escaping Text Markup
-#
-# Text markup can be escaped with a backslash, as in \<tt>, which was obtained
-# with <tt>\\<tt></tt>. Except in verbatim sections and between \<tt> tags,
-# to produce a backslash you have to double it unless it is followed by a
-# space, tab or newline. Otherwise, the HTML formatter will discard it, as it
-# is used to escape potential links:
-#
-# * The \ must be doubled if not followed by white space: \\.
-# * But not in \<tt> tags: in a Regexp, <tt>\S</tt> matches non-space.
-# * This is a link to {ruby-lang}[www.ruby-lang.org].
-# * This is not a link, however: \{ruby-lang.org}[www.ruby-lang.org].
-# * This will not be linked to \RDoc::RDoc#document
-#
-# generates:
-#
-# * The \ must be doubled if not followed by white space: \\.
-# * But not in \<tt> tags: in a Regexp, <tt>\S</tt> matches non-space.
-# * This is a link to {ruby-lang}[www.ruby-lang.org]
-# * This is not a link, however: \{ruby-lang.org}[www.ruby-lang.org]
-# * This will not be linked to \RDoc::RDoc#document
-#
-# Inside \<tt> tags, more precisely, leading backslashes are removed only if
-# followed by a markup character (<tt><*_+</tt>), a backslash, or a known link
-# reference (a known class or method). So in the example above, the backslash
-# of <tt>\S</tt> would be removed if there was a class or module named +S+ in
-# the current context.
-#
-# This behavior is inherited from RDoc version 1, and has been kept for
-# compatibility with existing RDoc documentation.
-#
-# === Conversion of characters
-#
-# HTML will convert two/three dashes to an em-dash. Other common characters are
-# converted as well:
-#
-# em-dash:: -- or ---
-# ellipsis:: ...
-#
-# single quotes:: 'text' or `text'
-# double quotes:: "text" or ``text''
-#
-# copyright:: (c)
-# registered trademark:: (r)
-#
-# produces:
-#
-# em-dash:: -- or ---
-# ellipsis:: ...
-#
-# single quotes:: 'text' or `text'
-# double quotes:: "text" or ``text''
-#
-# copyright:: (c)
-# registered trademark:: (r)
-#
-#
-# == Documenting Source Code
-#
-# Comment blocks can be written fairly naturally, either using <tt>#</tt> on
-# successive lines of the comment, or by including the comment in
-# a <tt>=begin</tt>/<tt>=end</tt> block. If you use the latter form,
-# the <tt>=begin</tt> line _must_ be flagged with an +rdoc+ tag:
-#
-# =begin rdoc
-# Documentation to be processed by RDoc.
-#
-# ...
-# =end
-#
-# RDoc stops processing comments if it finds a comment line starting
-# with <tt>--</tt> right after the <tt>#</tt> character (otherwise,
-# it will be treated as a rule if it has three dashes or more).
-# This can be used to separate external from internal comments,
-# or to stop a comment being associated with a method, class, or module.
-# Commenting can be turned back on with a line that starts with <tt>++</tt>.
-#
-# ##
-# # Extract the age and calculate the date-of-birth.
-# #--
-# # FIXME: fails if the birthday falls on February 29th
-# #++
-# # The DOB is returned as a Time object.
-#
-# def get_dob(person)
-# # ...
-# end
-#
-# Names of classes, files, and any method names containing an underscore or
-# preceded by a hash character are automatically linked from comment text to
-# their description. This linking works inside the current class or module,
-# and with ancestor methods (in included modules or in the superclass).
-#
-# Method parameter lists are extracted and displayed with the method
-# description. If a method calls +yield+, then the parameters passed to yield
-# will also be displayed:
-#
-# def fred
-# ...
-# yield line, address
-#
-# This will get documented as:
-#
-# fred() { |line, address| ... }
-#
-# You can override this using a comment containing ':yields: ...' immediately
-# after the method definition
-#
-# def fred # :yields: index, position
-# # ...
-#
-# yield line, address
-#
-# which will get documented as
-#
-# fred() { |index, position| ... }
-#
-# +:yields:+ is an example of a documentation directive. These appear
-# immediately after the start of the document element they are modifying.
-#
-# RDoc automatically cross-references words with underscores or camel-case.
-# To suppress cross-references, prefix the word with a \ character. To
-# include special characters like "<tt>\n</tt>", you'll need to use
-# two \ characters in normal text, but only one in \<tt> text:
-#
-# "\\n" or "<tt>\n</tt>"
-#
-# produces:
-#
-# "\\n" or "<tt>\n</tt>"
-#
-# == Directives
-#
-# Directives are keywords surrounded by ":" characters.
-#
-# === Controlling what is documented
-#
-# [+:nodoc:+ / <tt>:nodoc: all</tt>]
-# This directive prevents documentation for the element from
-# being generated. For classes and modules, methods, aliases,
-# constants, and attributes directly within the affected class or
-# module also will be omitted. By default, though, modules and
-# classes within that class or module _will_ be documented. This is
-# turned off by adding the +all+ modifier.
-#
-# module MyModule # :nodoc:
-# class Input
-# end
-# end
-#
-# module OtherModule # :nodoc: all
-# class Output
-# end
-# end
-#
-# In the above code, only class <tt>MyModule::Input</tt> will be documented.
-#
-# The +:nodoc:+ directive, like +:enddoc:+, +:stopdoc:+ and +:startdoc:+
-# presented below, is local to the current file: if you do not want to
-# document a module that appears in several files, specify +:nodoc:+ on each
-# appearance, at least once per file.
-#
-# [+:stopdoc:+ / +:startdoc:+]
-# Stop and start adding new documentation elements to the current container.
-# For example, if a class has a number of constants that you don't want to
-# document, put a +:stopdoc:+ before the first, and a +:startdoc:+ after the
-# last. If you don't specify a +:startdoc:+ by the end of the container,
-# disables documentation for the rest of the current file.
-#
-# [+:doc:+]
-# Forces a method or attribute to be documented even if it wouldn't be
-# otherwise. Useful if, for example, you want to include documentation of a
-# particular private method.
-#
-# [+:enddoc:+]
-# Document nothing further at the current level: directives +:startdoc:+ and
-# +:doc:+ that appear after this will not be honored for the current container
-# (file, class or module), in the current file.
-#
-# [+:notnew:+ / +:not_new:+ / +:not-new:+ ]
-# Only applicable to the +initialize+ instance method. Normally RDoc
-# assumes that the documentation and parameters for +initialize+ are
-# actually for the +new+ method, and so fakes out a +new+ for the class.
-# The +:notnew:+ directive stops this. Remember that +initialize+ is private,
-# so you won't see the documentation unless you use the +-a+ command line
-# option.
-#
-# === Other directives
-#
-# [+:include:+ _filename_]
-# Include the contents of the named file at this point. This directive
-# must appear alone on one line, possibly preceded by spaces. In this
-# position, it can be escaped with a \ in front of the first colon.
-#
-# The file will be searched for in the directories listed by the +--include+
-# option, or in the current directory by default. The contents of the file
-# will be shifted to have the same indentation as the ':' at the start of
-# the +:include:+ directive.
-#
-# [+:title:+ _text_]
-# Sets the title for the document. Equivalent to the <tt>--title</tt>
-# command line parameter. (The command line parameter overrides any :title:
-# directive in the source).
-#
-# [+:main:+ _name_]
-# Equivalent to the <tt>--main</tt> command line parameter.
-#
-# [<tt>:category: section</tt>]
-# Adds this item to the named +section+ overriding the current section. Use
-# this to group methods by section in RDoc output while maintaining a
-# sensible ordering (like alphabetical).
-#
-# # :category: Utility Methods
-# #
-# # CGI escapes +text+
-#
-# def convert_string text
-# CGI.escapeHTML text
-# end
-#
-# An empty category will place the item in the default category:
-#
-# # :category:
-# #
-# # This method is in the default category
-#
-# def some_method
-# # ...
-# end
-#
-# Unlike the :section: directive, :category: is not sticky. The category
-# only applies to the item immediately following the comment.
-#
-# Use the :section: directive to provide introductory text for a section of
-# documentation.
-#
-# [<tt>:section: title</tt>]
-# Provides section introductory text in RDoc output. The title following
-# +:section:+ is used as the section name and the remainder of the comment
-# containing the section is used as introductory text. A section's comment
-# block must be separated from following comment blocks. Use an empty title
-# to switch to the default section.
-#
-# The :section: directive is sticky, so subsequent methods, aliases,
-# attributes, and classes will be contained in this section until the
-# section is changed. The :category: directive will override the :section:
-# directive.
-#
-# A :section: comment block may have one or more lines before the :section:
-# directive. These will be removed, and any identical lines at the end of
-# the block are also removed. This allows you to add visual cues to the
-# section.
-#
-# Example:
-#
-# # ----------------------------------------
-# # :section: My Section
-# # This is the section that I wrote.
-# # See it glisten in the noon-day sun.
-# # ----------------------------------------
-#
-# ##
-# # Comment for some_method
-#
-# def some_method
-# # ...
-# end
-#
-# [+:call-seq:+]
-# Lines up to the next blank line in the comment are treated as the method's
-# calling sequence, overriding the default parsing of method parameters and
-# yield arguments.
-#
-# Further directives can be found in RDoc::Parser::Ruby and RDoc::Parser::C.
-#--
-# Original Author:: Dave Thomas, dave@pragmaticprogrammer.com
-# License:: Ruby license
-
-class RDoc::Markup
-
- ##
- # An AttributeManager which handles inline markup.
-
- attr_reader :attribute_manager
-
- ##
- # Take a block of text and use various heuristics to determine its
- # structure (paragraphs, lists, and so on). Invoke an event handler as we
- # identify significant chunks.
-
- def initialize attribute_manager = nil
- @attribute_manager = attribute_manager || RDoc::Markup::AttributeManager.new
- @output = nil
- end
-
- ##
- # Add to the sequences used to add formatting to an individual word (such
- # as *bold*). Matching entries will generate attributes that the output
- # formatters can recognize by their +name+.
-
- def add_word_pair(start, stop, name)
- @attribute_manager.add_word_pair(start, stop, name)
- end
-
- ##
- # Add to the sequences recognized as general markup.
-
- def add_html(tag, name)
- @attribute_manager.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)
- @attribute_manager.add_special(pattern, name)
- end
-
- ##
- # We take +input+, parse it if necessary, then invoke the output +formatter+
- # using a Visitor to render the result.
-
- def convert input, formatter
- document = case input
- when RDoc::Markup::Document then
- input
- else
- RDoc::Markup::Parser.parse input
- end
-
- document.accept formatter
- end
-
-end
-
-require 'rdoc/markup/parser'
-require 'rdoc/markup/attribute_manager'
-require 'rdoc/markup/inline'
-
diff --git a/ruby_1_9_3/lib/rdoc/markup/attribute_manager.rb b/ruby_1_9_3/lib/rdoc/markup/attribute_manager.rb
deleted file mode 100644
index d2402f1b1d..0000000000
--- a/ruby_1_9_3/lib/rdoc/markup/attribute_manager.rb
+++ /dev/null
@@ -1,335 +0,0 @@
-##
-# Manages changes of attributes in a block of text
-
-class RDoc::Markup::AttributeManager
-
- ##
- # The NUL character
-
- 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 # :nodoc:
-
- ##
- # Special mask character to prevent inline markup handling
-
- PROTECT_ATTR = A_PROTECT.chr # :nodoc:
-
- ##
- # 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
-
- attr_reader :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
-
- attr_reader :word_pair_map
-
- ##
- # This maps HTML tags to the corresponding attribute char
-
- attr_reader :html_tags
-
- ##
- # A \ in front of a character that would normally be processed turns off
- # processing. We do this by turning \< into <#{PROTECT}
-
- attr_reader :protectable
-
- ##
- # And this maps _special_ sequences to a name. A special sequence is
- # something like a WikiWord
-
- attr_reader :special
-
- ##
- # Creates a new attribute manager that understands bold, emphasized and
- # teletype text.
-
- def initialize
- @html_tags = {}
- @matching_word_pairs = {}
- @protectable = %w[<]
- @special = {}
- @word_pair_map = {}
-
- 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
- end
-
- ##
- # Return an attribute object with the given turn_on and turn_off bits set
-
- def attribute(turn_on, turn_off)
- RDoc::Markup::AttrChanger.new turn_on, turn_off
- end
-
- ##
- # Changes the current attribute from +current+ to +new+
-
- def change_attribute current, new
- diff = current ^ new
- attribute(new & diff, current & diff)
- end
-
- ##
- # Used by the tests to change attributes by name from +current_set+ to
- # +new_set+
-
- def changed_attribute_by_name current_set, new_set
- current = new = 0
- current_set.each do |name|
- current |= RDoc::Markup::Attribute.bitmap_for(name)
- end
-
- new_set.each do |name|
- new |= RDoc::Markup::Attribute.bitmap_for(name)
- end
-
- change_attribute(current, new)
- end
-
- ##
- # Copies +start_pos+ to +end_pos+ from the current string
-
- 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}])([#:\\]?[\w.\/-]+?\S?)\2(\W|$)/
-
- 1 while str.gsub!(re) do
- 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
- end
-
- # then non-matching
- unless @word_pair_map.empty? then
- @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
-
- ##
- # Converts HTML tags to RDoc attributes
-
- def convert_html(str, attrs)
- tags = @html_tags.keys.join '|'
-
- 1 while str.gsub!(/<(#{tags})>(.*?)<\/\1>/i) {
- 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
-
- ##
- # Converts special sequences to RDoc attributes
-
- def convert_specials(str, attrs)
- unless @special.empty?
- @special.each do |regexp, attr|
- str.scan(regexp) do
- attrs.set_attrs($`.length, $&.length,
- attr | RDoc::Markup::Attribute::SPECIAL)
- end
- end
- end
- end
-
- ##
- # Escapes special sequences of text to prevent conversion to RDoc
-
- def mask_protected_sequences
- # protect __send__, __FILE__, etc.
- @str.gsub!(/__([a-z]+)__/i,
- "_#{PROTECT_ATTR}_#{PROTECT_ATTR}\\1_#{PROTECT_ATTR}_#{PROTECT_ATTR}")
- @str.gsub!(/\\([#{Regexp.escape @protectable.join('')}])/,
- "\\1#{PROTECT_ATTR}")
- end
-
- ##
- # Unescapes special sequences of text
-
- def unmask_protected_sequences
- @str.gsub!(/(.)#{PROTECT_ATTR}/, "\\1\000")
- end
-
- ##
- # Adds a markup class with +name+ for words wrapped in the +start+ and
- # +stop+ character. To make words wrapped with "*" bold:
- #
- # am.add_word_pair '*', '*', :BOLD
-
- def add_word_pair(start, stop, name)
- raise ArgumentError, "Word flags may not start with '<'" if
- start[0,1] == '<'
-
- bitmap = RDoc::Markup::Attribute.bitmap_for name
-
- if start == stop then
- @matching_word_pairs[start] = bitmap
- else
- pattern = /(#{Regexp.escape start})(\S+)(#{Regexp.escape stop})/
- @word_pair_map[pattern] = bitmap
- end
-
- @protectable << start[0,1]
- @protectable.uniq!
- end
-
- ##
- # Adds a markup class with +name+ for words surrounded by HTML tag +tag+.
- # To process emphasis tags:
- #
- # am.add_html 'em', :EM
-
- def add_html(tag, name)
- @html_tags[tag.downcase] = RDoc::Markup::Attribute.bitmap_for name
- end
-
- ##
- # Adds a special handler for +pattern+ with +name+. A simple URL handler
- # would be:
- #
- # @am.add_special(/((https?:)\S+\w)/, :HYPERLINK)
-
- def add_special(pattern, name)
- @special[pattern] = RDoc::Markup::Attribute.bitmap_for name
- end
-
- ##
- # Processes +str+ converting attributes, HTML and specials
-
- def flow(str)
- @str = str
-
- mask_protected_sequences
-
- @attrs = RDoc::Markup::AttrSpan.new @str.length
-
- convert_attrs @str, @attrs
- convert_html @str, @attrs
- convert_specials @str, @attrs
-
- unmask_protected_sequences
-
- split_into_flow
- end
-
- ##
- # Debug method that prints a string along with its attributes
-
- 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
-
- ##
- # Splits the string into chunks by attribute change
-
- def split_into_flow
- res = []
- current_attr = 0
-
- str_len = @str.length
-
- # skip leading invisible text
- i = 0
- i += 1 while i < str_len and @str[i].chr == "\0"
- 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 & RDoc::Markup::Attribute::SPECIAL) != 0 then
- i += 1 while
- i < str_len and (@attrs[i] & RDoc::Markup::Attribute::SPECIAL) != 0
-
- res << RDoc::Markup::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].chr == "\0"
- 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
-
- res
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/markup/blank_line.rb b/ruby_1_9_3/lib/rdoc/markup/blank_line.rb
deleted file mode 100644
index 5da0ac8d81..0000000000
--- a/ruby_1_9_3/lib/rdoc/markup/blank_line.rb
+++ /dev/null
@@ -1,27 +0,0 @@
-##
-# An empty line. This class is a singleton.
-
-class RDoc::Markup::BlankLine
-
- @instance = new
-
- ##
- # RDoc::Markup::BlankLine is a singleton
-
- def self.new
- @instance
- end
-
- ##
- # Calls #accept_blank_line on +visitor+
-
- def accept visitor
- visitor.accept_blank_line self
- end
-
- def pretty_print q # :nodoc:
- q.text 'blankline'
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/markup/document.rb b/ruby_1_9_3/lib/rdoc/markup/document.rb
deleted file mode 100644
index 7077f357d3..0000000000
--- a/ruby_1_9_3/lib/rdoc/markup/document.rb
+++ /dev/null
@@ -1,127 +0,0 @@
-##
-# A Document containing lists, headings, paragraphs, etc.
-
-class RDoc::Markup::Document
-
- ##
- # The file this document was created from. See also
- # RDoc::ClassModule#add_comment
-
- attr_accessor :file
-
- ##
- # The parts of the Document
-
- attr_reader :parts
-
- ##
- # Creates a new Document with +parts+
-
- def initialize *parts
- @parts = []
- @parts.push(*parts)
-
- @file = nil
- end
-
- ##
- # Appends +part+ to the document
-
- def << part
- case part
- when RDoc::Markup::Document then
- unless part.empty? then
- parts.push(*part.parts)
- parts << RDoc::Markup::BlankLine.new
- end
- when String then
- raise ArgumentError,
- "expected RDoc::Markup::Document and friends, got String" unless
- part.empty?
- else
- parts << part
- end
- end
-
- def == other # :nodoc:
- self.class == other.class and
- @file == other.file and
- @parts == other.parts
- end
-
- ##
- # Runs this document and all its #items through +visitor+
-
- def accept visitor
- visitor.start_accepting
-
- @parts.each do |item|
- case item
- when RDoc::Markup::Document then # HACK
- visitor.accept_document item
- else
- item.accept visitor
- end
- end
-
- visitor.end_accepting
- end
-
- ##
- # Does this document have no parts?
-
- def empty?
- @parts.empty? or (@parts.length == 1 and merged? and @parts.first.empty?)
- end
-
- ##
- # When this is a collection of documents (#file is not set and this document
- # contains only other documents as its direct children) #merge replaces
- # documents in this class with documents from +other+ when the file matches
- # and adds documents from +other+ when the files do not.
- #
- # The information in +other+ is preferred over the receiver
-
- def merge other
- if empty? then
- @parts = other.parts
- return self
- end
-
- other.parts.each do |other_part|
- self.parts.delete_if do |self_part|
- self_part.file and self_part.file == other_part.file
- end
-
- self.parts << other_part
- end
-
- self
- end
-
- ##
- # Does this Document contain other Documents?
-
- def merged?
- RDoc::Markup::Document === @parts.first
- end
-
- def pretty_print q # :nodoc:
- start = @file ? "[doc (#{@file}): " : '[doc: '
-
- q.group 2, start, ']' do
- q.seplist @parts do |part|
- q.pp part
- end
- end
- end
-
- ##
- # Appends +parts+ to the document
-
- def push *parts
- self.parts.push(*parts)
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/markup/formatter.rb b/ruby_1_9_3/lib/rdoc/markup/formatter.rb
deleted file mode 100644
index f42b3fc6ea..0000000000
--- a/ruby_1_9_3/lib/rdoc/markup/formatter.rb
+++ /dev/null
@@ -1,169 +0,0 @@
-require 'rdoc/markup'
-
-##
-# Base class for RDoc markup formatters
-#
-# Formatters use a visitor pattern to convert content into output.
-#
-# If you'd like to write your own Formatter use
-# RDoc::Markup::FormatterTestCase. If you're writing a text-output formatter
-# use RDoc::Markup::TextFormatterTestCase which provides extra test cases.
-
-class RDoc::Markup::Formatter
-
- ##
- # Tag for inline markup containing a +bit+ for the bitmask and the +on+ and
- # +off+ triggers.
-
- InlineTag = Struct.new(:bit, :on, :off)
-
- ##
- # Creates a new Formatter
-
- def initialize markup = nil
- @markup = markup || RDoc::Markup.new
- @am = @markup.attribute_manager
-
- @attr_tags = []
-
- @in_tt = 0
- @tt_bit = RDoc::Markup::Attribute.bitmap_for :TT
- end
-
- ##
- # Adds +document+ to the output
-
- def accept_document document
- document.parts.each do |item|
- item.accept self
- end
- end
-
- ##
- # Add a new set of tags for an attribute. We allow separate start and end
- # tags for flexibility
-
- def add_tag(name, start, stop)
- attr = RDoc::Markup::Attribute.bitmap_for name
- @attr_tags << InlineTag.new(attr, start, stop)
- end
-
- ##
- # Allows +tag+ to be decorated with additional information.
-
- def annotate(tag)
- tag
- end
-
- ##
- # Marks up +content+
-
- def convert(content)
- @markup.convert content, self
- end
-
- ##
- # Converts flow items +flow+
-
- def convert_flow(flow)
- res = []
-
- flow.each do |item|
- case item
- when String then
- res << convert_string(item)
- when RDoc::Markup::AttrChanger then
- off_tags res, item
- on_tags res, item
- when RDoc::Markup::Special then
- res << convert_special(item)
- else
- raise "Unknown flow element: #{item.inspect}"
- end
- end
-
- res.join
- end
-
- ##
- # Converts added specials. See RDoc::Markup#add_special
-
- def convert_special special
- return special.text if in_tt?
-
- handled = false
-
- RDoc::Markup::Attribute.each_name_of special.type do |name|
- method_name = "handle_special_#{name}"
-
- if respond_to? method_name then
- special.text = send method_name, special
- handled = true
- end
- end
-
- raise "Unhandled special: #{special}" unless handled
-
- special.text
- end
-
- ##
- # Converts a string to be fancier if desired
-
- def convert_string string
- string
- end
-
- ##
- # Are we currently inside tt tags?
-
- def in_tt?
- @in_tt > 0
- end
-
- ##
- # Turns on tags for +item+ on +res+
-
- 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 then
- res << annotate(tag.on)
- @in_tt += 1 if tt? tag
- end
- end
- end
-
- ##
- # Turns off tags for +item+ on +res+
-
- 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 then
- @in_tt -= 1 if tt? tag
- res << annotate(tag.off)
- end
- end
- end
-
- ##
- # Is +tag+ a tt tag?
-
- def tt? tag
- tag.bit == @tt_bit
- end
-
-end
-
-class RDoc::Markup
- autoload :ToAnsi, 'rdoc/markup/to_ansi'
- autoload :ToBs, 'rdoc/markup/to_bs'
- autoload :ToHtml, 'rdoc/markup/to_html'
- autoload :ToHtmlCrossref, 'rdoc/markup/to_html_crossref'
- autoload :ToRdoc, 'rdoc/markup/to_rdoc'
-end
diff --git a/ruby_1_9_3/lib/rdoc/markup/formatter_test_case.rb b/ruby_1_9_3/lib/rdoc/markup/formatter_test_case.rb
deleted file mode 100644
index c739f990b3..0000000000
--- a/ruby_1_9_3/lib/rdoc/markup/formatter_test_case.rb
+++ /dev/null
@@ -1,699 +0,0 @@
-require 'minitest/unit'
-require 'rdoc/markup/formatter'
-
-##
-# Test case for creating new RDoc::Markup formatters. See
-# test/test_rdoc_markup_to_*.rb for examples.
-#
-# This test case adds a variety of tests to your subclass when
-# #add_visitor_tests is called. Most tests set up a scenario then call a
-# method you will provide to perform the assertion on the output.
-#
-# Your subclass must instantiate a visitor and assign it to <tt>@to</tt>.
-#
-# For example, test_accept_blank_line sets up a RDoc::Markup::BlockLine then
-# calls accept_blank_line on your visitor. You are responsible for asserting
-# that the output is correct.
-#
-# Example:
-#
-# class TestRDocMarkupToNewFormat < RDoc::Markup::FormatterTestCase
-#
-# add_visitor_tests
-#
-# def setup
-# super
-#
-# @to = RDoc::Markup::ToNewFormat.new
-# end
-#
-# def accept_blank_line
-# assert_equal :junk, @to.res.join
-# end
-#
-# # ...
-#
-# end
-
-class RDoc::Markup::FormatterTestCase < MiniTest::Unit::TestCase
-
- ##
- # Call #setup when inheriting from this test case.
- #
- # Provides the following instance variables:
- #
- # +@m+:: RDoc::Markup.new
- # +@RM+:: RDoc::Markup # to reduce typing
- # +@bullet_list+:: @RM::List.new :BULLET, # ...
- # +@label_list+:: @RM::List.new :LABEL, # ...
- # +@lalpha_list+:: @RM::List.new :LALPHA, # ...
- # +@note_list+:: @RM::List.new :NOTE, # ...
- # +@number_list+:: @RM::List.new :NUMBER, # ...
- # +@ualpha_list+:: @RM::List.new :UALPHA, # ...
-
- def setup
- super
-
- @m = RDoc::Markup.new
- @RM = RDoc::Markup
-
- @bullet_list = @RM::List.new(:BULLET,
- @RM::ListItem.new(nil, @RM::Paragraph.new('l1')),
- @RM::ListItem.new(nil, @RM::Paragraph.new('l2')))
-
- @label_list = @RM::List.new(:LABEL,
- @RM::ListItem.new('cat', @RM::Paragraph.new('cats are cool')),
- @RM::ListItem.new('dog', @RM::Paragraph.new('dogs are cool too')))
-
- @lalpha_list = @RM::List.new(:LALPHA,
- @RM::ListItem.new(nil, @RM::Paragraph.new('l1')),
- @RM::ListItem.new(nil, @RM::Paragraph.new('l2')))
-
- @note_list = @RM::List.new(:NOTE,
- @RM::ListItem.new('cat', @RM::Paragraph.new('cats are cool')),
- @RM::ListItem.new('dog', @RM::Paragraph.new('dogs are cool too')))
-
- @number_list = @RM::List.new(:NUMBER,
- @RM::ListItem.new(nil, @RM::Paragraph.new('l1')),
- @RM::ListItem.new(nil, @RM::Paragraph.new('l2')))
-
- @ualpha_list = @RM::List.new(:UALPHA,
- @RM::ListItem.new(nil, @RM::Paragraph.new('l1')),
- @RM::ListItem.new(nil, @RM::Paragraph.new('l2')))
- end
-
- ##
- # Call to add the visitor tests to your test case
-
- def self.add_visitor_tests
- self.class_eval do
-
- ##
- # Calls start_accepting which needs to verify startup state
-
- def test_start_accepting
- @to.start_accepting
-
- start_accepting
- end
-
- ##
- # Calls end_accepting on your test case which needs to call
- # <tt>@to.end_accepting</tt> and verify document generation
-
- def test_end_accepting
- @to.start_accepting
- @to.res << 'hi'
-
- end_accepting
- end
-
- ##
- # Calls accept_blank_line
-
- def test_accept_blank_line
- @to.start_accepting
-
- @to.accept_blank_line @RM::BlankLine.new
-
- accept_blank_line
- end
-
- ##
- # Test case that calls <tt>@to.accept_document</tt>
-
- def test_accept_document
- @to.start_accepting
- @to.accept_document @RM::Document.new @RM::Paragraph.new 'hello'
-
- accept_document
- end
-
- ##
- # Calls accept_heading with a level 5 RDoc::Markup::Heading
-
- def test_accept_heading
- @to.start_accepting
-
- @to.accept_heading @RM::Heading.new(5, 'Hello')
-
- accept_heading
- end
-
- ##
- # Calls accept_heading_1 with a level 1 RDoc::Markup::Heading
-
- def test_accept_heading_1
- @to.start_accepting
-
- @to.accept_heading @RM::Heading.new(1, 'Hello')
-
- accept_heading_1
- end
-
- ##
- # Calls accept_heading_2 with a level 2 RDoc::Markup::Heading
-
- def test_accept_heading_2
- @to.start_accepting
-
- @to.accept_heading @RM::Heading.new(2, 'Hello')
-
- accept_heading_2
- end
-
- ##
- # Calls accept_heading_3 with a level 3 RDoc::Markup::Heading
-
- def test_accept_heading_3
- # HACK this doesn't belong here
- skip "No String#chars, upgrade your ruby" unless ''.respond_to? :chars
-
- @to.start_accepting
-
- @to.accept_heading @RM::Heading.new(3, 'Hello')
-
- accept_heading_3
- end
-
- ##
- # Calls accept_heading_4 with a level 4 RDoc::Markup::Heading
-
- def test_accept_heading_4
- @to.start_accepting
-
- @to.accept_heading @RM::Heading.new(4, 'Hello')
-
- accept_heading_4
- end
-
- ##
- # Calls accept_heading_b with a bold level 1 RDoc::Markup::Heading
-
- def test_accept_heading_b
- @to.start_accepting
-
- @to.accept_heading @RM::Heading.new(1, '*Hello*')
-
- accept_heading_b
- end
-
- ##
- # Calls accept_heading_suppressed_crossref with a level 1
- # RDoc::Markup::Heading containing a suppressed crossref
-
- def test_accept_heading_suppressed_crossref # HACK to_html_crossref test
- @to.start_accepting
-
- @to.accept_heading @RM::Heading.new(1, '\\Hello')
-
- accept_heading_suppressed_crossref
- end
-
- ##
- # Calls accept_paragraph
-
- def test_accept_paragraph
- @to.start_accepting
-
- @to.accept_paragraph @RM::Paragraph.new('hi')
-
- accept_paragraph
- end
-
- ##
- # Calls accept_paragraph_b with a RDoc::Markup::Paragraph containing
- # bold words
-
- def test_accept_paragraph_b
- @to.start_accepting
-
- @to.accept_paragraph @RM::Paragraph.new('reg <b>bold words</b> reg')
-
- accept_paragraph_b
- end
-
- ##
- # Calls accept_paragraph_i with a RDoc::Markup::Paragraph containing
- # emphasized words
-
- def test_accept_paragraph_i
- @to.start_accepting
-
- @to.accept_paragraph @RM::Paragraph.new('reg <em>italic words</em> reg')
-
- accept_paragraph_i
- end
-
- ##
- # Calls accept_paragraph_plus with a RDoc::Markup::Paragraph containing
- # teletype words
-
- def test_accept_paragraph_plus
- @to.start_accepting
-
- @to.accept_paragraph @RM::Paragraph.new('reg +teletype+ reg')
-
- accept_paragraph_plus
- end
-
- ##
- # Calls accept_paragraph_star with a RDoc::Markup::Paragraph containing
- # bold words
-
- def test_accept_paragraph_star
- @to.start_accepting
-
- @to.accept_paragraph @RM::Paragraph.new('reg *bold* reg')
-
- accept_paragraph_star
- end
-
- ##
- # Calls accept_paragraph_underscore with a RDoc::Markup::Paragraph
- # containing emphasized words
-
- def test_accept_paragraph_underscore
- @to.start_accepting
-
- @to.accept_paragraph @RM::Paragraph.new('reg _italic_ reg')
-
- accept_paragraph_underscore
- end
-
- ##
- # Calls accept_verbatim with a RDoc::Markup::Verbatim
-
- def test_accept_verbatim
- @to.start_accepting
-
- @to.accept_verbatim @RM::Verbatim.new("hi\n", " world\n")
-
- accept_verbatim
- end
-
- ##
- # Calls accept_raw with a RDoc::Markup::Raw
-
- def test_accept_raw
- @to.start_accepting
-
- @to.accept_raw @RM::Raw.new("<table>",
- "<tr><th>Name<th>Count",
- "<tr><td>a<td>1",
- "<tr><td>b<td>2",
- "</table>")
-
- accept_raw
- end
-
- ##
- # Calls accept_rule with a RDoc::Markup::Rule
-
- def test_accept_rule
- @to.start_accepting
-
- @to.accept_rule @RM::Rule.new(4)
-
- accept_rule
- end
-
- ##
- # Calls accept_list_item_start_bullet
-
- def test_accept_list_item_start_bullet
- @to.start_accepting
-
- @to.accept_list_start @bullet_list
-
- @to.accept_list_item_start @bullet_list.items.first
-
- accept_list_item_start_bullet
- end
-
- ##
- # Calls accept_list_item_start_label
-
- def test_accept_list_item_start_label
- @to.start_accepting
-
- @to.accept_list_start @label_list
-
- @to.accept_list_item_start @label_list.items.first
-
- accept_list_item_start_label
- end
-
- ##
- # Calls accept_list_item_start_lalpha
-
- def test_accept_list_item_start_lalpha
- @to.start_accepting
-
- @to.accept_list_start @lalpha_list
-
- @to.accept_list_item_start @lalpha_list.items.first
-
- accept_list_item_start_lalpha
- end
-
- ##
- # Calls accept_list_item_start_note
-
- def test_accept_list_item_start_note
- @to.start_accepting
-
- @to.accept_list_start @note_list
-
- @to.accept_list_item_start @note_list.items.first
-
- accept_list_item_start_note
- end
-
- ##
- # Calls accept_list_item_start_note_2
-
- def test_accept_list_item_start_note_2
- list = @RM::List.new(:NOTE,
- @RM::ListItem.new('<tt>teletype</tt>',
- @RM::Paragraph.new('teletype description')))
-
- @to.start_accepting
-
- list.accept @to
-
- @to.end_accepting
-
- accept_list_item_start_note_2
- end
-
- ##
- # Calls accept_list_item_start_number
-
- def test_accept_list_item_start_number
- @to.start_accepting
-
- @to.accept_list_start @number_list
-
- @to.accept_list_item_start @number_list.items.first
-
- accept_list_item_start_number
- end
-
- ##
- # Calls accept_list_item_start_ualpha
-
- def test_accept_list_item_start_ualpha
- @to.start_accepting
-
- @to.accept_list_start @ualpha_list
-
- @to.accept_list_item_start @ualpha_list.items.first
-
- accept_list_item_start_ualpha
- end
-
- ##
- # Calls accept_list_item_end_bullet
-
- def test_accept_list_item_end_bullet
- @to.start_accepting
-
- @to.accept_list_start @bullet_list
-
- @to.accept_list_item_start @bullet_list.items.first
-
- @to.accept_list_item_end @bullet_list.items.first
-
- accept_list_item_end_bullet
- end
-
- ##
- # Calls accept_list_item_end_label
-
- def test_accept_list_item_end_label
- @to.start_accepting
-
- @to.accept_list_start @label_list
-
- @to.accept_list_item_start @label_list.items.first
-
- @to.accept_list_item_end @label_list.items.first
-
- accept_list_item_end_label
- end
-
- ##
- # Calls accept_list_item_end_lalpha
-
- def test_accept_list_item_end_lalpha
- @to.start_accepting
-
- @to.accept_list_start @lalpha_list
-
- @to.accept_list_item_start @lalpha_list.items.first
-
- @to.accept_list_item_end @lalpha_list.items.first
-
- accept_list_item_end_lalpha
- end
-
- ##
- # Calls accept_list_item_end_note
-
- def test_accept_list_item_end_note
- @to.start_accepting
-
- @to.accept_list_start @note_list
-
- @to.accept_list_item_start @note_list.items.first
-
- @to.accept_list_item_end @note_list.items.first
-
- accept_list_item_end_note
- end
-
- ##
- # Calls accept_list_item_end_number
-
- def test_accept_list_item_end_number
- @to.start_accepting
-
- @to.accept_list_start @number_list
-
- @to.accept_list_item_start @number_list.items.first
-
- @to.accept_list_item_end @number_list.items.first
-
- accept_list_item_end_number
- end
-
- ##
- # Calls accept_list_item_end_ualpha
-
- def test_accept_list_item_end_ualpha
- @to.start_accepting
-
- @to.accept_list_start @ualpha_list
-
- @to.accept_list_item_start @ualpha_list.items.first
-
- @to.accept_list_item_end @ualpha_list.items.first
-
- accept_list_item_end_ualpha
- end
-
- ##
- # Calls accept_list_start_bullet
-
- def test_accept_list_start_bullet
- @to.start_accepting
-
- @to.accept_list_start @bullet_list
-
- accept_list_start_bullet
- end
-
- ##
- # Calls accept_list_start_label
-
- def test_accept_list_start_label
- @to.start_accepting
-
- @to.accept_list_start @label_list
-
- accept_list_start_label
- end
-
- ##
- # Calls accept_list_start_lalpha
-
- def test_accept_list_start_lalpha
- @to.start_accepting
-
- @to.accept_list_start @lalpha_list
-
- accept_list_start_lalpha
- end
-
- ##
- # Calls accept_list_start_note
-
- def test_accept_list_start_note
- @to.start_accepting
-
- @to.accept_list_start @note_list
-
- accept_list_start_note
- end
-
- ##
- # Calls accept_list_start_number
-
- def test_accept_list_start_number
- @to.start_accepting
-
- @to.accept_list_start @number_list
-
- accept_list_start_number
- end
-
- ##
- # Calls accept_list_start_ualpha
-
- def test_accept_list_start_ualpha
- @to.start_accepting
-
- @to.accept_list_start @ualpha_list
-
- accept_list_start_ualpha
- end
-
- ##
- # Calls accept_list_end_bullet
-
- def test_accept_list_end_bullet
- @to.start_accepting
-
- @to.accept_list_start @bullet_list
-
- @to.accept_list_end @bullet_list
-
- accept_list_end_bullet
- end
-
- ##
- # Calls accept_list_end_label
-
- def test_accept_list_end_label
- @to.start_accepting
-
- @to.accept_list_start @label_list
-
- @to.accept_list_end @label_list
-
- accept_list_end_label
- end
-
- ##
- # Calls accept_list_end_lalpha
-
- def test_accept_list_end_lalpha
- @to.start_accepting
-
- @to.accept_list_start @lalpha_list
-
- @to.accept_list_end @lalpha_list
-
- accept_list_end_lalpha
- end
-
- ##
- # Calls accept_list_end_number
-
- def test_accept_list_end_number
- @to.start_accepting
-
- @to.accept_list_start @number_list
-
- @to.accept_list_end @number_list
-
- accept_list_end_number
- end
-
- ##
- # Calls accept_list_end_note
-
- def test_accept_list_end_note
- @to.start_accepting
-
- @to.accept_list_start @note_list
-
- @to.accept_list_end @note_list
-
- accept_list_end_note
- end
-
- ##
- # Calls accept_list_end_ulpha
-
- def test_accept_list_end_ualpha
- @to.start_accepting
-
- @to.accept_list_start @ualpha_list
-
- @to.accept_list_end @ualpha_list
-
- accept_list_end_ualpha
- end
-
- ##
- # Calls list_nested with a two-level list
-
- def test_list_nested
- doc = @RM::Document.new(
- @RM::List.new(:BULLET,
- @RM::ListItem.new(nil,
- @RM::Paragraph.new('l1'),
- @RM::List.new(:BULLET,
- @RM::ListItem.new(nil,
- @RM::Paragraph.new('l1.1')))),
- @RM::ListItem.new(nil,
- @RM::Paragraph.new('l2'))))
-
- doc.accept @to
-
- list_nested
- end
-
- ##
- # Calls list_verbatim with a list containing a verbatim block
-
- def test_list_verbatim # HACK overblown
- doc = @RM::Document.new(
- @RM::List.new(:BULLET,
- @RM::ListItem.new(nil,
- @RM::Paragraph.new('list', 'stuff'),
- @RM::BlankLine.new,
- @RM::Verbatim.new("* list\n",
- " with\n",
- "\n",
- " second\n",
- "\n",
- " 1. indented\n",
- " 2. numbered\n",
- "\n",
- " third\n",
- "\n",
- "* second\n"))))
-
- doc.accept @to
-
- list_verbatim
- end
-
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/markup/heading.rb b/ruby_1_9_3/lib/rdoc/markup/heading.rb
deleted file mode 100644
index 3bda77a1e1..0000000000
--- a/ruby_1_9_3/lib/rdoc/markup/heading.rb
+++ /dev/null
@@ -1,20 +0,0 @@
-##
-# A heading with a level (1-6) and text
-
-class RDoc::Markup::Heading < Struct.new :level, :text
-
- ##
- # Calls #accept_heading on +visitor+
-
- def accept visitor
- visitor.accept_heading self
- end
-
- def pretty_print q # :nodoc:
- q.group 2, "[head: #{level} ", ']' do
- q.pp text
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/markup/indented_paragraph.rb b/ruby_1_9_3/lib/rdoc/markup/indented_paragraph.rb
deleted file mode 100644
index d995c7d8ed..0000000000
--- a/ruby_1_9_3/lib/rdoc/markup/indented_paragraph.rb
+++ /dev/null
@@ -1,33 +0,0 @@
-##
-# An Indented Paragraph of text
-
-class RDoc::Markup::IndentedParagraph < RDoc::Markup::Raw
-
- ##
- # The indent in number of spaces
-
- attr_reader :indent
-
- ##
- # Creates a new IndentedParagraph containing +parts+ indented with +indent+
- # spaces
-
- def initialize indent, *parts
- @indent = indent
-
- super(*parts)
- end
-
- def == other # :nodoc:
- super and indent == other.indent
- end
-
- ##
- # Calls #accept_indented_paragraph on +visitor+
-
- def accept visitor
- visitor.accept_indented_paragraph self
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/markup/inline.rb b/ruby_1_9_3/lib/rdoc/markup/inline.rb
deleted file mode 100644
index cf598d1583..0000000000
--- a/ruby_1_9_3/lib/rdoc/markup/inline.rb
+++ /dev/null
@@ -1,144 +0,0 @@
-require 'rdoc'
-class RDoc::Markup
-
- ##
- # We manage a set of attributes. Each attribute has a symbol name and a bit
- # value.
-
- class Attribute
-
- ##
- # Special attribute type. See RDoc::Markup#add_special
-
- SPECIAL = 1
-
- @@name_to_bitmap = { :_SPECIAL_ => SPECIAL }
- @@next_bitmap = 2
-
- ##
- # Returns a unique bit for +name+
-
- def self.bitmap_for(name)
- bitmap = @@name_to_bitmap[name]
- unless bitmap then
- bitmap = @@next_bitmap
- @@next_bitmap <<= 1
- @@name_to_bitmap[name] = bitmap
- end
- bitmap
- end
-
- ##
- # Returns a string representation of +bitmap+
-
- def self.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
-
- ##
- # yields each attribute name in +bitmap+
-
- def self.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
-
- AttrChanger = Struct.new :turn_on, :turn_off # :nodoc:
-
- ##
- # 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.
-
- class AttrChanger
- def to_s # :nodoc:
- "Attr: +#{Attribute.as_string turn_on}/-#{Attribute.as_string turn_off}"
- end
-
- def inspect # :nodoc:
- "+%s/-%s" % [
- Attribute.as_string(turn_on),
- Attribute.as_string(turn_off),
- ]
- end
- end
-
- ##
- # An array of attributes which parallels the characters in a string.
-
- class AttrSpan
-
- ##
- # Creates a new AttrSpan for +length+ characters
-
- def initialize(length)
- @attrs = Array.new(length, 0)
- end
-
- ##
- # Toggles +bits+ from +start+ to +length+
- def set_attrs(start, length, bits)
- for i in start ... (start+length)
- @attrs[i] |= bits
- end
- end
-
- ##
- # Accesses flags for character +n+
-
- def [](n)
- @attrs[n]
- end
-
- end
-
- ##
- # Hold details of a special sequence
-
- class Special
-
- ##
- # Special type
-
- attr_reader :type
-
- ##
- # Special text
-
- attr_accessor :text
-
- ##
- # Creates a new special sequence of +type+ with +text+
-
- def initialize(type, text)
- @type, @text = type, text
- end
-
- ##
- # Specials are equal when the have the same text and type
-
- def ==(o)
- self.text == o.text && self.type == o.type
- end
-
- def inspect # :nodoc:
- "#<RDoc::Markup::Special:0x%x @type=%p, name=%p @text=%p>" % [
- object_id, @type, RDoc::Markup::Attribute.as_string(type), text.dump]
- end
-
- def to_s # :nodoc:
- "Special: type=#{type}, name=#{RDoc::Markup::Attribute.as_string type}, text=#{text.dump}"
- end
-
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/markup/list.rb b/ruby_1_9_3/lib/rdoc/markup/list.rb
deleted file mode 100644
index 820b4c9645..0000000000
--- a/ruby_1_9_3/lib/rdoc/markup/list.rb
+++ /dev/null
@@ -1,81 +0,0 @@
-##
-# A List of ListItems
-
-class RDoc::Markup::List
-
- ##
- # The list's type
-
- attr_accessor :type
-
- ##
- # Items in the list
-
- attr_reader :items
-
- ##
- # Creates a new list of +type+ with +items+
-
- def initialize type = nil, *items
- @type = type
- @items = []
- @items.push(*items)
- end
-
- ##
- # Appends +item+ to the list
-
- def << item
- @items << item
- end
-
- def == other # :nodoc:
- self.class == other.class and
- @type == other.type and
- @items == other.items
- end
-
- ##
- # Runs this list and all its #items through +visitor+
-
- def accept visitor
- visitor.accept_list_start self
-
- @items.each do |item|
- item.accept visitor
- end
-
- visitor.accept_list_end self
- end
-
- ##
- # Is the list empty?
-
- def empty?
- @items.empty?
- end
-
- ##
- # Returns the last item in the list
-
- def last
- @items.last
- end
-
- def pretty_print q # :nodoc:
- q.group 2, "[list: #{@type} ", ']' do
- q.seplist @items do |item|
- q.pp item
- end
- end
- end
-
- ##
- # Appends +items+ to the list
-
- def push *items
- @items.push(*items)
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/markup/list_item.rb b/ruby_1_9_3/lib/rdoc/markup/list_item.rb
deleted file mode 100644
index d719c352ec..0000000000
--- a/ruby_1_9_3/lib/rdoc/markup/list_item.rb
+++ /dev/null
@@ -1,86 +0,0 @@
-##
-# An item within a List that contains paragraphs, headings, etc.
-
-class RDoc::Markup::ListItem
-
- ##
- # The label for the ListItem
-
- attr_accessor :label
-
- ##
- # Parts of the ListItem
-
- attr_reader :parts
-
- ##
- # Creates a new ListItem with an optional +label+ containing +parts+
-
- def initialize label = nil, *parts
- @label = label
- @parts = []
- @parts.push(*parts)
- end
-
- ##
- # Appends +part+ to the ListItem
-
- def << part
- @parts << part
- end
-
- def == other # :nodoc:
- self.class == other.class and
- @label == other.label and
- @parts == other.parts
- end
-
- ##
- # Runs this list item and all its #parts through +visitor+
-
- def accept visitor
- visitor.accept_list_item_start self
-
- @parts.each do |part|
- part.accept visitor
- end
-
- visitor.accept_list_item_end self
- end
-
- ##
- # Is the ListItem empty?
-
- def empty?
- @parts.empty?
- end
-
- ##
- # Length of parts in the ListItem
-
- def length
- @parts.length
- end
-
- def pretty_print q # :nodoc:
- q.group 2, '[item: ', ']' do
- if @label then
- q.text @label
- q.breakable
- end
-
- q.seplist @parts do |part|
- q.pp part
- end
- end
- end
-
- ##
- # Adds +parts+ to the ListItem
-
- def push *parts
- @parts.push(*parts)
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/markup/paragraph.rb b/ruby_1_9_3/lib/rdoc/markup/paragraph.rb
deleted file mode 100644
index 808430d576..0000000000
--- a/ruby_1_9_3/lib/rdoc/markup/paragraph.rb
+++ /dev/null
@@ -1,14 +0,0 @@
-##
-# A Paragraph of text
-
-class RDoc::Markup::Paragraph < RDoc::Markup::Raw
-
- ##
- # Calls #accept_paragraph on +visitor+
-
- def accept visitor
- visitor.accept_paragraph self
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/markup/parser.rb b/ruby_1_9_3/lib/rdoc/markup/parser.rb
deleted file mode 100644
index c18ce821fb..0000000000
--- a/ruby_1_9_3/lib/rdoc/markup/parser.rb
+++ /dev/null
@@ -1,497 +0,0 @@
-require 'strscan'
-require 'rdoc/text'
-
-##
-# A recursive-descent parser for RDoc markup.
-#
-# The parser tokenizes an input string then parses the tokens into a Document.
-# Documents can be converted into output formats by writing a visitor like
-# RDoc::Markup::ToHTML.
-#
-# The parser only handles the block-level constructs Paragraph, List,
-# ListItem, Heading, Verbatim, BlankLine and Rule. Inline markup such as
-# <tt>\+blah\+</tt> is handled separately by RDoc::Markup::AttributeManager.
-#
-# To see what markup the Parser implements read RDoc. To see how to use
-# RDoc markup to format text in your program read RDoc::Markup.
-
-class RDoc::Markup::Parser
-
- include RDoc::Text
-
- ##
- # List token types
-
- LIST_TOKENS = [
- :BULLET,
- :LABEL,
- :LALPHA,
- :NOTE,
- :NUMBER,
- :UALPHA,
- ]
-
- ##
- # Parser error subclass
-
- class Error < RuntimeError; end
-
- ##
- # Raised when the parser is unable to handle the given markup
-
- class ParseError < Error; end
-
- ##
- # Enables display of debugging information
-
- attr_accessor :debug
-
- ##
- # Token accessor
-
- attr_reader :tokens
-
- ##
- # Parses +str+ into a Document
-
- def self.parse str
- parser = new
- parser.tokenize str
- doc = RDoc::Markup::Document.new
- parser.parse doc
- end
-
- ##
- # Returns a token stream for +str+, for testing
-
- def self.tokenize str
- parser = new
- parser.tokenize str
- parser.tokens
- end
-
- ##
- # Creates a new Parser. See also ::parse
-
- def initialize
- @tokens = []
- @current_token = nil
- @debug = false
-
- @line = 0
- @line_pos = 0
- end
-
- ##
- # Builds a Heading of +level+
-
- def build_heading level
- type, text, = get
-
- text = case type
- when :TEXT then
- skip :NEWLINE
- text
- else
- unget
- ''
- end
-
- RDoc::Markup::Heading.new level, text
- end
-
- ##
- # Builds a List flush to +margin+
-
- def build_list margin
- p :list_start => margin if @debug
-
- list = RDoc::Markup::List.new
-
- until @tokens.empty? do
- type, data, column, = get
-
- case type
- when :BULLET, :LABEL, :LALPHA, :NOTE, :NUMBER, :UALPHA then
-
- if column < margin || (list.type && list.type != type) then
- unget
- break
- end
-
- list.type = type
- peek_type, _, column, = peek_token
-
- case type
- when :NOTE, :LABEL then
- if peek_type == :NEWLINE then
- # description not on the same line as LABEL/NOTE
- # skip the trailing newline & any blank lines below
- while peek_type == :NEWLINE
- get
- peek_type, _, column, = peek_token
- end
-
- # we may be:
- # - at end of stream
- # - at a column < margin:
- # [text]
- # blah blah blah
- # - at the same column, but with a different type of list item
- # [text]
- # * blah blah
- # - at the same column, with the same type of list item
- # [one]
- # [two]
- # In all cases, we have an empty description.
- # In the last case only, we continue.
- if peek_type.nil? || column < margin then
- empty = 1
- elsif column == margin then
- case peek_type
- when type
- empty = 2 # continue
- when *LIST_TOKENS
- empty = 1
- else
- empty = 0
- end
- else
- empty = 0
- end
-
- if empty > 0 then
- item = RDoc::Markup::ListItem.new(data)
- item << RDoc::Markup::BlankLine.new
- list << item
- break if empty == 1
- next
- end
- end
- else
- data = nil
- end
-
- list_item = RDoc::Markup::ListItem.new data
- parse list_item, column
- list << list_item
-
- else
- unget
- break
- end
- end
-
- p :list_end => margin if @debug
-
- return nil if list.empty?
-
- list
- end
-
- ##
- # Builds a Paragraph that is flush to +margin+
-
- def build_paragraph margin
- p :paragraph_start => margin if @debug
-
- paragraph = RDoc::Markup::Paragraph.new
-
- until @tokens.empty? do
- type, data, column, = get
-
- if type == :TEXT && column == margin then
- paragraph << data
- skip :NEWLINE
- else
- unget
- break
- end
- end
-
- p :paragraph_end => margin if @debug
-
- paragraph
- end
-
- ##
- # Builds a Verbatim that is indented from +margin+.
- #
- # The verbatim block is shifted left (the least indented lines start in
- # column 0). Each part of the verbatim is one line of text, always
- # terminated by a newline. Blank lines always consist of a single newline
- # character, and there is never a single newline at the end of the verbatim.
-
- def build_verbatim margin
- p :verbatim_begin => margin if @debug
- verbatim = RDoc::Markup::Verbatim.new
-
- min_indent = nil
- generate_leading_spaces = true
- line = ''
-
- until @tokens.empty? do
- type, data, column, = get
-
- if type == :NEWLINE then
- line << data
- verbatim << line
- line = ''
- generate_leading_spaces = true
- next
- end
-
- if column <= margin
- unget
- break
- end
-
- if generate_leading_spaces then
- indent = column - margin
- line << ' ' * indent
- min_indent = indent if min_indent.nil? || indent < min_indent
- generate_leading_spaces = false
- end
-
- case type
- when :HEADER then
- line << '=' * data
- _, _, peek_column, = peek_token
- peek_column ||= column + data
- indent = peek_column - column - data
- line << ' ' * indent
- when :RULE then
- width = 2 + data
- line << '-' * width
- _, _, peek_column, = peek_token
- peek_column ||= column + width
- indent = peek_column - column - width
- line << ' ' * indent
- when :TEXT then
- line << data
- else # *LIST_TOKENS
- list_marker = case type
- when :BULLET then data
- when :LABEL then "[#{data}]"
- when :NOTE then "#{data}::"
- else # :LALPHA, :NUMBER, :UALPHA
- "#{data}."
- end
- line << list_marker
- peek_type, _, peek_column = peek_token
- unless peek_type == :NEWLINE then
- peek_column ||= column + list_marker.length
- indent = peek_column - column - list_marker.length
- line << ' ' * indent
- end
- end
-
- end
-
- verbatim << line << "\n" unless line.empty?
- verbatim.parts.each { |p| p.slice!(0, min_indent) unless p == "\n" } if min_indent > 0
- verbatim.normalize
-
- p :verbatim_end => margin if @debug
-
- verbatim
- end
-
- ##
- # Pulls the next token from the stream.
-
- def get
- @current_token = @tokens.shift
- p :get => @current_token if @debug
- @current_token
- end
-
- ##
- # Parses the tokens into an array of RDoc::Markup::XXX objects,
- # and appends them to the passed +parent+ RDoc::Markup::YYY object.
- #
- # Exits at the end of the token stream, or when it encounters a token
- # in a column less than +indent+ (unless it is a NEWLINE).
- #
- # Returns +parent+.
-
- def parse parent, indent = 0
- p :parse_start => indent if @debug
-
- until @tokens.empty? do
- type, data, column, = get
-
- if type == :NEWLINE then
- # trailing newlines are skipped below, so this is a blank line
- parent << RDoc::Markup::BlankLine.new
- skip :NEWLINE, false
- next
- end
-
- # indentation change: break or verbatim
- if column < indent then
- unget
- break
- elsif column > indent then
- unget
- parent << build_verbatim(indent)
- next
- end
-
- # indentation is the same
- case type
- when :HEADER then
- parent << build_heading(data)
- when :RULE then
- parent << RDoc::Markup::Rule.new(data)
- skip :NEWLINE
- when :TEXT then
- unget
- parent << build_paragraph(indent)
- when *LIST_TOKENS then
- unget
- parent << build_list(indent)
- else
- type, data, column, line = @current_token
- raise ParseError, "Unhandled token #{type} (#{data.inspect}) at #{line}:#{column}"
- end
- end
-
- p :parse_end => indent if @debug
-
- parent
-
- end
-
- ##
- # Returns the next token on the stream without modifying the stream
-
- def peek_token
- token = @tokens.first || []
- p :peek => token if @debug
- token
- end
-
- ##
- # Skips the next token if its type is +token_type+.
- #
- # Optionally raises an error if the next token is not of the expected type.
-
- def skip token_type, error = true
- type, = get
- return unless type # end of stream
- return @current_token if token_type == type
- unget
- raise ParseError, "expected #{token_type} got #{@current_token.inspect}" if error
- end
-
- ##
- # Turns text +input+ into a stream of tokens
-
- def tokenize input
- s = StringScanner.new input
-
- @line = 0
- @line_pos = 0
-
- until s.eos? do
- pos = s.pos
-
- # leading spaces will be reflected by the column of the next token
- # the only thing we loose are trailing spaces at the end of the file
- next if s.scan(/ +/)
-
- # note: after BULLET, LABEL, etc.,
- # indent will be the column of the next non-newline token
-
- @tokens << case
- # [CR]LF => :NEWLINE
- when s.scan(/\r?\n/) then
- token = [:NEWLINE, s.matched, *token_pos(pos)]
- @line_pos = s.pos
- @line += 1
- token
- # === text => :HEADER then :TEXT
- when s.scan(/(=+)(\s*)/) then
- level = s[1].length
- header = [:HEADER, level, *token_pos(pos)]
-
- if s[2] =~ /^\r?\n/ then
- s.pos -= s[2].length
- header
- else
- pos = s.pos
- s.scan(/.*/)
- @tokens << header
- [:TEXT, s.matched.sub(/\r$/, ''), *token_pos(pos)]
- end
- # --- (at least 3) and nothing else on the line => :RULE
- when s.scan(/(-{3,}) *$/) then
- [:RULE, s[1].length - 2, *token_pos(pos)]
- # * or - followed by white space and text => :BULLET
- when s.scan(/([*-]) +(\S)/) then
- s.pos -= s[2].bytesize # unget \S
- [:BULLET, s[1], *token_pos(pos)]
- # A. text, a. text, 12. text => :UALPHA, :LALPHA, :NUMBER
- when s.scan(/([a-z]|\d+)\. +(\S)/i) then
- # FIXME if tab(s), the column will be wrong
- # either support tabs everywhere by first expanding them to
- # spaces, or assume that they will have been replaced
- # before (and provide a check for that at least in debug
- # mode)
- list_label = s[1]
- s.pos -= s[2].bytesize # unget \S
- list_type =
- case list_label
- when /[a-z]/ then :LALPHA
- when /[A-Z]/ then :UALPHA
- when /\d/ then :NUMBER
- else
- raise ParseError, "BUG token #{list_label}"
- end
- [list_type, list_label, *token_pos(pos)]
- # [text] followed by spaces or end of line => :LABEL
- when s.scan(/\[(.*?)\]( +|$)/) then
- [:LABEL, s[1], *token_pos(pos)]
- # text:: followed by spaces or end of line => :NOTE
- when s.scan(/(.*?)::( +|$)/) then
- [:NOTE, s[1], *token_pos(pos)]
- # anything else: :TEXT
- else s.scan(/.*/)
- [:TEXT, s.matched.sub(/\r$/, ''), *token_pos(pos)]
- end
- end
-
- self
- end
-
- ##
- # Calculates the column and line of the current token based on +offset+.
-
- def token_pos offset
- [offset - @line_pos, @line]
- end
-
- ##
- # Returns the current token to the token stream
-
- def unget
- token = @current_token
- p :unget => token if @debug
- raise Error, 'too many #ungets' if token == @tokens.first
- @tokens.unshift token if token
- end
-
-end
-
-require 'rdoc/markup/blank_line'
-require 'rdoc/markup/document'
-require 'rdoc/markup/heading'
-require 'rdoc/markup/list'
-require 'rdoc/markup/list_item'
-require 'rdoc/markup/raw'
-require 'rdoc/markup/paragraph'
-require 'rdoc/markup/indented_paragraph'
-require 'rdoc/markup/rule'
-require 'rdoc/markup/verbatim'
-
diff --git a/ruby_1_9_3/lib/rdoc/markup/pre_process.rb b/ruby_1_9_3/lib/rdoc/markup/pre_process.rb
deleted file mode 100644
index 53e8e38ec1..0000000000
--- a/ruby_1_9_3/lib/rdoc/markup/pre_process.rb
+++ /dev/null
@@ -1,227 +0,0 @@
-require 'rdoc/markup'
-require 'rdoc/encoding'
-
-##
-# Handle common directives that can occur in a block of text:
-#
-# \:include: filename
-#
-# Directives can be escaped by preceding them with a backslash.
-#
-# RDoc plugin authors can register additional directives to be handled by
-# using RDoc::Markup::PreProcess::register
-
-class RDoc::Markup::PreProcess
-
- attr_accessor :options
-
- @registered = {}
-
- ##
- # Registers +directive+ as one handled by RDoc. If a block is given the
- # directive will be replaced by the result of the block, otherwise the
- # directive will be removed from the processed text.
-
- def self.register directive, &block
- @registered[directive] = block
- end
-
- ##
- # Registered directives
-
- def self.registered
- @registered
- end
-
- ##
- # Creates a new pre-processor for +input_file_name+ that will look for
- # included files in +include_path+
-
- def initialize(input_file_name, include_path)
- @input_file_name = input_file_name
- @include_path = include_path
- @options = nil
- end
-
- ##
- # Look for directives in a chunk of +text+.
- #
- # Options that we don't handle are yielded. If the block returns false the
- # directive is restored to the text. If the block returns nil or no block
- # was given the directive is handled according to the registered directives.
- # If a String was returned the directive is replaced with the string.
- #
- # If no matching directive was registered the directive is restored to the
- # text.
- #
- # If +code_object+ is given and the param is set as metadata on the
- # +code_object+. See RDoc::CodeObject#metadata
-
- def handle text, code_object = nil, &block
- encoding = if defined?(Encoding) then text.encoding else nil end
- # regexp helper (square brackets for optional)
- # $1 $2 $3 $4 $5
- # [prefix][\]:directive:[spaces][param]newline
- text.gsub!(/^([ \t]*(?:#|\/?\*)?[ \t]*)(\\?):(\w+):([ \t]*)(.+)?\n/) do
- # skip something like ':toto::'
- next $& if $4.empty? and $5 and $5[0, 1] == ':'
-
- # skip if escaped
- next "#$1:#$3:#$4#$5\n" unless $2.empty?
-
- handle_directive $1, $3, $5, code_object, encoding, &block
- end
-
- text
- end
-
- #--
- # When 1.8.7 support is ditched prefix can be defaulted to ''
-
- def handle_directive prefix, directive, param, code_object = nil,
- encoding = nil
- blankline = "#{prefix.strip}\n"
- directive = directive.downcase
-
- case directive
- when 'arg', 'args' then
- return blankline unless code_object
-
- code_object.params = param
-
- blankline
- when 'category' then
- if RDoc::Context === code_object then
- section = code_object.add_section param, ''
- code_object.temporary_section = section
- end
-
- blankline # ignore category if we're not on an RDoc::Context
- when 'doc' then
- return blankline unless code_object
- code_object.document_self = true
- code_object.force_documentation = true
-
- blankline
- when 'enddoc' then
- return blankline unless code_object
- code_object.done_documenting = true
-
- blankline
- when 'include' then
- filename = param.split.first
- include_file filename, prefix, encoding
- when 'main' then
- @options.main_page = param if @options.respond_to? :main_page
-
- blankline
- when 'nodoc' then
- return blankline unless code_object
- code_object.document_self = nil # notify nodoc
- code_object.document_children = param !~ /all/i
-
- blankline
- when 'notnew', 'not_new', 'not-new' then
- return blankline unless RDoc::AnyMethod === code_object
-
- code_object.dont_rename_initialize = true
-
- blankline
- when 'startdoc' then
- return blankline unless code_object
-
- code_object.start_doc
- code_object.force_documentation = true
-
- blankline
- when 'stopdoc' then
- return blankline unless code_object
-
- code_object.stop_doc
-
- blankline
- when 'title' then
- @options.default_title = param if @options.respond_to? :default_title=
-
- blankline
- when 'yield', 'yields' then
- return blankline unless code_object
- # remove parameter &block
- code_object.params.sub!(/,?\s*&\w+/, '') if code_object.params
-
- code_object.block_params = param
-
- blankline
- else
- result = yield directive, param if block_given?
-
- case result
- when nil then
- code_object.metadata[directive] = param if code_object
-
- if RDoc::Markup::PreProcess.registered.include? directive then
- handler = RDoc::Markup::PreProcess.registered[directive]
- result = handler.call directive, param if handler
- else
- result = "#{prefix}:#{directive}: #{param}\n"
- end
- when false then
- result = "#{prefix}:#{directive}: #{param}\n"
- end
-
- result
- end
- end
-
- ##
- # Handles the <tt>:include: _filename_</tt> directive.
- #
- # If the first line of the included file starts with '#', and contains
- # an encoding information in the form 'coding:' or 'coding=', it is
- # removed.
- #
- # If all lines in the included file start with a '#', this leading '#'
- # is removed before inclusion. The included content is indented like
- # the <tt>:include:</tt> directive.
- #--
- # so all content will be verbatim because of the likely space after '#'?
- # TODO shift left the whole file content in that case
- # TODO comment stop/start #-- and #++ in included file must be processed here
-
- def include_file name, indent, encoding
- full_name = find_include_file name
-
- unless full_name then
- warn "Couldn't find file to include '#{name}' from #{@input_file_name}"
- return ''
- end
-
- content = RDoc::Encoding.read_file full_name, encoding, true
-
- # strip magic comment
- content = content.sub(/\A# .*coding[=:].*$/, '').lstrip
-
- # strip leading '#'s, but only if all lines start with them
- if content =~ /^[^#]/ then
- content.gsub(/^/, indent)
- else
- content.gsub(/^#?/, indent)
- 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
-
diff --git a/ruby_1_9_3/lib/rdoc/markup/raw.rb b/ruby_1_9_3/lib/rdoc/markup/raw.rb
deleted file mode 100644
index ca877c79af..0000000000
--- a/ruby_1_9_3/lib/rdoc/markup/raw.rb
+++ /dev/null
@@ -1,69 +0,0 @@
-##
-# A section of text that is added to the output document as-is
-
-class RDoc::Markup::Raw
-
- ##
- # The component parts of the list
-
- attr_reader :parts
-
- ##
- # Creates a new Raw containing +parts+
-
- def initialize *parts
- @parts = []
- @parts.push(*parts)
- end
-
- ##
- # Appends +text+
-
- def << text
- @parts << text
- end
-
- def == other # :nodoc:
- self.class == other.class and text == other.text
- end
-
- ##
- # Calls #accept_raw+ on +visitor+
-
- def accept visitor
- visitor.accept_raw self
- end
-
- ##
- # Appends +other+'s parts
-
- def merge other
- @parts.push(*other.parts)
- end
-
- def pretty_print q # :nodoc:
- self.class.name =~ /.*::(\w{4})/i
-
- q.group 2, "[#{$1.downcase}: ", ']' do
- q.seplist @parts do |part|
- q.pp part
- end
- end
- end
-
- ##
- # Appends +texts+ onto this Paragraph
-
- def push *texts
- self.parts.push(*texts)
- end
-
- ##
- # The raw text
-
- def text
- @parts.join ' '
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/markup/rule.rb b/ruby_1_9_3/lib/rdoc/markup/rule.rb
deleted file mode 100644
index b778f2bc09..0000000000
--- a/ruby_1_9_3/lib/rdoc/markup/rule.rb
+++ /dev/null
@@ -1,20 +0,0 @@
-##
-# A horizontal rule with a weight
-
-class RDoc::Markup::Rule < Struct.new :weight
-
- ##
- # Calls #accept_rule on +visitor+
-
- def accept visitor
- visitor.accept_rule self
- end
-
- def pretty_print q # :nodoc:
- q.group 2, '[rule:', ']' do
- q.pp weight
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/markup/text_formatter_test_case.rb b/ruby_1_9_3/lib/rdoc/markup/text_formatter_test_case.rb
deleted file mode 100644
index ba9e7c6187..0000000000
--- a/ruby_1_9_3/lib/rdoc/markup/text_formatter_test_case.rb
+++ /dev/null
@@ -1,116 +0,0 @@
-require 'rdoc/markup/formatter_test_case'
-
-##
-# Test case for creating new plain-text RDoc::Markup formatters. See also
-# RDoc::Markup::FormatterTestCase
-#
-# See test_rdoc_markup_to_rdoc.rb for a complete example.
-#
-# Example:
-#
-# class TestRDocMarkupToNewTextFormat < RDoc::Markup::TextFormatterTestCase
-#
-# add_visitor_tests
-# add_text_tests
-#
-# def setup
-# super
-#
-# @to = RDoc::Markup::ToNewTextFormat.new
-# end
-#
-# def accept_blank_line
-# assert_equal :junk, @to.res.join
-# end
-#
-# # ...
-#
-# end
-
-class RDoc::Markup::TextFormatterTestCase < RDoc::Markup::FormatterTestCase
-
- ##
- # Adds test cases to the calling TestCase.
-
- def self.add_text_tests
- self.class_eval do
-
- ##
- # Test case that calls <tt>@to.accept_heading</tt>
-
- def test_accept_heading_indent
- @to.start_accepting
- @to.indent = 3
- @to.accept_heading @RM::Heading.new(1, 'Hello')
-
- accept_heading_indent
- end
-
- ##
- # Test case that calls <tt>@to.accept_rule</tt>
-
- def test_accept_rule_indent
- @to.start_accepting
- @to.indent = 3
- @to.accept_rule @RM::Rule.new(1)
-
- accept_rule_indent
- end
-
- ##
- # Test case that calls <tt>@to.accept_verbatim</tt>
-
- def test_accept_verbatim_indent
- @to.start_accepting
- @to.indent = 2
- @to.accept_verbatim @RM::Verbatim.new("hi\n", " world\n")
-
- accept_verbatim_indent
- end
-
- ##
- # Test case that calls <tt>@to.accept_verbatim</tt> with a big indent
-
- def test_accept_verbatim_big_indent
- @to.start_accepting
- @to.indent = 2
- @to.accept_verbatim @RM::Verbatim.new("hi\n", "world\n")
-
- accept_verbatim_big_indent
- end
-
- ##
- # Test case that calls <tt>@to.accept_paragraph</tt> with an indent
-
- def test_accept_paragraph_indent
- @to.start_accepting
- @to.indent = 3
- @to.accept_paragraph @RM::Paragraph.new(('words ' * 30).strip)
-
- accept_paragraph_indent
- end
-
- ##
- # Test case that calls <tt>@to.accept_paragraph</tt> with a long line
-
- def test_accept_paragraph_wrap
- @to.start_accepting
- @to.accept_paragraph @RM::Paragraph.new(('words ' * 30).strip)
-
- accept_paragraph_wrap
- end
-
- ##
- # Test case that calls <tt>@to.attributes</tt> with an escaped
- # cross-reference. If this test doesn't pass something may be very
- # wrong.
-
- def test_attributes
- assert_equal 'Dog', @to.attributes("\\Dog")
- end
-
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/markup/to_ansi.rb b/ruby_1_9_3/lib/rdoc/markup/to_ansi.rb
deleted file mode 100644
index 1e8a0289d9..0000000000
--- a/ruby_1_9_3/lib/rdoc/markup/to_ansi.rb
+++ /dev/null
@@ -1,84 +0,0 @@
-require 'rdoc/markup/to_rdoc'
-
-##
-# Outputs RDoc markup with vibrant ANSI color!
-
-class RDoc::Markup::ToAnsi < RDoc::Markup::ToRdoc
-
- ##
- # Creates a new ToAnsi visitor that is ready to output vibrant ANSI color!
-
- def initialize markup = nil
- super
-
- @headings.clear
- @headings[1] = ["\e[1;32m", "\e[m"] # bold
- @headings[2] = ["\e[4;32m", "\e[m"] # underline
- @headings[3] = ["\e[32m", "\e[m"] # just green
- end
-
- ##
- # Maps attributes to ANSI sequences
-
- def init_tags
- add_tag :BOLD, "\e[1m", "\e[m"
- add_tag :TT, "\e[7m", "\e[m"
- add_tag :EM, "\e[4m", "\e[m"
- end
-
- ##
- # Overrides indent width to ensure output lines up correctly.
-
- def accept_list_item_end list_item
- width = case @list_type.last
- when :BULLET then
- 2
- when :NOTE, :LABEL then
- @res << "\n" unless res.length == 1
- 2
- else
- bullet = @list_index.last.to_s
- @list_index[-1] = @list_index.last.succ
- bullet.length + 2
- end
-
- @indent -= width
- end
-
- ##
- # Adds coloring to note and label list items
-
- def accept_list_item_start list_item
- bullet = case @list_type.last
- when :BULLET then
- '*'
- when :NOTE, :LABEL then
- attributes(list_item.label) + ":\n"
- else
- @list_index.last.to_s + '.'
- end
-
- case @list_type.last
- when :NOTE, :LABEL then
- @indent += 2
- @prefix = bullet + (' ' * @indent)
- else
- @prefix = (' ' * @indent) + bullet.ljust(bullet.length + 1)
-
- width = bullet.gsub(/\e\[[\d;]*m/, '').length + 1
-
- @indent += width
- end
- end
-
- ##
- # Starts accepting with a reset screen
-
- def start_accepting
- super
-
- @res = ["\e[0m"]
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/markup/to_bs.rb b/ruby_1_9_3/lib/rdoc/markup/to_bs.rb
deleted file mode 100644
index 32b1bbb9eb..0000000000
--- a/ruby_1_9_3/lib/rdoc/markup/to_bs.rb
+++ /dev/null
@@ -1,80 +0,0 @@
-require 'rdoc/markup/to_rdoc'
-
-##
-# Outputs RDoc markup with hot backspace action! You will probably need a
-# pager to use this output format.
-#
-# This formatter won't work on 1.8.6 because it lacks String#chars.
-
-class RDoc::Markup::ToBs < RDoc::Markup::ToRdoc
-
- ##
- # Returns a new ToBs that is ready for hot backspace action!
-
- def initialize markup = nil
- super
-
- @in_b = false
- @in_em = false
- end
-
- ##
- # Sets a flag that is picked up by #annotate to do the right thing in
- # #convert_string
-
- def init_tags
- add_tag :BOLD, '+b', '-b'
- add_tag :EM, '+_', '-_'
- add_tag :TT, '' , '' # we need in_tt information maintained
- end
-
- ##
- # Makes heading text bold.
-
- def accept_heading heading
- use_prefix or @res << ' ' * @indent
- @res << @headings[heading.level][0]
- @in_b = true
- @res << attributes(heading.text)
- @in_b = false
- @res << @headings[heading.level][1]
- @res << "\n"
- end
-
- ##
- # Turns on or off special handling for +convert_string+
-
- def annotate tag
- case tag
- when '+b' then @in_b = true
- when '-b' then @in_b = false
- when '+_' then @in_em = true
- when '-_' then @in_em = false
- end
- ''
- end
-
- ##
- # Calls convert_string on the result of convert_special
-
- def convert_special special
- convert_string super
- end
-
- ##
- # Adds bold or underline mixed with backspaces
-
- def convert_string string
- return string unless string.respond_to? :chars # your ruby is lame
- return string unless @in_b or @in_em
- chars = if @in_b then
- string.chars.map do |char| "#{char}\b#{char}" end
- elsif @in_em then
- string.chars.map do |char| "_\b#{char}" end
- end
-
- chars.join
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/markup/to_html.rb b/ruby_1_9_3/lib/rdoc/markup/to_html.rb
deleted file mode 100644
index bd5fdb493e..0000000000
--- a/ruby_1_9_3/lib/rdoc/markup/to_html.rb
+++ /dev/null
@@ -1,324 +0,0 @@
-require 'rdoc/markup/formatter'
-require 'rdoc/markup/inline'
-
-require 'cgi'
-
-##
-# Outputs RDoc markup as HTML
-
-class RDoc::Markup::ToHtml < RDoc::Markup::Formatter
-
- include RDoc::Text
-
- # :section: Utilities
-
- ##
- # Maps RDoc::Markup::Parser::LIST_TOKENS types to HTML tags
-
- LIST_TYPE_TO_HTML = {
- :BULLET => ['<ul>', '</ul>'],
- :LABEL => ['<dl class="rdoc-list">', '</dl>'],
- :LALPHA => ['<ol style="display: lower-alpha">', '</ol>'],
- :NOTE => ['<table class="rdoc-list">', '</table>'],
- :NUMBER => ['<ol>', '</ol>'],
- :UALPHA => ['<ol style="display: upper-alpha">', '</ol>'],
- }
-
- attr_reader :res # :nodoc:
- attr_reader :in_list_entry # :nodoc:
- attr_reader :list # :nodoc:
-
- ##
- # Path to this document for relative links
-
- attr_accessor :from_path
-
- ##
- # Converts a target url to one that is relative to a given path
-
- def self.gen_relative_url(path, target)
- from = File.dirname path
- to, to_file = File.split target
-
- from = from.split "/"
- to = to.split "/"
-
- from.delete '.'
- to.delete '.'
-
- while from.size > 0 and to.size > 0 and from[0] == to[0] do
- from.shift
- to.shift
- end
-
- from.fill ".."
- from.concat to
- from << to_file
- File.join(*from)
- end
-
- # :section:
-
- ##
- # Creates a new formatter that will output HTML
-
- def initialize markup = nil
- super
-
- @th = nil
- @in_list_entry = nil
- @list = nil
- @from_path = ''
-
- # external links
- @markup.add_special(/((link:|https?:|mailto:|ftp:|www\.)\S+\w)/, :HYPERLINK)
-
- # and links of the form <text>[<url>]
- @markup.add_special(/(((\{.*?\})|\b\S+?)\[\S+?\])/, :TIDYLINK)
-
- init_tags
- end
-
- # :section: Special Handling
- #
- # These methods handle special markup added by RDoc::Markup#add_special.
-
- ##
- # +special+ is a potential link. The following schemes are handled:
- #
- # <tt>mailto:</tt>::
- # Inserted as-is.
- # <tt>http:</tt>::
- # Links are checked to see if they reference an image. If so, that image
- # gets inserted using an <tt><img></tt> tag. Otherwise a conventional
- # <tt><a href></tt> is used.
- # <tt>link:</tt>::
- # Reference to a local file relative to the output directory.
-
- def handle_special_HYPERLINK(special)
- url = special.text
-
- gen_url url, url
- end
-
- ##
- # This +special+ is a link where the label is different from the URL
- # <tt>label[url]</tt> or <tt>{long label}[url]</tt>
-
- def handle_special_TIDYLINK(special)
- text = special.text
-
- return text unless text =~ /\{(.*?)\}\[(.*?)\]/ or text =~ /(\S+)\[(.*?)\]/
-
- label = $1
- url = $2
- gen_url url, label
- end
-
- # :section: Visitor
- #
- # These methods implement the HTML visitor.
-
- ##
- # Prepares the visitor for HTML generation
-
- def start_accepting
- @res = []
- @in_list_entry = []
- @list = []
- end
-
- ##
- # Returns the generated output
-
- def end_accepting
- @res.join
- end
-
- ##
- # Adds +paragraph+ to the output
-
- def accept_paragraph(paragraph)
- @res << "\n<p>"
- @res << wrap(to_html(paragraph.text))
- @res << "</p>\n"
- end
-
- ##
- # Adds +verbatim+ to the output
-
- def accept_verbatim(verbatim)
- @res << "\n<pre>"
- @res << CGI.escapeHTML(verbatim.text.rstrip)
- @res << "</pre>\n"
- end
-
- ##
- # Adds +rule+ to the output
-
- def accept_rule(rule)
- size = rule.weight
- size = 10 if size > 10
- @res << "<hr style=\"height: #{size}px\">\n"
- end
-
- ##
- # Prepares the visitor for consuming +list+
-
- def accept_list_start(list)
- @list << list.type
- @res << html_list_name(list.type, true)
- @in_list_entry.push false
- end
-
- ##
- # Finishes consumption of +list+
-
- def accept_list_end(list)
- @list.pop
- if tag = @in_list_entry.pop
- @res << tag
- end
- @res << html_list_name(list.type, false) << "\n"
- end
-
- ##
- # Prepares the visitor for consuming +list_item+
-
- def accept_list_item_start(list_item)
- if tag = @in_list_entry.last
- @res << tag
- end
-
- @res << list_item_start(list_item, @list.last)
- end
-
- ##
- # Finishes consumption of +list_item+
-
- def accept_list_item_end(list_item)
- @in_list_entry[-1] = list_end_for(@list.last)
- end
-
- ##
- # Adds +blank_line+ to the output
-
- def accept_blank_line(blank_line)
- # @res << annotate("<p />") << "\n"
- end
-
- ##
- # Adds +heading+ to the output
-
- def accept_heading(heading)
- @res << "\n<h#{heading.level}>"
- @res << to_html(heading.text)
- @res << "</h#{heading.level}>\n"
- end
-
- ##
- # Adds +raw+ to the output
-
- def accept_raw raw
- @res << raw.parts.join("\n")
- end
-
- # :section: Utilities
-
- ##
- # CGI escapes +text+
-
- def convert_string(text)
- CGI.escapeHTML text
- end
-
- ##
- # Generate a link for +url+, labeled with +text+. Handles the special cases
- # for img: and link: described under handle_special_HYPERLINK
-
- def gen_url(url, text)
- if url =~ /([A-Za-z]+):(.*)/ then
- type = $1
- path = $2
- else
- type = "http"
- path = url
- url = "http://#{url}"
- end
-
- if type == "link" then
- url = if path[0, 1] == '#' then # is this meaningful?
- path
- else
- self.class.gen_relative_url @from_path, path
- end
- end
-
- if (type == "http" or type == "https" or type == "link") and
- url =~ /\.(gif|png|jpg|jpeg|bmp)$/ then
- "<img src=\"#{url}\" />"
- else
- "<a href=\"#{url}\">#{text.sub(%r{^#{type}:/*}, '')}</a>"
- end
- end
-
- ##
- # Determines the HTML list element for +list_type+ and +open_tag+
-
- def html_list_name(list_type, open_tag)
- tags = LIST_TYPE_TO_HTML[list_type]
- raise RDoc::Error, "Invalid list type: #{list_type.inspect}" unless tags
- tags[open_tag ? 0 : 1]
- end
-
- ##
- # Maps attributes to HTML tags
-
- def init_tags
- add_tag :BOLD, "<b>", "</b>"
- add_tag :TT, "<tt>", "</tt>"
- add_tag :EM, "<em>", "</em>"
- end
-
- ##
- # Returns the HTML tag for +list_type+, possible using a label from
- # +list_item+
-
- def list_item_start(list_item, list_type)
- case list_type
- when :BULLET, :LALPHA, :NUMBER, :UALPHA then
- "<li>"
- when :LABEL then
- "<dt>#{to_html list_item.label}</dt>\n<dd>"
- when :NOTE then
- "<tr><td class=\"rdoc-term\"><p>#{to_html list_item.label}</p></td>\n<td>"
- else
- raise RDoc::Error, "Invalid list type: #{list_type.inspect}"
- end
- end
-
- ##
- # Returns the HTML end-tag for +list_type+
-
- def list_end_for(list_type)
- case list_type
- when :BULLET, :LALPHA, :NUMBER, :UALPHA then
- "</li>"
- when :LABEL then
- "</dd>"
- when :NOTE then
- "</td></tr>"
- else
- raise RDoc::Error, "Invalid list type: #{list_type.inspect}"
- end
- end
-
- ##
- # Converts +item+ to HTML using RDoc::Text#to_html
-
- def to_html item
- super convert_flow @am.flow item
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/markup/to_html_crossref.rb b/ruby_1_9_3/lib/rdoc/markup/to_html_crossref.rb
deleted file mode 100644
index 450ea960b5..0000000000
--- a/ruby_1_9_3/lib/rdoc/markup/to_html_crossref.rb
+++ /dev/null
@@ -1,120 +0,0 @@
-require 'rdoc/markup/to_html'
-require 'rdoc/cross_reference'
-
-##
-# Subclass of the RDoc::Markup::ToHtml class that supports looking up method
-# names, classes, etc to create links. RDoc::CrossReference is used to
-# generate those links based on the current context.
-
-class RDoc::Markup::ToHtmlCrossref < RDoc::Markup::ToHtml
-
- # :stopdoc:
- ALL_CROSSREF_REGEXP = RDoc::CrossReference::ALL_CROSSREF_REGEXP
- CLASS_REGEXP_STR = RDoc::CrossReference::CLASS_REGEXP_STR
- CROSSREF_REGEXP = RDoc::CrossReference::CROSSREF_REGEXP
- METHOD_REGEXP_STR = RDoc::CrossReference::METHOD_REGEXP_STR
- # :startdoc:
-
- ##
- # RDoc::CodeObject for generating references
-
- attr_accessor :context
-
- ##
- # Should we show '#' characters on method references?
-
- attr_accessor :show_hash
-
- ##
- # Creates a new crossref resolver that generates links relative to +context+
- # which lives at +from_path+ in the generated files. '#' characters on
- # references are removed unless +show_hash+ is true. Only method names
- # preceded by '#' or '::' are linked, unless +hyperlink_all+ is true.
-
- def initialize(from_path, context, show_hash, hyperlink_all = false,
- markup = nil)
- raise ArgumentError, 'from_path cannot be nil' if from_path.nil?
- super markup
-
- crossref_re = hyperlink_all ? ALL_CROSSREF_REGEXP : CROSSREF_REGEXP
-
- @cross_reference = RDoc::CrossReference.new context
-
- @markup.add_special crossref_re, :CROSSREF
- @markup.add_special(/rdoc-ref:\S+\w/, :HYPERLINK)
-
- @from_path = from_path
- @hyperlink_all = hyperlink_all
- @show_hash = show_hash
- end
-
- ##
- # Creates a link to the reference +name+ if the name exists. If +text+ is
- # given it is used as the link text, otherwise +name+ is used.
-
- def cross_reference name, text = nil
- lookup = name
-
- name = name[1..-1] unless @show_hash if name[0, 1] == '#'
-
- text = name unless text
-
- link lookup, text
- end
-
- ##
- # We're invoked when any text matches the CROSSREF pattern. If we find the
- # corresponding reference, generate a link. If the name we're looking for
- # contains no punctuation, we look for it up the module/class chain. For
- # example, ToHtml is found, even without the <tt>RDoc::Markup::</tt> prefix,
- # because we look for it in module Markup first.
-
- def handle_special_CROSSREF(special)
- name = special.text
-
- unless @hyperlink_all then
- # This ensures that words entirely consisting of lowercase letters will
- # not have cross-references generated (to suppress lots of erroneous
- # cross-references to "new" in text, for instance)
- return name if name =~ /\A[a-z]*\z/
- end
-
- cross_reference name
- end
-
- ##
- # Handles <tt>rdoc-ref:</tt> scheme links and allows RDoc::Markup::ToHtml to
- # handle other schemes.
-
- def handle_special_HYPERLINK special
- return cross_reference $' if special.text =~ /\Ardoc-ref:/
-
- super
- end
-
- ##
- # Generates links for <tt>rdoc-ref:</tt> scheme URLs and allows
- # RDoc::Markup::ToHtml to handle other schemes.
-
- def gen_url url, text
- return super unless url =~ /\Ardoc-ref:/
-
- cross_reference $', text
- end
-
- ##
- # Creates an HTML link to +name+ with the given +text+.
-
- def link name, text
- ref = @cross_reference.resolve name, text
-
- case ref
- when String then
- ref
- else
- "<a href=\"#{ref.as_href @from_path}\">#{text}</a>"
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/markup/to_rdoc.rb b/ruby_1_9_3/lib/rdoc/markup/to_rdoc.rb
deleted file mode 100644
index 6f2faac2f6..0000000000
--- a/ruby_1_9_3/lib/rdoc/markup/to_rdoc.rb
+++ /dev/null
@@ -1,301 +0,0 @@
-require 'rdoc/markup/formatter'
-require 'rdoc/markup/inline'
-
-##
-# Outputs RDoc markup as RDoc markup! (mostly)
-
-class RDoc::Markup::ToRdoc < RDoc::Markup::Formatter
-
- ##
- # Current indent amount for output in characters
-
- attr_accessor :indent
-
- ##
- # Output width in characters
-
- attr_accessor :width
-
- ##
- # Stack of current list indexes for alphabetic and numeric lists
-
- attr_reader :list_index
-
- ##
- # Stack of list types
-
- attr_reader :list_type
-
- ##
- # Stack of list widths for indentation
-
- attr_reader :list_width
-
- ##
- # Prefix for the next list item. See #use_prefix
-
- attr_reader :prefix
-
- ##
- # Output accumulator
-
- attr_reader :res
-
- ##
- # Creates a new formatter that will output (mostly) \RDoc markup
-
- def initialize markup = nil
- super
-
- @markup.add_special(/\\\S/, :SUPPRESSED_CROSSREF)
- @width = 78
- init_tags
-
- @headings = {}
- @headings.default = []
-
- @headings[1] = ['= ', '']
- @headings[2] = ['== ', '']
- @headings[3] = ['=== ', '']
- @headings[4] = ['==== ', '']
- @headings[5] = ['===== ', '']
- @headings[6] = ['====== ', '']
- end
-
- ##
- # Maps attributes to HTML sequences
-
- def init_tags
- add_tag :BOLD, "<b>", "</b>"
- add_tag :TT, "<tt>", "</tt>"
- add_tag :EM, "<em>", "</em>"
- end
-
- ##
- # Adds +blank_line+ to the output
-
- def accept_blank_line blank_line
- @res << "\n"
- end
-
- ##
- # Adds +heading+ to the output
-
- def accept_heading heading
- use_prefix or @res << ' ' * @indent
- @res << @headings[heading.level][0]
- @res << attributes(heading.text)
- @res << @headings[heading.level][1]
- @res << "\n"
- end
-
- ##
- # Finishes consumption of +list+
-
- def accept_list_end list
- @list_index.pop
- @list_type.pop
- @list_width.pop
- end
-
- ##
- # Finishes consumption of +list_item+
-
- def accept_list_item_end list_item
- width = case @list_type.last
- when :BULLET then
- 2
- when :NOTE, :LABEL then
- @res << "\n"
- 2
- else
- bullet = @list_index.last.to_s
- @list_index[-1] = @list_index.last.succ
- bullet.length + 2
- end
-
- @indent -= width
- end
-
- ##
- # Prepares the visitor for consuming +list_item+
-
- def accept_list_item_start list_item
- type = @list_type.last
-
- case type
- when :NOTE, :LABEL then
- bullet = attributes(list_item.label) + ":\n"
- @prefix = ' ' * @indent
- @indent += 2
- @prefix << bullet + (' ' * @indent)
- else
- bullet = type == :BULLET ? '*' : @list_index.last.to_s + '.'
- @prefix = (' ' * @indent) + bullet.ljust(bullet.length + 1)
- width = bullet.length + 1
- @indent += width
- end
- end
-
- ##
- # Prepares the visitor for consuming +list+
-
- def accept_list_start list
- case list.type
- when :BULLET then
- @list_index << nil
- @list_width << 1
- when :LABEL, :NOTE then
- @list_index << nil
- @list_width << 2
- when :LALPHA then
- @list_index << 'a'
- @list_width << list.items.length.to_s.length
- when :NUMBER then
- @list_index << 1
- @list_width << list.items.length.to_s.length
- when :UALPHA then
- @list_index << 'A'
- @list_width << list.items.length.to_s.length
- else
- raise RDoc::Error, "invalid list type #{list.type}"
- end
-
- @list_type << list.type
- end
-
- ##
- # Adds +paragraph+ to the output
-
- def accept_paragraph paragraph
- wrap attributes(paragraph.text)
- end
-
- ##
- # Adds +paragraph+ to the output
-
- def accept_indented_paragraph paragraph
- @indent += paragraph.indent
- wrap attributes(paragraph.text)
- @indent -= paragraph.indent
- end
-
- ##
- # Adds +raw+ to the output
-
- def accept_raw raw
- @res << raw.parts.join("\n")
- end
-
- ##
- # Adds +rule+ to the output
-
- def accept_rule rule
- use_prefix or @res << ' ' * @indent
- @res << '-' * (@width - @indent)
- @res << "\n"
- end
-
- ##
- # Outputs +verbatim+ indented 2 columns
-
- def accept_verbatim verbatim
- indent = ' ' * (@indent + 2)
-
- verbatim.parts.each do |part|
- @res << indent unless part == "\n"
- @res << part
- end
-
- @res << "\n" unless @res =~ /\n\z/
- end
-
- ##
- # Applies attribute-specific markup to +text+ using RDoc::AttributeManager
-
- def attributes text
- flow = @am.flow text.dup
- convert_flow flow
- end
-
- ##
- # Returns the generated output
-
- def end_accepting
- @res.join
- end
-
- ##
- # Removes preceding \\ from the suppressed crossref +special+
-
- def handle_special_SUPPRESSED_CROSSREF special
- text = special.text
- text = text.sub('\\', '') unless in_tt?
- text
- end
-
- ##
- # Prepares the visitor for text generation
-
- def start_accepting
- @res = [""]
- @indent = 0
- @prefix = nil
-
- @list_index = []
- @list_type = []
- @list_width = []
- end
-
- ##
- # Adds the stored #prefix to the output and clears it. Lists generate a
- # prefix for later consumption.
-
- def use_prefix
- prefix = @prefix
- @prefix = nil
- @res << prefix if prefix
-
- prefix
- end
-
- ##
- # Wraps +text+ to #width
-
- def wrap text
- return unless text && !text.empty?
-
- text_len = @width - @indent
-
- text_len = 20 if text_len < 20
-
- re = /^(.{0,#{text_len}})[ \n]/
- next_prefix = ' ' * @indent
-
- prefix = @prefix || next_prefix
- @prefix = nil
-
- @res << prefix
-
- while text.length > text_len
- if text =~ re then
- @res << $1
- text.slice!(0, $&.length)
- else
- @res << text.slice!(0, text_len)
- end
-
- @res << "\n" << next_prefix
- end
-
- if text.empty? then
- @res.pop
- @res.pop
- else
- @res << text
- @res << "\n"
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/markup/to_test.rb b/ruby_1_9_3/lib/rdoc/markup/to_test.rb
deleted file mode 100644
index 4847fd29f7..0000000000
--- a/ruby_1_9_3/lib/rdoc/markup/to_test.rb
+++ /dev/null
@@ -1,72 +0,0 @@
-require 'rdoc/markup'
-require 'rdoc/markup/formatter'
-
-##
-# This Markup outputter is used for testing purposes.
-
-class RDoc::Markup::ToTest < RDoc::Markup::Formatter
-
- # :stopdoc:
-
- ##
- # :section: Visitor
-
- def start_accepting
- @res = []
- @list = []
- end
-
- def end_accepting
- @res
- end
-
- def accept_paragraph(paragraph)
- @res << convert_flow(@am.flow(paragraph.text))
- end
-
- def accept_raw raw
- @res << raw.parts.join
- end
-
- def accept_verbatim(verbatim)
- @res << verbatim.text.gsub(/^(\S)/, ' \1')
- end
-
- def accept_list_start(list)
- @list << case list.type
- when :BULLET then
- '*'
- when :NUMBER then
- '1'
- else
- list.type
- end
- end
-
- def accept_list_end(list)
- @list.pop
- end
-
- def accept_list_item_start(list_item)
- @res << "#{' ' * (@list.size - 1)}#{@list.last}: "
- end
-
- def accept_list_item_end(list_item)
- end
-
- def accept_blank_line(blank_line)
- @res << "\n"
- end
-
- def accept_heading(heading)
- @res << "#{'=' * heading.level} #{heading.text}"
- end
-
- def accept_rule(rule)
- @res << '-' * rule.weight
- end
-
- # :startdoc:
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/markup/to_tt_only.rb b/ruby_1_9_3/lib/rdoc/markup/to_tt_only.rb
deleted file mode 100644
index 078e87db98..0000000000
--- a/ruby_1_9_3/lib/rdoc/markup/to_tt_only.rb
+++ /dev/null
@@ -1,114 +0,0 @@
-require 'rdoc/markup/formatter'
-require 'rdoc/markup/inline'
-
-##
-# Extracts sections of text enclosed in plus, tt or code. Used to discover
-# undocumented parameters.
-
-class RDoc::Markup::ToTtOnly < RDoc::Markup::Formatter
-
- ##
- # Stack of list types
-
- attr_reader :list_type
-
- ##
- # Output accumulator
-
- attr_reader :res
-
- ##
- # Creates a new tt-only formatter.
-
- def initialize markup = nil
- super
-
- add_tag :TT, nil, nil
- end
-
- ##
- # Pops the list type for +list+ from #list_type
-
- def accept_list_end list
- @list_type.pop
- end
-
- ##
- # Pushes the list type for +list+ onto #list_type
-
- def accept_list_start list
- @list_type << list.type
- end
-
- ##
- # Prepares the visitor for consuming +list_item+
-
- def accept_list_item_start list_item
- case @list_type.last
- when :NOTE, :LABEL then
- tt_sections(list_item.label)
- end
- end
-
- ##
- # Adds +paragraph+ to the output
-
- def accept_paragraph paragraph
- tt_sections(paragraph.text)
- end
-
- ##
- # Does nothing to +markup_item+ because it doesn't have any user-built
- # content
-
- def do_nothing markup_item
- end
-
- alias accept_blank_line do_nothing # :nodoc:
- alias accept_heading do_nothing # :nodoc:
- alias accept_list_item_end do_nothing # :nodoc:
- alias accept_raw do_nothing # :nodoc:
- alias accept_rule do_nothing # :nodoc:
- alias accept_verbatim do_nothing # :nodoc:
-
- ##
- # Extracts tt sections from +text+
-
- def tt_sections text
- flow = @am.flow text.dup
-
- flow.each do |item|
- case item
- when String then
- @res << item if in_tt?
- when RDoc::Markup::AttrChanger then
- off_tags res, item
- on_tags res, item
- when RDoc::Markup::Special then
- @res << convert_special(item) if in_tt? # TODO can this happen?
- else
- raise "Unknown flow element: #{item.inspect}"
- end
- end
-
- res
- end
-
- ##
- # Returns an Array of items that were wrapped in plus, tt or code.
-
- def end_accepting
- @res.compact
- end
-
- ##
- # Prepares the visitor for gathering tt sections
-
- def start_accepting
- @res = []
-
- @list_type = []
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/markup/verbatim.rb b/ruby_1_9_3/lib/rdoc/markup/verbatim.rb
deleted file mode 100644
index 8fe2184699..0000000000
--- a/ruby_1_9_3/lib/rdoc/markup/verbatim.rb
+++ /dev/null
@@ -1,45 +0,0 @@
-##
-# A section of verbatim text
-
-class RDoc::Markup::Verbatim < RDoc::Markup::Raw
-
- ##
- # Calls #accept_verbatim on +visitor+
-
- def accept visitor
- visitor.accept_verbatim self
- end
-
- ##
- # Collapses 3+ newlines into two newlines
-
- def normalize
- parts = []
-
- newlines = 0
-
- @parts.each do |part|
- case part
- when /^\s*\n/ then
- newlines += 1
- parts << part if newlines == 1
- else
- newlines = 0
- parts << part
- end
- end
-
- parts.pop if parts.last =~ /\A\r?\n\z/
-
- @parts = parts
- end
-
- ##
- # The text of the section
-
- def text
- @parts.join
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/meta_method.rb b/ruby_1_9_3/lib/rdoc/meta_method.rb
deleted file mode 100644
index e0c065c2ba..0000000000
--- a/ruby_1_9_3/lib/rdoc/meta_method.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-require 'rdoc/any_method'
-
-##
-# MetaMethod represents a meta-programmed method
-
-class RDoc::MetaMethod < RDoc::AnyMethod
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/method_attr.rb b/ruby_1_9_3/lib/rdoc/method_attr.rb
deleted file mode 100644
index a4cd3c5fff..0000000000
--- a/ruby_1_9_3/lib/rdoc/method_attr.rb
+++ /dev/null
@@ -1,355 +0,0 @@
-require 'rdoc/code_object'
-
-##
-# Abstract class representing either a method or an attribute.
-
-class RDoc::MethodAttr < RDoc::CodeObject
-
- include Comparable
-
- ##
- # Name of this method/attribute.
-
- attr_accessor :name
-
- ##
- # public, protected, private
-
- attr_accessor :visibility
-
- ##
- # Is this a singleton method/attribute?
-
- attr_accessor :singleton
-
- ##
- # Source file token stream
-
- attr_reader :text
-
- ##
- # Array of other names for this method/attribute
-
- attr_reader :aliases
-
- ##
- # The method/attribute we're aliasing
-
- attr_accessor :is_alias_for
-
- #--
- # The attributes below are for AnyMethod only.
- # They are left here for the time being to
- # allow ri to operate.
- # TODO modify ri to avoid calling these on attributes.
- #++
-
- ##
- # Parameters yielded by the called block
-
- attr_reader :block_params
-
- ##
- # Parameters for this method
-
- attr_accessor :params
-
- ##
- # Different ways to call this method
-
- attr_accessor :call_seq
-
- ##
- # The call_seq or the param_seq with method name, if there is no call_seq.
-
- attr_reader :arglists
-
- ##
- # Pretty parameter list for this method
-
- attr_reader :param_seq
-
-
- ##
- # Creates a new MethodAttr from token stream +text+ and method or attribute
- # name +name+.
- #
- # Usually this is called by super from a subclass.
-
- def initialize text, name
- super()
-
- @text = text
- @name = name
-
- @aliases = []
- @is_alias_for = nil
- @parent_name = nil
- @singleton = nil
- @visibility = :public
- @see = false
-
- @arglists = nil
- @block_params = nil
- @call_seq = nil
- @param_seq = nil
- @params = nil
- end
-
- ##
- # Order by #singleton then #name
-
- def <=>(other)
- [@singleton ? 0 : 1, name] <=> [other.singleton ? 0 : 1, other.name]
- end
-
- ##
- # A method/attribute is documented if any of the following is true:
- # - it was marked with :nodoc:;
- # - it has a comment;
- # - it is an alias for a documented method;
- # - it has a +#see+ method that is documented.
-
- def documented?
- super or
- (is_alias_for and is_alias_for.documented?) or
- (see and see.documented?)
- end
-
- ##
- # A method/attribute to look at,
- # in particular if this method/attribute has no documentation.
- #
- # It can be a method/attribute of the superclass or of an included module,
- # including the Kernel module, which is always appended to the included
- # modules.
- #
- # Returns +nil+ if there is no such method/attribute.
- # The +#is_alias_for+ method/attribute, if any, is not included.
- #
- # Templates may generate a "see also ..." if this method/attribute
- # has documentation, and "see ..." if it does not.
-
- def see
- @see = find_see if @see == false
- @see
- end
-
- def find_see # :nodoc:
- return nil if singleton || is_alias_for
-
- # look for the method
- other = find_method_or_attribute name
- return other if other
-
- # if it is a setter, look for a getter
- return nil unless name =~ /[a-z_]=$/i # avoid == or ===
- return find_method_or_attribute name[0..-2]
- end
-
- def find_method_or_attribute name # :nodoc:
- return nil unless parent.respond_to? :ancestors
-
- searched = parent.ancestors
- kernel = RDoc::TopLevel.all_modules_hash['Kernel']
-
- searched << kernel if kernel &&
- parent != kernel && !searched.include?(kernel)
-
- searched.each do |ancestor|
- next if parent == ancestor
- next if String === ancestor
-
- other = ancestor.find_method_named('#' << name) ||
- ancestor.find_attribute_named(name)
-
- return other if other
- end
-
- nil
- end
-
- ##
- # Abstract method. Contexts in their building phase call this
- # to register a new alias for this known method/attribute.
- #
- # - creates a new AnyMethod/Attribute +newa+ named an_alias.new_name;
- # - adds +self+ as +newa.is_alias_for+;
- # - adds +newa+ to #aliases
- # - adds +newa+ to the methods/attributes of +context+.
-
- def add_alias(an_alias, context)
- raise NotImplementedError
- end
-
- ##
- # HTML fragment reference for this method
-
- def aref
- type = singleton ? 'c' : 'i'
- # % characters are not allowed in html names => dash instead
- "#{aref_prefix}-#{type}-#{html_name}"
- end
-
- ##
- # Prefix for +aref+, defined by subclasses.
-
- def aref_prefix
- raise NotImplementedError
- end
-
- ##
- # Attempts to sanitize the content passed by the ruby parser:
- # remove outer parentheses, etc.
-
- def block_params=(value)
- # 'yield.to_s' or 'assert yield, msg'
- return @block_params = '' if value =~ /^[\.,]/
-
- # remove trailing 'if/unless ...'
- return @block_params = '' if value =~ /^(if|unless)\s/
-
- value = $1.strip if value =~ /^(.+)\s(if|unless)\s/
-
- # outer parentheses
- value = $1 if value =~ /^\s*\((.*)\)\s*$/
- value = value.strip
-
- # proc/lambda
- return @block_params = $1 if value =~ /^(proc|lambda)(\s*\{|\sdo)/
-
- # surrounding +...+ or [...]
- value = $1.strip if value =~ /^\+(.*)\+$/
- value = $1.strip if value =~ /^\[(.*)\]$/
-
- return @block_params = '' if value.empty?
-
- # global variable
- return @block_params = 'str' if value =~ /^\$[&0-9]$/
-
- # wipe out array/hash indices
- value.gsub!(/(\w)\[[^\[]+\]/, '\1')
-
- # remove @ from class/instance variables
- value.gsub!(/@@?([a-z0-9_]+)/, '\1')
-
- # method calls => method name
- value.gsub!(/([A-Z:a-z0-9_]+)\.([a-z0-9_]+)(\s*\(\s*[a-z0-9_.,\s]*\s*\)\s*)?/) do
- case $2
- when 'to_s' then $1
- when 'const_get' then 'const'
- when 'new' then
- $1.split('::').last. # ClassName => class_name
- gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
- gsub(/([a-z\d])([A-Z])/,'\1_\2').
- downcase
- else
- $2
- end
- end
-
- # class prefixes
- value.gsub!(/[A-Za-z0-9_:]+::/, '')
-
- # simple expressions
- value = $1 if value =~ /^([a-z0-9_]+)\s*[-*+\/]/
-
- @block_params = value.strip
- end
-
- ##
- # HTML id-friendly method/attribute name
-
- def html_name
- CGI.escape(@name.gsub('-', '-2D')).gsub('%','-').sub(/^-/, '')
- end
-
- ##
- # Full method/attribute name including namespace
-
- def full_name
- @full_name || "#{parent_name}#{pretty_name}"
- end
-
- ##
- # '::' for a class method/attribute, '#' for an instance method.
-
- def name_prefix
- singleton ? '::' : '#'
- end
-
- ##
- # Method/attribute name with class/instance indicator
-
- def pretty_name
- "#{name_prefix}#{@name}"
- end
-
- ##
- # Type of method/attribute (class or instance)
-
- def type
- singleton ? 'class' : 'instance'
- end
-
- ##
- # Path to this method
-
- def path
- "#{@parent.path}##{aref}"
- end
-
- ##
- # Name of our parent with special handling for un-marshaled methods
-
- def parent_name
- @parent_name || super
- end
-
- def pretty_print q # :nodoc:
- alias_for = @is_alias_for ? "alias for #{@is_alias_for.name}" : nil
-
- q.group 2, "[#{self.class.name} #{full_name} #{visibility}", "]" do
- if alias_for then
- q.breakable
- q.text alias_for
- end
-
- if text then
- q.breakable
- q.text "text:"
- q.breakable
- q.pp @text
- end
-
- unless comment.empty? then
- q.breakable
- q.text "comment:"
- q.breakable
- q.pp @comment
- end
- end
- end
-
- def inspect # :nodoc:
- alias_for = @is_alias_for ? " (alias for #{@is_alias_for.name})" : nil
- visibility = self.visibility
- visibility = "forced #{visibility}" if force_documentation
- "#<%s:0x%x %s (%s)%s>" % [
- self.class, object_id,
- full_name,
- visibility,
- alias_for,
- ]
- end
-
- def to_s # :nodoc:
- if @is_alias_for
- "#{self.class.name}: #{full_name} -> #{is_alias_for}"
- else
- "#{self.class.name}: #{full_name}"
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/normal_class.rb b/ruby_1_9_3/lib/rdoc/normal_class.rb
deleted file mode 100644
index f67380e783..0000000000
--- a/ruby_1_9_3/lib/rdoc/normal_class.rb
+++ /dev/null
@@ -1,71 +0,0 @@
-require 'rdoc/class_module'
-
-##
-# A normal class, neither singleton nor anonymous
-
-class RDoc::NormalClass < RDoc::ClassModule
-
- ##
- # Appends the superclass, if any, to the included modules.
-
- def ancestors
- superclass ? super + [superclass] : super
- end
-
- ##
- # The definition of this class, <tt>class MyClassName</tt>
-
- def definition
- "class #{full_name}"
- end
-
- def inspect # :nodoc:
- superclass = @superclass ? " < #{@superclass}" : nil
- "<%s:0x%x class %s%s includes: %p attributes: %p methods: %p aliases: %p>" % [
- self.class, object_id,
- full_name, superclass, @includes, @attributes, @method_list, @aliases
- ]
- end
-
- def to_s # :nodoc:
- display = "#{self.class.name} #{self.full_name}"
- if superclass
- display << ' < ' << (superclass.is_a?(String) ? superclass : superclass.full_name)
- end
- display << ' -> ' << is_alias_for.to_s if is_alias_for
- display
- end
-
- def pretty_print q # :nodoc:
- superclass = @superclass ? " < #{@superclass}" : nil
-
- q.group 2, "[class #{full_name}#{superclass} ", "]" do
- q.breakable
- q.text "includes:"
- q.breakable
- q.seplist @includes do |inc| q.pp inc end
-
- q.breakable
- q.text "attributes:"
- q.breakable
- q.seplist @attributes do |inc| q.pp inc end
-
- q.breakable
- q.text "methods:"
- q.breakable
- q.seplist @method_list do |inc| q.pp inc end
-
- q.breakable
- q.text "aliases:"
- q.breakable
- q.seplist @aliases do |inc| q.pp inc end
-
- q.breakable
- q.text "comment:"
- q.breakable
- q.pp comment
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/normal_module.rb b/ruby_1_9_3/lib/rdoc/normal_module.rb
deleted file mode 100644
index 0fa7223547..0000000000
--- a/ruby_1_9_3/lib/rdoc/normal_module.rb
+++ /dev/null
@@ -1,66 +0,0 @@
-require 'rdoc/class_module'
-
-##
-# A normal module, like NormalClass
-
-class RDoc::NormalModule < RDoc::ClassModule
-
- def inspect # :nodoc:
- "#<%s:0x%x module %s includes: %p attributes: %p methods: %p aliases: %p>" % [
- self.class, object_id,
- full_name, @includes, @attributes, @method_list, @aliases
- ]
- end
-
- ##
- # The definition of this module, <tt>module MyModuleName</tt>
-
- def definition
- "module #{full_name}"
- end
-
- ##
- # This is a module, returns true
-
- def module?
- true
- end
-
- def pretty_print q # :nodoc:
- q.group 2, "[module #{full_name}: ", "]" do
- q.breakable
- q.text "includes:"
- q.breakable
- q.seplist @includes do |inc| q.pp inc end
- q.breakable
-
- q.text "attributes:"
- q.breakable
- q.seplist @attributes do |inc| q.pp inc end
- q.breakable
-
- q.text "methods:"
- q.breakable
- q.seplist @method_list do |inc| q.pp inc end
- q.breakable
-
- q.text "aliases:"
- q.breakable
- q.seplist @aliases do |inc| q.pp inc end
- q.breakable
-
- q.text "comment:"
- q.breakable
- q.pp comment
- end
- end
-
- ##
- # Modules don't have one, raises NoMethodError
-
- def superclass
- raise NoMethodError, "#{full_name} is a module"
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/options.rb b/ruby_1_9_3/lib/rdoc/options.rb
deleted file mode 100644
index bab5463897..0000000000
--- a/ruby_1_9_3/lib/rdoc/options.rb
+++ /dev/null
@@ -1,770 +0,0 @@
-require 'optparse'
-
-require 'rdoc/ri/paths'
-
-##
-# RDoc::Options handles the parsing and storage of options
-
-class RDoc::Options
-
- ##
- # The deprecated options.
-
- DEPRECATED = {
- '--accessor' => 'support discontinued',
- '--diagram' => 'support discontinued',
- '--help-output' => 'support discontinued',
- '--image-format' => 'was an option for --diagram',
- '--inline-source' => 'source code is now always inlined',
- '--merge' => 'ri now always merges class information',
- '--one-file' => 'support discontinued',
- '--op-name' => 'support discontinued',
- '--opname' => 'support discontinued',
- '--promiscuous' => 'files always only document their content',
- '--ri-system' => 'Ruby installers use other techniques',
- }
-
- ##
- # Template option validator for OptionParser
-
- Template = nil
-
- ##
- # Character-set for HTML output. #encoding is preferred over #charset
-
- attr_accessor :charset
-
- ##
- # If true, RDoc will not write any files.
-
- attr_accessor :dry_run
-
- ##
- # Encoding of output where. This is set via --encoding.
-
- attr_accessor :encoding if Object.const_defined? :Encoding
-
- ##
- # Files matching this pattern will be excluded
-
- attr_accessor :exclude
-
- ##
- # The list of files to be processed
-
- attr_accessor :files
-
- ##
- # Create the output even if the output directory does not look
- # like an rdoc output directory
-
- attr_accessor :force_output
-
- ##
- # Scan newer sources than the flag file if true.
-
- attr_accessor :force_update
-
- ##
- # Formatter to mark up text with
-
- attr_accessor :formatter
-
- ##
- # Description of the output generator (set with the <tt>--fmt</tt> option)
-
- attr_accessor :generator
-
- ##
- # Loaded generator options. Used to prevent --help from loading the same
- # options multiple times.
-
- attr_accessor :generator_options
-
- ##
- # Old rdoc behavior: hyperlink all words that match a method name,
- # even if not preceded by '#' or '::'
-
- attr_accessor :hyperlink_all
-
- ##
- # Include line numbers in the source code
-
- attr_accessor :line_numbers
-
- ##
- # 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
-
- ##
- # If true, only report on undocumented files
-
- attr_accessor :coverage_report
-
- ##
- # The name of the output directory
-
- attr_accessor :op_dir
-
- ##
- # The OptionParser for this instance
-
- attr_accessor :option_parser
-
- ##
- # Is RDoc in pipe mode?
-
- attr_accessor :pipe
-
- ##
- # Array of directories to search for files to satisfy an :include:
-
- attr_accessor :rdoc_include
-
- ##
- # Include the '#' at the front of hyperlinked instance method names
-
- attr_accessor :show_hash
-
- ##
- # The number of columns in a tab
-
- attr_accessor :tab_width
-
- ##
- # Template to be used when generating output
-
- attr_accessor :template
-
- ##
- # Directory the template lives in
-
- attr_accessor :template_dir
-
- ##
- # Documentation title
-
- attr_accessor :title
-
- ##
- # Should RDoc update the timestamps in the output dir?
-
- attr_accessor :update_output_dir
-
- ##
- # Verbosity, zero means quiet
-
- attr_accessor :verbosity
-
- ##
- # URL of web cvs frontend
-
- attr_accessor :webcvs
-
- ##
- # Minimum visibility of a documented method. One of +:public+,
- # +:protected+, +:private+. May be overridden on a per-method
- # basis with the :doc: directive.
-
- attr_accessor :visibility
-
- def initialize # :nodoc:
- require 'rdoc/rdoc'
- @dry_run = false
- @exclude = []
- @force_output = false
- @force_update = true
- @generator = nil
- @generator_name = nil
- @generator_options = []
- @generators = RDoc::RDoc::GENERATORS
- @hyperlink_all = false
- @line_numbers = false
- @main_page = nil
- @coverage_report = false
- @op_dir = nil
- @pipe = false
- @rdoc_include = []
- @show_hash = false
- @stylesheet_url = nil
- @tab_width = 8
- @template = nil
- @template_dir = nil
- @title = nil
- @update_output_dir = true
- @verbosity = 1
- @visibility = :protected
- @webcvs = nil
-
- if Object.const_defined? :Encoding then
- @encoding = Encoding.default_external
- @charset = @encoding.to_s
- else
- @charset = 'UTF-8'
- end
- end
-
- ##
- # Check that the files on the command line exist
-
- def check_files
- @files.delete_if do |file|
- if File.exist? file then
- if File.readable? file then
- false
- else
- warn "file '#{file}' not readable"
-
- true
- end
- else
- warn "file '#{file}' not found"
-
- true
- end
- end
- end
-
- ##
- # Ensure only one generator is loaded
-
- def check_generator
- if @generator then
- raise OptionParser::InvalidOption,
- "generator already set to #{@generator_name}"
- end
- end
-
- ##
- # Set the title, but only if not already set. Used to set the title
- # from a source file, so that a title set from the command line
- # will have the priority.
-
- def default_title=(string)
- @title ||= string
- end
-
- ##
- # Completes any unfinished option setup business such as filtering for
- # existent files, creating a regexp for #exclude and setting a default
- # #template.
-
- def finish
- @op_dir ||= 'doc'
-
- @rdoc_include << "." if @rdoc_include.empty?
-
- if @exclude.nil? or Regexp === @exclude then
- # done, #finish is being re-run
- elsif @exclude.empty? then
- @exclude = nil
- else
- @exclude = Regexp.new(@exclude.join("|"))
- end
-
- check_files
-
- # If no template was specified, use the default template for the output
- # formatter
-
- unless @template then
- @template = @generator_name
- @template_dir = template_dir_for @template
- end
-
- self
- end
-
- ##
- # Returns a properly-space list of generators and their descriptions.
-
- def generator_descriptions
- lengths = []
-
- generators = RDoc::RDoc::GENERATORS.map do |name, generator|
- lengths << name.length
-
- description = generator::DESCRIPTION if
- generator.const_defined? :DESCRIPTION
-
- [name, description]
- end
-
- longest = lengths.max
-
- generators.sort.map do |name, description|
- if description then
- " %-*s - %s" % [longest, name, description]
- else
- " #{name}"
- end
- end.join "\n"
- end
-
- ##
- # Parses command line options.
-
- def parse(argv)
- ignore_invalid = true
-
- argv.insert(0, *ENV['RDOCOPT'].split) if ENV['RDOCOPT']
-
- opts = OptionParser.new do |opt|
- @option_parser = opt
- opt.program_name = File.basename $0
- opt.version = RDoc::VERSION
- opt.release = nil
- opt.summary_indent = ' ' * 4
- opt.banner = <<-EOF
-Usage: #{opt.program_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.
-
- How RDoc generates output depends on the output formatter being used, and on
- the options you give.
-
- Options can be specified via the RDOCOPT environment variable, which
- functions similar to the RUBYOPT environment variable for ruby.
-
- $ export RDOCOPT="--show-hash"
-
- will make rdoc show hashes in method links by default. Command-line options
- always will override those in RDOCOPT.
-
- Available formatters:
-
-#{generator_descriptions}
-
- RDoc understands the following file formats:
-
- EOF
-
- parsers = Hash.new { |h,parser| h[parser] = [] }
-
- RDoc::Parser.parsers.each do |regexp, parser|
- parsers[parser.name.sub('RDoc::Parser::', '')] << regexp.source
- end
-
- parsers.sort.each do |parser, regexp|
- opt.banner << " - #{parser}: #{regexp.join ', '}\n"
- end
-
- opt.banner << "\n The following options are deprecated:\n\n"
-
- name_length = DEPRECATED.keys.sort_by { |k| k.length }.last.length
-
- DEPRECATED.sort_by { |k,| k }.each do |name, reason|
- opt.banner << " %*1$2$s %3$s\n" % [-name_length, name, reason]
- end
-
- opt.accept Template do |template|
- template_dir = template_dir_for template
-
- unless template_dir then
- warn "could not find template #{template}"
- nil
- else
- [template, template_dir]
- end
- end
-
- opt.separator nil
- opt.separator "Parsing options:"
- opt.separator nil
-
- if Object.const_defined? :Encoding then
- opt.on("--encoding=ENCODING", "-e", Encoding.list.map { |e| e.name },
- "Specifies the output encoding. All files",
- "read will be converted to this encoding.",
- "Preferred over --charset") do |value|
- @encoding = Encoding.find value
- @charset = @encoding.to_s # may not be valid value
- end
-
- opt.separator nil
- end
-
- opt.on("--all", "-a",
- "Synonym for --visibility=private.") do |value|
- @visibility = :private
- end
-
- opt.separator nil
-
- opt.on("--exclude=PATTERN", "-x", Regexp,
- "Do not process files or directories",
- "matching PATTERN.") do |value|
- @exclude << value
- end
-
- opt.separator nil
-
- opt.on("--extension=NEW=OLD", "-E",
- "Treat files ending with .new as if they",
- "ended with .old. Using '-E cgi=rb' will",
- "cause xxx.cgi to be parsed as a Ruby file.") do |value|
- new, old = value.split(/=/, 2)
-
- unless new and old then
- raise OptionParser::InvalidArgument, "Invalid parameter to '-E'"
- end
-
- unless RDoc::Parser.alias_extension old, new then
- raise OptionParser::InvalidArgument, "Unknown extension .#{old} to -E"
- end
- end
-
- opt.separator nil
-
- opt.on("--[no-]force-update", "-U",
- "Forces rdoc to scan all sources even if",
- "newer than the flag file.") do |value|
- @force_update = value
- end
-
- opt.separator nil
-
- opt.on("--pipe",
- "Convert RDoc on stdin to HTML") do
- @pipe = true
- end
-
- opt.separator nil
-
- opt.on("--tab-width=WIDTH", "-w", OptionParser::DecimalInteger,
- "Set the width of tab characters.") do |value|
- @tab_width = value
- end
-
- opt.separator nil
-
- opt.on("--visibility=VISIBILITY", "-V", RDoc::VISIBILITIES,
- "Minimum visibility to document a method.",
- "One of 'public', 'protected' (the default)",
- "or 'private'. Can be abbreviated.") do |value|
- @visibility = value
- end
-
- opt.separator nil
- opt.separator "Common generator options:"
- opt.separator nil
-
- opt.on("--force-output", "-O",
- "Forces rdoc to write the output files,",
- "even if the output directory exists",
- "and does not seem to have been created",
- "by rdoc.") do |value|
- @force_output = value
- end
-
- opt.separator nil
-
- generator_text = @generators.keys.map { |name| " #{name}" }.sort
-
- opt.on("-f", "--fmt=FORMAT", "--format=FORMAT", @generators.keys,
- "Set the output formatter. One of:", *generator_text) do |value|
- check_generator
-
- @generator_name = value.downcase
- setup_generator
- end
-
- opt.separator nil
-
- opt.on("--include=DIRECTORIES", "-i", Array,
- "Set (or add to) the list of directories to",
- "be searched when satisfying :include:",
- "requests. Can be used more than once.") do |value|
- @rdoc_include.concat value.map { |dir| dir.strip }
- end
-
- opt.separator nil
-
- opt.on("--[no-]coverage-report=[LEVEL]", "--[no-]dcov", "-C", Integer,
- "Prints a report on undocumented items.",
- "Does not generate files.") do |value|
- value = 0 if value.nil? # Integer converts -C to nil
-
- @coverage_report = value
- @force_update = true if value
- end
-
- opt.separator nil
-
- opt.on("--output=DIR", "--op", "-o",
- "Set the output directory.") do |value|
- @op_dir = value
- end
-
- opt.separator nil
-
- opt.on("-d",
- "Deprecated --diagram option.",
- "Prevents firing debug mode",
- "with legacy invocation.") do |value|
- end
-
- opt.separator nil
- opt.separator 'HTML generator options:'
- opt.separator nil
-
- opt.on("--charset=CHARSET", "-c",
- "Specifies the output HTML character-set.",
- "Use --encoding instead of --charset if",
- "available.") do |value|
- @charset = value
- end
-
- opt.separator nil
-
- opt.on("--hyperlink-all", "-A",
- "Generate hyperlinks for all words that",
- "correspond to known methods, even if they",
- "do not start with '#' or '::' (legacy",
- "behavior).") do |value|
- @hyperlink_all = value
- end
-
- opt.separator nil
-
- opt.on("--main=NAME", "-m",
- "NAME will be the initial page displayed.") do |value|
- @main_page = value
- end
-
- opt.separator nil
-
- opt.on("--[no-]line-numbers", "-N",
- "Include line numbers in the source code.",
- "By default, only the number of the first",
- "line is displayed, in a leading comment.") do |value|
- @line_numbers = value
- end
-
- opt.separator nil
-
- opt.on("--show-hash", "-H",
- "A name of the form #name in a comment is a",
- "possible hyperlink to an instance method",
- "name. When displayed, the '#' is removed",
- "unless this option is specified.") do |value|
- @show_hash = value
- end
-
- opt.separator nil
-
- opt.on("--template=NAME", "-T", Template,
- "Set the template used when generating",
- "output. The default depends on the",
- "formatter used.") do |(template, template_dir)|
- @template = template
- @template_dir = template_dir
- end
-
- opt.separator nil
-
- opt.on("--title=TITLE", "-t",
- "Set TITLE as the title for HTML output.") do |value|
- @title = value
- end
-
- opt.separator nil
-
- opt.on("--webcvs=URL", "-W",
- "Specify a URL for linking to a web frontend",
- "to CVS. If the URL contains a '\%s', the",
- "name of the current file will be",
- "substituted; if the URL doesn't contain a",
- "'\%s', the filename will be appended to it.") do |value|
- @webcvs = value
- end
-
- opt.separator nil
- opt.separator "ri generator options:"
- opt.separator nil
-
- opt.on("--ri", "-r",
- "Generate output for use by `ri`. The files",
- "are stored in the '.rdoc' directory under",
- "your home directory unless overridden by a",
- "subsequent --op parameter, so no special",
- "privileges are needed.") do |value|
- check_generator
-
- @generator_name = "ri"
- @op_dir ||= RDoc::RI::Paths::HOMEDIR
- setup_generator
- end
-
- opt.separator nil
-
- opt.on("--ri-site", "-R",
- "Generate output for use by `ri`. The files",
- "are stored in a site-wide directory,",
- "making them accessible to others, so",
- "special privileges are needed.") do |value|
- check_generator
-
- @generator_name = "ri"
- @op_dir = RDoc::RI::Paths::SITEDIR
- setup_generator
- end
-
- opt.separator nil
- opt.separator "Generic options:"
- opt.separator nil
-
- opt.on("--[no-]dry-run",
- "Don't write any files") do |value|
- @dry_run = value
- end
-
- opt.on("-D", "--[no-]debug",
- "Displays lots on internal stuff.") do |value|
- $DEBUG_RDOC = value
- end
-
- opt.on("--[no-]ignore-invalid",
- "Ignore invalid options and continue",
- "(default true).") do |value|
- ignore_invalid = value
- end
-
- opt.on("--quiet", "-q",
- "Don't show progress as we parse.") do |value|
- @verbosity = 0
- end
-
- opt.on("--verbose", "-v",
- "Display extra progress as RDoc parses") do |value|
- @verbosity = 2
- end
-
- opt.on("--help",
- "Display this help") do
- RDoc::RDoc::GENERATORS.each_key do |generator|
- setup_generator generator
- end
-
- puts opt.help
- exit
- end
-
- opt.separator nil
- end
-
- setup_generator 'darkfish' if
- argv.grep(/\A(-f|--fmt|--format|-r|-R|--ri|--ri-site)\b/).empty?
-
- deprecated = []
- invalid = []
-
- begin
- opts.parse! argv
- rescue OptionParser::InvalidArgument, OptionParser::InvalidOption => e
- if DEPRECATED[e.args.first] then
- deprecated << e.args.first
- elsif %w[--format --ri -r --ri-site -R].include? e.args.first then
- raise
- else
- invalid << e.args.join(' ')
- end
-
- retry
- end
-
- unless @generator then
- @generator = RDoc::Generator::Darkfish
- @generator_name = 'darkfish'
- end
-
- if @pipe and not argv.empty? then
- @pipe = false
- invalid << '-p (with files)'
- end
-
- unless quiet then
- deprecated.each do |opt|
- $stderr.puts 'option ' << opt << ' is deprecated: ' << DEPRECATED[opt]
- end
-
- unless invalid.empty? then
- invalid = "invalid options: #{invalid.join ', '}"
-
- if ignore_invalid then
- $stderr.puts invalid
- $stderr.puts '(invalid options are ignored)'
- else
- $stderr.puts opts
- $stderr.puts invalid
- exit 1
- end
- end
- end
-
- @files = argv.dup
-
- finish
- end
-
- ##
- # Don't display progress as we process the files
-
- def quiet
- @verbosity.zero?
- end
-
- ##
- # Set quietness to +bool+
-
- def quiet= bool
- @verbosity = bool ? 0 : 1
- end
-
- ##
- # Set up an output generator for the named +generator_name+.
- #
- # If the found generator responds to :setup_options it will be called with
- # the options instance. This allows generators to add custom options or set
- # default options.
-
- def setup_generator generator_name = @generator_name
- @generator = @generators[generator_name]
-
- unless @generator then
- raise OptionParser::InvalidArgument,
- "Invalid output formatter #{generator_name}"
- end
-
- return if @generator_options.include? @generator
-
- @generator_name = generator_name
- @generator_options << @generator
-
- if @generator.respond_to? :setup_options then
- @option_parser ||= OptionParser.new
- @generator.setup_options self
- end
- end
-
- ##
- # Finds the template dir for +template+
-
- def template_dir_for template
- template_path = File.join 'rdoc', 'generator', 'template', template
-
- $LOAD_PATH.map do |path|
- File.join File.expand_path(path), template_path
- end.find do |dir|
- File.directory? dir
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/parser.rb b/ruby_1_9_3/lib/rdoc/parser.rb
deleted file mode 100644
index 27267f3d81..0000000000
--- a/ruby_1_9_3/lib/rdoc/parser.rb
+++ /dev/null
@@ -1,208 +0,0 @@
-require 'rdoc'
-require 'rdoc/code_objects'
-require 'rdoc/markup/pre_process'
-require 'rdoc/stats'
-
-##
-# A parser is a class that subclasses RDoc::Parser and implements
-#
-# #initialize top_level, file_name, body, options, stats
-#
-# 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.
-#
-# RDoc::Parser::for is a factory that creates the correct parser for a
-# given filename extension. Parsers have to register themselves RDoc::Parser
-# using parse_files_matching as when they are loaded:
-#
-# require "rdoc/parser"
-#
-# class RDoc::Parser::Xyz < RDoc::Parser
-# parse_files_matching /\.xyz$/ # <<<<
-#
-# def initialize top_level, file_name, body, options, stats
-# ...
-# end
-#
-# def scan
-# ...
-# end
-# end
-#
-# If a plain text file is detected, RDoc also looks for a shebang line in case
-# the file is a shell script.
-
-class RDoc::Parser
-
- @parsers = []
-
- class << self
-
- ##
- # An Array of arrays that maps file extension (or name) regular
- # expressions to parser classes that will parse matching filenames.
- #
- # Use parse_files_matching to register a parser's file extensions.
-
- attr_reader :parsers
-
- 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 self.alias_extension(old_ext, new_ext)
- old_ext = old_ext.sub(/^\.(.*)/, '\1')
- new_ext = new_ext.sub(/^\.(.*)/, '\1')
-
- parser = can_parse "xxx.#{old_ext}"
- return false unless parser
-
- RDoc::Parser.parsers.unshift [/\.#{new_ext}$/, parser]
-
- true
- end
-
- ##
- # Determines if the file is a "binary" file which basically means it has
- # content that an RDoc parser shouldn't try to consume.
-
- def self.binary?(file)
- return false if file =~ /\.(rdoc|txt)$/
-
- s = File.read(file, 1024) or return false
-
- have_encoding = s.respond_to? :encoding
-
- if have_encoding then
- return false if s.encoding != Encoding::ASCII_8BIT and s.valid_encoding?
- end
-
- return true if s[0, 2] == Marshal.dump('')[0, 2] or s.index("\x00")
-
- if have_encoding then
- s.force_encoding Encoding.default_external
-
- not s.valid_encoding?
- else
- if 0.respond_to? :fdiv then
- s.count("\x00-\x7F", "^ -~\t\r\n").fdiv(s.size) > 0.3
- else # HACK 1.8.6
- (s.count("\x00-\x7F", "^ -~\t\r\n").to_f / s.size) > 0.3
- end
- end
- end
-
- ##
- # Processes common directives for CodeObjects for the C and Ruby parsers.
- #
- # Applies +directive+'s +value+ to +code_object+, if appropriate
-
- def self.process_directive code_object, directive, value
- warn "RDoc::Parser::process_directive is deprecated and wil be removed in RDoc 4. Use RDoc::Markup::PreProcess#handle_directive instead" if $-w
-
- case directive
- when 'nodoc' then
- code_object.document_self = nil # notify nodoc
- code_object.document_children = value.downcase != 'all'
- when 'doc' then
- code_object.document_self = true
- code_object.force_documentation = true
- when 'yield', 'yields' then
- # remove parameter &block
- code_object.params.sub!(/,?\s*&\w+/, '') if code_object.params
-
- code_object.block_params = value
- when 'arg', 'args' then
- code_object.params = value
- end
- end
-
- ##
- # Checks if +file+ is a zip file in disguise. Signatures from
- # http://www.garykessler.net/library/file_sigs.html
-
- def self.zip? file
- zip_signature = File.read file, 4
-
- zip_signature == "PK\x03\x04" or
- zip_signature == "PK\x05\x06" or
- zip_signature == "PK\x07\x08"
- end
-
- ##
- # Return a parser that can handle a particular extension
-
- def self.can_parse(file_name)
- parser = RDoc::Parser.parsers.find { |regexp,| regexp =~ file_name }.last
-
- # HACK Selenium hides a jar file using a .txt extension
- return if parser == RDoc::Parser::Simple and zip? file_name
-
- # The default parser must not parse binary files
- ext_name = File.extname file_name
- return parser if ext_name.empty?
- return if parser == RDoc::Parser::Simple and ext_name !~ /txt|rdoc/
-
- parser
- end
-
- ##
- # Find the correct parser for a particular file name. Return a SimpleParser
- # for ones that we don't know
-
- def self.for(top_level, file_name, body, options, stats)
- return if binary? file_name
-
- # If no extension, look for shebang
- if file_name !~ /\.\w+$/ && body =~ %r{\A#!(.+)} then
- shebang = $1
- case shebang
- when %r{env\s+ruby}, %r{/ruby}
- file_name = "dummy.rb"
- end
- end
-
- parser = can_parse file_name
-
- return unless parser
-
- parser.new top_level, file_name, body, options, stats
- end
-
- ##
- # Record which file types this parser can understand.
- #
- # It is ok to call this multiple times.
-
- def self.parse_files_matching(regexp)
- RDoc::Parser.parsers.unshift [regexp, self]
- end
-
- ##
- # Creates a new Parser storing +top_level+, +file_name+, +content+,
- # +options+ and +stats+ in instance variables.
- #
- # Usually invoked by +super+
-
- def initialize(top_level, file_name, content, options, stats)
- @top_level = top_level
- @file_name = file_name
- @content = content
- @options = options
- @stats = stats
-
- @preprocess = RDoc::Markup::PreProcess.new @file_name, @options.rdoc_include
- @preprocess.options = @options
- end
-
-end
-
-require 'rdoc/parser/simple'
-
diff --git a/ruby_1_9_3/lib/rdoc/parser/c.rb b/ruby_1_9_3/lib/rdoc/parser/c.rb
deleted file mode 100644
index 3da1820c50..0000000000
--- a/ruby_1_9_3/lib/rdoc/parser/c.rb
+++ /dev/null
@@ -1,1047 +0,0 @@
-
-require 'rdoc/parser/ruby'
-require 'rdoc/known_classes'
-
-##
-# RDoc::Parser::C attempts to parse C extension files. It looks for
-# the standard patterns that you find in extensions: <tt>rb_define_class,
-# rb_define_method</tt> and so on. It tries 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.
-#
-# The comment blocks may include special directives:
-#
-# [Document-class: +name+]
-# Documentation for the named class.
-#
-# [Document-module: +name+]
-# Documentation for the named module.
-#
-# [Document-const: +name+]
-# Documentation for the named +rb_define_const+.
-#
-# [Document-global: +name+]
-# Documentation for the named +rb_define_global_const+
-#
-# [Document-variable: +name+]
-# Documentation for the named +rb_define_variable+
-#
-# [Document-method: +method_name+]
-# Documentation for the named method. Use this when the method name is
-# unambiguous.
-#
-# [Document-method: <tt>ClassName::method_name<tt>]
-# Documentation for a singleton method in the given class. Use this when
-# the method name alone is ambiguous.
-#
-# [Document-method: <tt>ClassName#method_name<tt>]
-# Documentation for a instance method in the given class. Use this when the
-# method name alone is ambiguous.
-#
-# [Document-attr: +name+]
-# Documentation for the named attribute.
-#
-# [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 RDoc::Parser::C < RDoc::Parser
-
- parse_files_matching(/\.(?:([CcHh])\1?|c([+xp])\2|y)\z/)
-
- include RDoc::Text
-
- ##
- # C file the parser is parsing
-
- attr_accessor :content
-
-
- ##
- # Maps C variable names to names of ruby classes (andsingleton classes)
-
- attr_reader :known_classes
-
- ##
- # Maps C variable names to names of ruby singleton classes
-
- attr_reader :singleton_classes
-
- ##
- # Resets cross-file state. Call when parsing different projects that need
- # separate documentation.
-
- def self.reset
- @@enclosure_classes = {}
- @@known_bodies = {}
- end
-
- reset
-
- ##
- # Prepare to parse a C file
-
- def initialize(top_level, file_name, content, options, stats)
- super
-
- @known_classes = RDoc::KNOWN_CLASSES.dup
- @content = handle_tab_width handle_ifdefs_in(@content)
- @classes = {}
- @singleton_classes = {}
- @file_dir = File.dirname(@file_name)
- end
-
- ##
- # Scans #content for rb_define_alias
-
- def do_aliases
- @content.scan(/rb_define_alias\s*\(
- \s*(\w+),
- \s*"(.+?)",
- \s*"(.+?)"
- \s*\)/xm) do |var_name, new_name, old_name|
- class_name = @known_classes[var_name]
-
- unless class_name then
- warn "Enclosing class/module %p for alias %s %s not known" % [
- var_name, new_name, old_name]
- next
- end
-
- class_obj = find_class var_name, class_name
-
- al = RDoc::Alias.new '', old_name, new_name, ''
- al.singleton = @singleton_classes.key? var_name
-
- comment = find_alias_comment var_name, new_name, old_name
- comment = strip_stars comment
- al.comment = comment
-
- al.record_location @top_level
-
- class_obj.add_alias al
- @stats.add_alias al
- end
- end
-
- ##
- # Scans #content for rb_attr and rb_define_attr
-
- def do_attrs
- @content.scan(/rb_attr\s*\(
- \s*(\w+),
- \s*([\w"()]+),
- \s*([01]),
- \s*([01]),
- \s*\w+\);/xm) do |var_name, attr_name, read, write|
- handle_attr var_name, attr_name, read, write
- end
-
- @content.scan(%r%rb_define_attr\(
- \s*([\w\.]+),
- \s*"([^"]+)",
- \s*(\d+),
- \s*(\d+)\s*\);
- %xm) do |var_name, attr_name, read, write|
- handle_attr var_name, attr_name, read, write
- end
- end
-
- ##
- # Scans #content for rb_define_module, rb_define_class, boot_defclass,
- # rb_define_module_under, rb_define_class_under and rb_singleton_class
-
- def do_classes
- @content.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
- @content.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
-
- @content.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
-
- @content.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
-
- @content.scan(/([\w\.]+)\s* = # var_name
- \s*rb_define_class_under\s*
- \(
- \s* (\w+), # under
- \s* "(\w+)", # class_name
- \s*
- (?:
- ([\w\*\s\(\)\.\->]+) | # parent_name
- rb_path2class\("([\w:]+)"\) # path
- )
- \s*
- \)
- /mx) do |var_name, under, class_name, parent_name, path|
- parent = path || parent_name
-
- handle_class_module var_name, 'class', class_name, parent, under
- end
-
- @content.scan(/([\w\.]+)\s* = \s*rb_singleton_class\s*
- \(
- \s*(\w+)
- \s*\)/mx) do |sclass_var, class_var|
- handle_singleton sclass_var, class_var
- end
- end
-
- ##
- # Scans #content for rb_define_variable, rb_define_readonly_variable,
- # rb_define_const and rb_define_global_const
-
- def do_constants
- @content.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
-
- @content.scan(%r%
- \Wrb_curses_define_const
- \s*\(
- \s*
- (\w+)
- \s*
- \)
- \s*;%xm) do |consts|
- const = consts.first
- handle_constants 'const', 'mCurses', const, "UINT2NUM(#{const})"
- end
- end
-
- ##
- # Scans #content for rb_include_module
-
- def do_includes
- @content.scan(/rb_include_module\s*\(\s*(\w+?),\s*(\w+?)\s*\)/) do |c,m|
- if cls = @classes[c]
- m = @known_classes[m] || m
- incl = cls.add_include RDoc::Include.new(m, "")
- incl.record_location @top_level
- end
- end
- end
-
- ##
- # Scans #content for rb_define_method, rb_define_singleton_method,
- # rb_define_module_function, rb_define_private_method,
- # rb_define_global_function and define_filetest_function
-
- def do_methods
- @content.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+?\.(?:cpp|c|y)))?
- %xm) do |type, var_name, meth_name, function, 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"
-
- var_name = "rb_cObject" if var_name == "rb_mKernel"
- handle_method(type, var_name, meth_name, function, param_count,
- source_file)
- end
-
- @content.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, function, param_count, source_file|
- handle_method("method", "rb_mKernel", meth_name, function, param_count,
- source_file)
- end
-
- @content.scan(/define_filetest_function\s*\(
- \s*"([^"]+)",
- \s*(?:RUBY_METHOD_FUNC\(|VALUEFUNC\()?(\w+)\)?,
- \s*(-?\w+)\s*\)/xm) do |meth_name, function, param_count|
-
- handle_method("method", "rb_mFileTest", meth_name, function, param_count)
- handle_method("singleton_method", "rb_cFile", meth_name, function,
- param_count)
- end
- end
-
- ##
- # Finds the comment for an alias on +class_name+ from +new_name+ to
- # +old_name+
-
- def find_alias_comment class_name, new_name, old_name
- content =~ %r%((?>/\*.*?\*/\s+))
- rb_define_alias\(\s*#{Regexp.escape class_name}\s*,
- \s*"#{Regexp.escape new_name}"\s*,
- \s*"#{Regexp.escape old_name}"\s*\);%xm
-
- $1 || ''
- end
-
- ##
- # Finds a comment for rb_define_attr, rb_attr or Document-attr.
- #
- # +var_name+ is the C class variable the attribute is defined on.
- # +attr_name+ is the attribute's name.
- #
- # +read+ and +write+ are the read/write flags ('1' or '0'). Either both or
- # neither must be provided.
-
- def find_attr_comment var_name, attr_name, read = nil, write = nil
- attr_name = Regexp.escape attr_name
-
- rw = if read and write then
- /\s*#{read}\s*,\s*#{write}\s*/xm
- else
- /.*?/m
- end
-
- if @content =~ %r%((?>/\*.*?\*/\s+))
- rb_define_attr\((?:\s*#{var_name},)?\s*
- "#{attr_name}"\s*,
- #{rw}\)\s*;%xm then
- $1
- elsif @content =~ %r%((?>/\*.*?\*/\s+))
- rb_attr\(\s*#{var_name}\s*,
- \s*#{attr_name}\s*,
- #{rw},.*?\)\s*;%xm then
- $1
- elsif @content =~ %r%Document-attr:\s#{attr_name}\s*?\n
- ((?>.*?\*/))%xm then
- $1
- else
- ''
- end
- end
-
- ##
- # Find the C code corresponding to a Ruby method
-
- def find_body class_name, meth_name, meth_obj, file_content, quiet = false
- case file_content
- when %r%((?>/\*.*?\*/\s*)?)
- ((?:(?:static|SWIGINTERN)\s+)?
- (?:intern\s+)?VALUE\s+#{meth_name}
- \s*(\([^)]*\))([^;]|$))%xm then
- comment = $1
- body = $2
- offset = $~.offset(2).first
-
- remove_private_comments comment if comment
-
- # try to find the whole body
- body = $& if /#{Regexp.escape body}[^(]*?\{.*?^\}/m =~ file_content
-
- # 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 class_name, meth_obj
- comment = override_comment if override_comment
-
- find_modifiers comment, meth_obj if comment
-
- #meth_obj.params = params
- meth_obj.start_collecting_tokens
- tk = RDoc::RubyToken::Token.new nil, 1, 1
- tk.set_text body
- meth_obj.add_token tk
- meth_obj.comment = strip_stars comment
- meth_obj.offset = offset
- meth_obj.line = file_content[0, offset].count("\n") + 1
-
- body
- when %r%((?>/\*.*?\*/\s*))^\s*(\#\s*define\s+#{meth_name}\s+(\w+))%m then
- comment = $1
- body = $2
- offset = $~.offset(2).first
-
- find_body class_name, $3, meth_obj, file_content, true
- find_modifiers comment, meth_obj
-
- meth_obj.start_collecting_tokens
- tk = RDoc::RubyToken::Token.new nil, 1, 1
- tk.set_text body
- meth_obj.add_token tk
- meth_obj.comment = strip_stars(comment) + meth_obj.comment.to_s
- meth_obj.offset = offset
- meth_obj.line = file_content[0, offset].count("\n") + 1
-
- body
- when %r%^\s*\#\s*define\s+#{meth_name}\s+(\w+)%m then
- # with no comment we hope the aliased definition has it and use it's
- # definition
-
- body = find_body(class_name, $1, meth_obj, file_content, true)
-
- return body if body
-
- warn "No definition for #{meth_name}" if @options.verbosity > 1
- false
- else # No body, but might still have an override comment
- comment = find_override_comment class_name, meth_obj
-
- if comment then
- find_modifiers comment, meth_obj
- meth_obj.comment = strip_stars comment
-
- ''
- else
- warn "No definition for #{meth_name}" if @options.verbosity > 1
- false
- end
- end
- end
-
- ##
- # Finds a RDoc::NormalClass or RDoc::NormalModule for +raw_name+
-
- def find_class(raw_name, name)
- unless @classes[raw_name]
- if raw_name =~ /^rb_m/
- container = @top_level.add_module RDoc::NormalModule, name
- else
- container = @top_level.add_class RDoc::NormalClass, name
- end
-
- container.record_location @top_level
- @classes[raw_name] = container
- end
- @classes[raw_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_mod)
- comment = nil
-
- if @content =~ %r%
- ((?>/\*.*?\*/\s+))
- (static\s+)?
- void\s+
- Init_#{class_name}\s*(?:_\(\s*)?\(\s*(?:void\s*)?\)%xmi then
- comment = $1.sub(%r%Document-(?:class|module):\s+#{class_name}%, '')
- elsif @content =~ %r%Document-(?:class|module):\s+#{class_name}\s*?
- (?:<\s+[:,\w]+)?\n((?>.*?\*/))%xm then
- comment = $1
- elsif @content =~ %r%((?>/\*.*?\*/\s+))
- ([\w\.\s]+\s* = \s+)?rb_define_(class|module).*?"(#{class_name})"%xm then
- comment = $1
- end
-
- return unless comment
-
- comment = strip_stars comment
-
- comment = look_for_directives_in class_mod, comment
-
- class_mod.add_comment comment, @top_level
- 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, class_name = nil)
- if @content =~ %r%((?>^\s*/\*.*?\*/\s+))
- rb_define_#{type}\((?:\s*(\w+),)?\s*
- "#{const_name}"\s*,
- .*?\)\s*;%xmi then
- $1
- elsif class_name and
- @content =~ %r%Document-(?:const|global|variable):\s
- #{class_name}::#{const_name}
- \s*?\n((?>.*?\*/))%xm then
- $1
- elsif @content =~ %r%Document-(?:const|global|variable):\s#{const_name}
- \s*?\n((?>.*?\*/))%xm then
- $1
- else
- ''
- end
- end
-
- ##
- # Handles modifiers in +comment+ and updates +meth_obj+ as appropriate.
- #
- # If <tt>:nodoc:</tt> is found, documentation on +meth_obj+ is suppressed.
- #
- # If <tt>:yields:</tt> is followed by an argument list it is used for the
- # #block_params of +meth_obj+.
- #
- # If the comment block contains a <tt>call-seq:</tt> section like:
- #
- # call-seq:
- # ARGF.readlines(sep=$/) -> array
- # ARGF.readlines(limit) -> array
- # ARGF.readlines(sep, limit) -> array
- #
- # ARGF.to_a(sep=$/) -> array
- # ARGF.to_a(limit) -> array
- # ARGF.to_a(sep, limit) -> array
- #
- # it is used for the parameters of +meth_obj+.
-
- def find_modifiers comment, meth_obj
- # we must handle situations like the above followed by an unindented first
- # comment. The difficulty is to make sure not to match lines starting
- # with ARGF at the same indent, but that are after the first description
- # paragraph.
-
- if comment =~ /call-seq:(.*?(?:\S|\*\/?).*?)^\s*(?:\*\/?)?\s*$/m then
- all_start, all_stop = $~.offset(0)
- seq_start, seq_stop = $~.offset(1)
-
- # we get the following lines that start with the leading word at the
- # same indent, even if they have blank lines before
- if $1 =~ /(^\s*\*?\s*\n)+^(\s*\*?\s*\w+)/m then
- leading = $2 # ' * ARGF' in the example above
- re = %r%
- \A(
- (^\s*\*?\s*\n)+
- (^#{Regexp.escape leading}.*?\n)+
- )+
- ^\s*\*?\s*$
- %xm
- if comment[seq_stop..-1] =~ re then
- all_stop = seq_stop + $~.offset(0).last
- seq_stop = seq_stop + $~.offset(1).last
- end
- end
-
- seq = comment[seq_start..seq_stop]
- seq.gsub!(/^(\s*\*?\s*?)(\S|\n)/m, '\2')
- comment.slice! all_start...all_stop
- meth_obj.call_seq = seq
- elsif comment.sub!(/\A\/\*\s*call-seq:(.*?)\*\/\Z/, '') then
- meth_obj.call_seq = $1.strip
- end
-
- look_for_directives_in meth_obj, comment
- end
-
- ##
- # Finds a <tt>Document-method</tt> override for +meth_obj+ on +class_name+
-
- def find_override_comment class_name, meth_obj
- name = Regexp.escape meth_obj.name
- prefix = Regexp.escape meth_obj.name_prefix
-
- if @content =~ %r%Document-method:\s+#{class_name}#{prefix}#{name}\s*?\n((?>.*?\*/))%m then
- $1
- elsif @content =~ %r%Document-method:\s#{name}\s*?\n((?>.*?\*/))%m then
- $1
- end
- end
-
- ##
- # Creates a new RDoc::Attr +attr_name+ on class +var_name+ that is either
- # +read+, +write+ or both
-
- def handle_attr(var_name, attr_name, read, write)
- rw = ''
- rw << 'R' if '1' == read
- rw << 'W' if '1' == write
-
- class_name = @known_classes[var_name]
-
- return unless class_name
-
- class_obj = find_class var_name, class_name
-
- return unless class_obj
-
- comment = find_attr_comment var_name, attr_name
- comment = strip_stars comment
-
- name = attr_name.gsub(/rb_intern\("([^"]+)"\)/, '\1')
-
- attr = RDoc::Attr.new '', name, rw, comment
-
- attr.record_location @top_level
- class_obj.add_attribute attr
- @stats.add_attribute attr
- end
-
- ##
- # Creates a new RDoc::NormalClass or RDoc::NormalModule based on +type+
- # named +class_name+ in +parent+ which was assigned to the C +var_name+.
-
- def handle_class_module(var_name, type, class_name, parent, in_module)
- parent_name = @known_classes[parent] || parent
-
- if in_module then
- enclosure = @classes[in_module] || @@enclosure_classes[in_module]
-
- if enclosure.nil? and enclosure = @known_classes[in_module] then
- enc_type = /^rb_m/ =~ in_module ? "module" : "class"
- handle_class_module in_module, enc_type, enclosure, nil, nil
- enclosure = @classes[in_module]
- end
-
- unless enclosure then
- warn "Enclosing class/module '#{in_module}' for #{type} #{class_name} not known"
- return
- end
- else
- enclosure = @top_level
- end
-
- if type == "class" then
- full_name = if RDoc::ClassModule === enclosure then
- enclosure.full_name + "::#{class_name}"
- else
- class_name
- end
-
- if @content =~ %r%Document-class:\s+#{full_name}\s*<\s+([:,\w]+)% then
- parent_name = $1
- end
-
- cm = enclosure.add_class RDoc::NormalClass, class_name, parent_name
- else
- cm = enclosure.add_module RDoc::NormalModule, class_name
- end
-
- cm.record_location enclosure.top_level
-
- find_class_comment cm.full_name, cm
-
- case cm
- when RDoc::NormalClass
- @stats.add_class cm
- when RDoc::NormalModule
- @stats.add_module cm
- end
-
- @classes[var_name] = cm
- @@enclosure_classes[var_name] = cm
- @known_classes[var_name] = cm.full_name
- end
-
- ##
- # Adds constants. By providing some_value: at the start of the 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 <tt>INT2FIX(300)</tt> with the value +300+ in the output
- # RDoc. Values may include quotes and escaped colons (\:).
-
- def handle_constants(type, var_name, const_name, definition)
- class_name = @known_classes[var_name]
-
- return unless class_name
-
- class_obj = find_class var_name, class_name
-
- unless class_obj then
- warn "Enclosing class/module #{const_name.inspect} not known"
- return
- end
-
- comment = find_const_comment type, const_name, class_name
- comment = strip_stars comment
- comment = normalize_comment comment
-
- # 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 = comment.split ':'
-
- if elements.nil? or elements.empty? then
- con = RDoc::Constant.new const_name, definition, 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 = if $1.nil? then
- elements.last.lstrip
- else
- "#{$1}#{elements.last.lstrip}"
- end
-
- con = RDoc::Constant.new const_name, new_definition, new_comment
- end
- else
- con = RDoc::Constant.new const_name, definition, comment
- end
-
- con.record_location @top_level
- @stats.add_constant con
- class_obj.add_constant con
- 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
-
- ##
- # Adds an RDoc::AnyMethod +meth_name+ defined on a class or module assigned
- # to +var_name+. +type+ is the type of method definition function used.
- # +singleton_method+ and +module_function+ create a singleton method.
-
- def handle_method(type, var_name, meth_name, function, param_count,
- source_file = nil)
- class_name = @known_classes[var_name]
- singleton = @singleton_classes.key? var_name
-
- return unless class_name
-
- class_obj = find_class var_name, class_name
-
- if class_obj then
- if meth_name == 'initialize' then
- meth_name = 'new'
- singleton = true
- type = 'method' # force public
- end
-
- meth_obj = RDoc::AnyMethod.new '', meth_name
- meth_obj.c_function = function
- meth_obj.singleton =
- singleton || %w[singleton_method module_function].include?(type)
-
- p_count = Integer(param_count) rescue -1
-
- if source_file then
- file_name = File.join @file_dir, source_file
-
- if File.exist? file_name then
- file_content = (@@known_bodies[file_name] ||= File.read(file_name))
- else
- warn "unknown source #{source_file} for #{meth_name} in #{@file_name}"
- end
- else
- file_content = @content
- end
-
- body = find_body class_name, function, meth_obj, file_content
-
- if body and meth_obj.document_self then
- meth_obj.params = if p_count < -1 then # -2 is Array
- '(*args)'
- elsif p_count == -1 then # argc, argv
- rb_scan_args body
- else
- "(#{(1..p_count).map { |i| "p#{i}" }.join ', '})"
- end
-
-
- meth_obj.record_location @top_level
- class_obj.add_method meth_obj
- @stats.add_method meth_obj
- meth_obj.visibility = :private if 'private_method' == type
- end
- end
- end
-
- ##
- # Registers a singleton class +sclass_var+ as a singleton of +class_var+
-
- def handle_singleton sclass_var, class_var
- class_name = @known_classes[class_var]
-
- @known_classes[sclass_var] = class_name
- @singleton_classes[sclass_var] = class_name
- end
-
- ##
- # Normalizes tabs in +body+
-
- def handle_tab_width(body)
- if /\t/ =~ body
- tab_width = @options.tab_width
- body.split(/\n/).map do |line|
- 1 while line.gsub!(/\t+/) do
- ' ' * (tab_width * $&.length - $`.length % tab_width)
- end && $~
- line
- end.join "\n"
- else
- body
- end
- end
-
- ##
- # Look for directives in a normal comment block:
- #
- # /*
- # * :title: My Awesome Project
- # */
- #
- # This method modifies the +comment+
-
- def look_for_directives_in context, comment
- @preprocess.handle comment, context do |directive, param|
- case directive
- when 'main' then
- @options.main_page = param
- ''
- when 'title' then
- @options.default_title = param if @options.respond_to? :default_title=
- ''
- end
- end
-
- comment
- end
-
- ##
- # Extracts parameters from the +method_body+ and returns a method
- # parameter string. Follows 1.9.3dev's scan-arg-spec, see README.EXT
-
- def rb_scan_args method_body
- method_body =~ /rb_scan_args\((.*?)\)/m
- return '(*args)' unless $1
-
- $1.split(/,/)[2] =~ /"(.*?)"/ # format argument
- format = $1.split(//)
-
- lead = opt = trail = 0
-
- if format.first =~ /\d/ then
- lead = $&.to_i
- format.shift
- if format.first =~ /\d/ then
- opt = $&.to_i
- format.shift
- if format.first =~ /\d/ then
- trail = $&.to_i
- format.shift
- block_arg = true
- end
- end
- end
-
- if format.first == '*' and not block_arg then
- var = true
- format.shift
- if format.first =~ /\d/ then
- trail = $&.to_i
- format.shift
- end
- end
-
- if format.first == ':' then
- hash = true
- format.shift
- end
-
- if format.first == '&' then
- block = true
- format.shift
- end
-
- # if the format string is not empty there's a bug in the C code, ignore it
-
- args = []
- position = 1
-
- (1...(position + lead)).each do |index|
- args << "p#{index}"
- end
-
- position += lead
-
- (position...(position + opt)).each do |index|
- args << "p#{index} = v#{index}"
- end
-
- position += opt
-
- if var then
- args << '*args'
- position += 1
- end
-
- (position...(position + trail)).each do |index|
- args << "p#{index}"
- end
-
- position += trail
-
- if hash then
- args << "p#{position} = {}"
- position += 1
- end
-
- args << '&block' if block
-
- "(#{args.join ', '})"
- end
-
- ##
- # Removes lines that are commented out that might otherwise get picked up
- # when scanning for classes and methods
-
- def remove_commented_out_lines
- @content.gsub!(%r%//.*rb_define_%, '//')
- end
-
- ##
- # Removes private comments from +comment+
-
- def remove_private_comments(comment)
- comment.gsub!(/\/?\*--\n(.*?)\/?\*\+\+/m, '')
- comment.sub!(/\/?\*--\n.*/m, '')
- end
-
- ##
- # Extracts the classes, modules, methods, attributes, constants and aliases
- # from a C file and returns an RDoc::TopLevel for this file
-
- def scan
- remove_commented_out_lines
- do_classes
- do_constants
- do_methods
- do_includes
- do_aliases
- do_attrs
- @top_level
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/parser/ruby.rb b/ruby_1_9_3/lib/rdoc/parser/ruby.rb
deleted file mode 100644
index c9a12a8fe8..0000000000
--- a/ruby_1_9_3/lib/rdoc/parser/ruby.rb
+++ /dev/null
@@ -1,1782 +0,0 @@
-##
-# This file contains stuff stolen outright from:
-#
-# rtags.rb -
-# ruby-lex.rb - ruby lexcal analyzer
-# ruby-token.rb - ruby tokens
-# by Keiju ISHITSUKA (Nippon Rational Inc.)
-#
-
-require 'rdoc/ruby_token'
-require 'rdoc/ruby_lex'
-
-require 'rdoc/code_objects'
-require 'rdoc/token_stream'
-require 'rdoc/markup/pre_process'
-require 'rdoc/parser'
-require 'rdoc/parser/ruby_tools'
-
-$TOKEN_DEBUG ||= nil
-
-##
-# Extracts code elements from a source file returning a TopLevel object
-# containing the constituent file elements.
-#
-# This file is based on rtags
-#
-# RubyParser understands how to document:
-# * classes
-# * modules
-# * methods
-# * constants
-# * aliases
-# * private, public, protected
-# * private_class_function, public_class_function
-# * module_function
-# * attr, attr_reader, attr_writer, attr_accessor
-# * extra accessors given on the command line
-# * metaprogrammed methods
-# * require
-# * include
-#
-# == Method Arguments
-#
-#--
-# NOTE: I don't think this works, needs tests, remove the paragraph following
-# this block when known to work
-#
-# The parser extracts the arguments from the method definition. You can
-# override this with a custom argument definition using the :args: directive:
-#
-# ##
-# # This method tries over and over until it is tired
-#
-# def go_go_go(thing_to_try, tries = 10) # :args: thing_to_try
-# puts thing_to_try
-# go_go_go thing_to_try, tries - 1
-# end
-#
-# If you have a more-complex set of overrides you can use the :call-seq:
-# directive:
-#++
-#
-# The parser extracts the arguments from the method definition. You can
-# override this with a custom argument definition using the :call-seq:
-# directive:
-#
-# ##
-# # This method can be called with a range or an offset and length
-# #
-# # :call-seq:
-# # my_method(Range)
-# # my_method(offset, length)
-#
-# def my_method(*args)
-# end
-#
-# The parser extracts +yield+ expressions from method bodies to gather the
-# yielded argument names. If your method manually calls a block instead of
-# yielding or you want to override the discovered argument names use
-# the :yields: directive:
-#
-# ##
-# # My method is awesome
-#
-# def my_method(&block) # :yields: happy, times
-# block.call 1, 2
-# end
-#
-# == Metaprogrammed Methods
-#
-# To pick up a metaprogrammed method, the parser looks for a comment starting
-# with '##' before an identifier:
-#
-# ##
-# # This is a meta-programmed method!
-#
-# add_my_method :meta_method, :arg1, :arg2
-#
-# The parser looks at the token after the identifier to determine the name, in
-# this example, :meta_method. If a name cannot be found, a warning is printed
-# and 'unknown is used.
-#
-# You can force the name of a method using the :method: directive:
-#
-# ##
-# # :method: woo_hoo!
-#
-# By default, meta-methods are instance methods. To indicate that a method is
-# a singleton method instead use the :singleton-method: directive:
-#
-# ##
-# # :singleton-method:
-#
-# You can also use the :singleton-method: directive with a name:
-#
-# ##
-# # :singleton-method: woo_hoo!
-#
-# Additionally you can mark a method as an attribute by
-# using :attr:, :attr_reader:, :attr_writer: or :attr_accessor:. Just like
-# for :method:, the name is optional.
-#
-# ##
-# # :attr_reader: my_attr_name
-#
-# == Hidden methods and attributes
-#
-# You can provide documentation for methods that don't appear using
-# the :method:, :singleton-method: and :attr: directives:
-#
-# ##
-# # :attr_writer: ghost_writer
-# # There is an attribute here, but you can't see it!
-#
-# ##
-# # :method: ghost_method
-# # There is a method here, but you can't see it!
-#
-# ##
-# # this is a comment for a regular method
-#
-# def regular_method() end
-#
-# Note that by default, the :method: directive will be ignored if there is a
-# standard rdocable item following it.
-
-class RDoc::Parser::Ruby < RDoc::Parser
-
- parse_files_matching(/\.rbw?$/)
-
- include RDoc::RubyToken
- include RDoc::TokenStream
- include RDoc::Parser::RubyTools
-
- ##
- # RDoc::NormalClass type
-
- NORMAL = "::"
-
- ##
- # RDoc::SingleClass type
-
- SINGLE = "<<"
-
- ##
- # Creates a new Ruby parser.
-
- def initialize(top_level, file_name, content, options, stats)
- super
-
- @size = 0
- @token_listeners = nil
- @scanner = RDoc::RubyLex.new content, @options
- @scanner.exception_on_syntax_error = false
- @prev_seek = nil
-
- @encoding = nil
- @encoding = @options.encoding if Object.const_defined? :Encoding
-
- reset
- end
-
- ##
- # Look for the first comment in a file that isn't a shebang line.
-
- def collect_first_comment
- skip_tkspace
- comment = ''
- comment.force_encoding @encoding if @encoding
- first_line = true
-
- tk = get_tk
-
- while TkCOMMENT === tk
- if first_line and tk.text =~ /\A#!/ then
- skip_tkspace
- tk = get_tk
- elsif first_line and tk.text =~ /\A#\s*-\*-/ then
- first_line = false
- skip_tkspace
- tk = get_tk
- else
- first_line = false
- comment << tk.text << "\n"
- tk = get_tk
-
- if TkNL === tk then
- skip_tkspace false
- tk = get_tk
- end
- end
- end
-
- unget_tk tk
-
- comment
- end
-
- ##
- # Aborts with +msg+
-
- def error(msg)
- msg = make_message msg
-
- abort msg
- end
-
- ##
- # Look for a 'call-seq' in the comment, and override the normal parameter
- # stuff
- #--
- # TODO handle undent
-
- def extract_call_seq(comment, meth)
- if comment.sub!(/:?call-seq:(.*?)(^\s*#?\s*$|\z)/m, '') then
- seq = $1
- seq.gsub!(/^\s*\#\s*/, '')
- meth.call_seq = seq
- end
-
- meth
- end
-
- ##
- # Looks for a true or false token. Returns false if TkFALSE or TkNIL are
- # found.
-
- def get_bool
- skip_tkspace
- tk = get_tk
- case tk
- when TkTRUE
- true
- when TkFALSE, TkNIL
- false
- else
- unget_tk tk
- true
- end
- end
-
- ##
- # Look for the name of a class of module (optionally with a leading :: or
- # with :: separated named) and return the ultimate name, the associated
- # container, and the given name (with the ::).
-
- def get_class_or_module(container)
- skip_tkspace
- name_t = get_tk
- given_name = ''
-
- # class ::A -> A is in the top level
- case name_t
- when TkCOLON2, TkCOLON3 then # bug
- name_t = get_tk
- container = @top_level
- given_name << '::'
- end
-
- skip_tkspace false
- given_name << name_t.name
-
- while TkCOLON2 === peek_tk do
- prev_container = container
- container = container.find_module_named name_t.name
- unless container then
- container = prev_container.add_module RDoc::NormalModule, name_t.name
- end
- get_tk
- name_t = get_tk
- given_name << '::' << name_t.name
- end
- skip_tkspace false
- return [container, name_t, given_name]
- end
-
- ##
- # Return a superclass, which can be either a constant of an expression
-
- def get_class_specification
- tk = get_tk
- return "self" if TkSELF === tk
-
- res = ""
- while TkCOLON2 === tk or TkCOLON3 === tk or TkCONSTANT === tk do
- res += tk.name
- tk = get_tk
- end
-
- unget_tk(tk)
- skip_tkspace false
-
- get_tkread # empty out read buffer
-
- tk = get_tk
-
- case tk
- when TkNL, TkCOMMENT, TkSEMICOLON then
- unget_tk(tk)
- return res
- end
-
- res += parse_call_parameters(tk)
- res
- end
-
- ##
- # Parse a constant, which might be qualified by one or more class or module
- # names
-
- def get_constant
- res = ""
- skip_tkspace false
- tk = get_tk
-
- while TkCOLON2 === tk or TkCOLON3 === tk or TkCONSTANT === tk do
- res += tk.name
- tk = get_tk
- end
-
-# if res.empty?
-# warn("Unexpected token #{tk} in constant")
-# end
- unget_tk(tk)
- res
- end
-
- ##
- # Get a constant that may be surrounded by parens
-
- def get_constant_with_optional_parens
- skip_tkspace false
-
- nest = 0
-
- while TkLPAREN === (tk = peek_tk) or TkfLPAREN === tk do
- get_tk
- skip_tkspace
- nest += 1
- end
-
- name = get_constant
-
- while nest > 0
- skip_tkspace
- tk = get_tk
- nest -= 1 if TkRPAREN === tk
- end
-
- name
- end
-
- ##
- # Extracts a name or symbol from the token stream.
-
- def get_symbol_or_name
- tk = get_tk
- case tk
- when TkSYMBOL then
- text = tk.text.sub(/^:/, '')
-
- if TkASSIGN === peek_tk then
- get_tk
- text << '='
- end
-
- text
- when TkId, TkOp then
- tk.name
- when TkAMPER,
- TkDSTRING,
- TkSTAR,
- TkSTRING then
- tk.text
- else
- raise RDoc::Error, "Name or symbol expected (got #{tk})"
- end
- end
-
- ##
- # Look for directives in a normal comment block:
- #
- # # :stopdoc:
- # # Don't display comment from this point forward
- #
- # This routine modifies its +comment+ parameter.
-
- def look_for_directives_in context, comment
- @preprocess.handle comment, context do |directive, param|
- case directive
- when 'method', 'singleton-method',
- 'attr', 'attr_accessor', 'attr_reader', 'attr_writer' then
- false # handled elsewhere
- when 'section' then
- context.set_current_section param, comment
- comment.replace ''
- break
- end
- end
-
- remove_private_comments comment
- end
-
- ##
- # Adds useful info about the parser to +message+
-
- def make_message message
- prefix = "#{@file_name}:"
-
- prefix << "#{@scanner.line_no}:#{@scanner.char_no}:" if @scanner
-
- "#{prefix} #{message}"
- end
-
- ##
- # Creates an RDoc::Attr for the name following +tk+, setting the comment to
- # +comment+.
-
- def parse_attr(context, single, tk, comment)
- offset = tk.seek
- line_no = tk.line_no
-
- args = parse_symbol_arg 1
- if args.size > 0 then
- name = args[0]
- rw = "R"
- skip_tkspace false
- tk = get_tk
-
- if TkCOMMA === tk then
- rw = "RW" if get_bool
- else
- unget_tk tk
- end
-
- att = RDoc::Attr.new get_tkread, name, rw, comment, single == SINGLE
- att.record_location @top_level
- att.offset = offset
- att.line = line_no
-
- read_documentation_modifiers att, RDoc::ATTR_MODIFIERS
-
- context.add_attribute att
-
- @stats.add_attribute att
- else
- warn "'attr' ignored - looks like a variable"
- end
- end
-
- ##
- # Creates an RDoc::Attr for each attribute listed after +tk+, setting the
- # comment for each to +comment+.
-
- def parse_attr_accessor(context, single, tk, comment)
- offset = tk.seek
- line_no = tk.line_no
-
- args = parse_symbol_arg
- rw = "?"
-
- tmp = RDoc::CodeObject.new
- read_documentation_modifiers tmp, RDoc::ATTR_MODIFIERS
- # TODO In most other places we let the context keep track of document_self
- # and add found items appropriately but here we do not. I'm not sure why.
- return unless tmp.document_self
-
- case tk.name
- when "attr_reader" then rw = "R"
- when "attr_writer" then rw = "W"
- when "attr_accessor" then rw = "RW"
- else
- rw = '?'
- end
-
- for name in args
- att = RDoc::Attr.new get_tkread, name, rw, comment, single == SINGLE
- att.record_location @top_level
- att.offset = offset
- att.line = line_no
-
- context.add_attribute att
- @stats.add_attribute att
- end
- end
-
- ##
- # Parses an +alias+ in +context+ with +comment+
-
- def parse_alias(context, single, tk, comment)
- offset = tk.seek
- line_no = tk.line_no
-
- skip_tkspace
-
- if TkLPAREN === peek_tk then
- get_tk
- skip_tkspace
- end
-
- new_name = get_symbol_or_name
-
- @scanner.instance_eval { @lex_state = EXPR_FNAME }
-
- skip_tkspace
- if TkCOMMA === peek_tk then
- get_tk
- skip_tkspace
- end
-
- begin
- old_name = get_symbol_or_name
- rescue RDoc::Error
- return
- end
-
- al = RDoc::Alias.new(get_tkread, old_name, new_name, comment,
- single == SINGLE)
- al.record_location @top_level
- al.offset = offset
- al.line = line_no
-
- read_documentation_modifiers al, RDoc::ATTR_MODIFIERS
- context.add_alias al
- @stats.add_alias al
-
- al
- end
-
- ##
- # Extracts call parameters from the token stream.
-
- def parse_call_parameters(tk)
- end_token = case tk
- when TkLPAREN, TkfLPAREN
- TkRPAREN
- when TkRPAREN
- return ""
- else
- TkNL
- end
- nest = 0
-
- loop do
- case tk
- when TkSEMICOLON
- break
- when TkLPAREN, TkfLPAREN
- nest += 1
- when end_token
- if end_token == TkRPAREN
- nest -= 1
- break if @scanner.lex_state == EXPR_END and nest <= 0
- else
- break unless @scanner.continue
- end
- when TkCOMMENT, TkASSIGN, TkOPASGN
- unget_tk(tk)
- break
- when nil then
- break
- end
- tk = get_tk
- end
- res = get_tkread.tr("\n", " ").strip
- res = "" if res == ";"
- res
- end
-
- ##
- # Parses a class in +context+ with +comment+
-
- def parse_class(container, single, tk, comment)
- offset = tk.seek
- line_no = tk.line_no
-
- declaration_context = container
- container, name_t, given_name = get_class_or_module container
-
- case name_t
- when TkCONSTANT
- name = name_t.name
- superclass = '::Object'
-
- if TkLT === peek_tk then
- get_tk
- skip_tkspace
- superclass = get_class_specification
- superclass = '(unknown)' if superclass.empty?
- end
-
- cls_type = single == SINGLE ? RDoc::SingleClass : RDoc::NormalClass
- cls = declaration_context.add_class cls_type, given_name, superclass
- cls.ignore unless container.document_children
-
- read_documentation_modifiers cls, RDoc::CLASS_MODIFIERS
- cls.record_location @top_level
- cls.offset = offset
- cls.line = line_no
-
- cls.add_comment comment, @top_level
-
- @top_level.add_to_classes_or_modules cls
- @stats.add_class cls
-
- parse_statements cls
- when TkLSHFT
- case name = get_class_specification
- when "self", container.name
- parse_statements container, SINGLE
- else
- other = RDoc::TopLevel.find_class_named name
-
- unless other then
- other = container.add_module RDoc::NormalModule, name
- other.record_location @top_level
- other.offset = offset
- other.line = line_no
-
- other.add_comment comment, @top_level
- end
-
- # notify :nodoc: all if not a constant-named class/module
- # (and remove any comment)
- unless name =~ /\A(::)?[A-Z]/ then
- other.document_self = nil
- other.document_children = false
- other.clear_comment
- end
-
- @top_level.add_to_classes_or_modules other
- @stats.add_class other
-
- read_documentation_modifiers other, RDoc::CLASS_MODIFIERS
- parse_statements(other, SINGLE)
- end
- else
- warn("Expected class name or '<<'. Got #{name_t.class}: #{name_t.text.inspect}")
- end
- end
-
- ##
- # Parses a constant in +context+ with +comment+
-
- def parse_constant container, tk, comment
- offset = tk.seek
- line_no = tk.line_no
-
- name = tk.name
- skip_tkspace false
-
- return unless name =~ /^\w+$/
-
- eq_tk = get_tk
-
- unless TkASSIGN === eq_tk then
- unget_tk eq_tk
- return false
- end
-
- nest = 0
- get_tkread
-
- tk = get_tk
-
- if TkGT === tk then
- unget_tk tk
- unget_tk eq_tk
- return false
- end
-
- rhs_name = ''
-
- loop do
- case tk
- when TkSEMICOLON then
- break if nest <= 0
- when TkLPAREN, TkfLPAREN, TkLBRACE, TkfLBRACE, TkLBRACK, TkfLBRACK,
- TkDO, TkIF, TkUNLESS, TkCASE, TkDEF, TkBEGIN then
- nest += 1
- when TkRPAREN, TkRBRACE, TkRBRACK, TkEND then
- nest -= 1
- when TkCOMMENT then
- if nest <= 0 &&
- (@scanner.lex_state == EXPR_END || !@scanner.continue) then
- unget_tk tk
- break
- end
- when TkCONSTANT then
- rhs_name << tk.name
-
- if nest <= 0 and TkNL === peek_tk then
- mod = if rhs_name =~ /^::/ then
- RDoc::TopLevel.find_class_or_module rhs_name
- else
- container.find_module_named rhs_name
- end
-
- container.add_module_alias mod, name, @top_level if mod
- break
- end
- when TkNL then
- if nest <= 0 &&
- (@scanner.lex_state == EXPR_END || !@scanner.continue) then
- unget_tk tk
- break
- end
- when TkCOLON2, TkCOLON3 then
- rhs_name << '::'
- when nil then
- break
- end
- tk = get_tk
- end
-
- res = get_tkread.gsub(/^[ \t]+/, '').strip
- res = "" if res == ";"
-
- con = RDoc::Constant.new name, res, comment
- con.record_location @top_level
- con.offset = offset
- con.line = line_no
- read_documentation_modifiers con, RDoc::CONSTANT_MODIFIERS
-
- @stats.add_constant con
- container.add_constant con
- true
- end
-
- ##
- # Generates an RDoc::Method or RDoc::Attr from +comment+ by looking for
- # :method: or :attr: directives in +comment+.
-
- def parse_comment(container, tk, comment)
- column = tk.char_no
- offset = tk.seek
- line_no = tk.line_no
-
- singleton = !!comment.sub!(/(^# +:?)(singleton-)(method:)/, '\1\3')
-
- # REFACTOR
- if comment.sub!(/^# +:?method: *(\S*).*?\n/i, '') then
- name = $1 unless $1.empty?
-
- meth = RDoc::GhostMethod.new get_tkread, name
- meth.record_location @top_level
- meth.singleton = singleton
- meth.offset = offset
- meth.line = line_no
-
- meth.start_collecting_tokens
- indent = TkSPACE.new nil, 1, 1
- indent.set_text " " * column
-
- position_comment = TkCOMMENT.new nil, line_no, 1
- position_comment.set_text "# File #{@top_level.absolute_name}, line #{line_no}"
- meth.add_tokens [position_comment, NEWLINE_TOKEN, indent]
-
- meth.params = ''
-
- extract_call_seq comment, meth
-
- return unless meth.name
-
- container.add_method meth
-
- meth.comment = comment
-
- @stats.add_method meth
- elsif comment.sub!(/# +:?(attr(_reader|_writer|_accessor)?): *(\S*).*?\n/i, '') then
- rw = case $1
- when 'attr_reader' then 'R'
- when 'attr_writer' then 'W'
- else 'RW'
- end
-
- name = $3 unless $3.empty?
-
- # TODO authorize 'singleton-attr...'?
- att = RDoc::Attr.new get_tkread, name, rw, comment
- att.record_location @top_level
- att.offset = offset
- att.line = line_no
-
- container.add_attribute att
- @stats.add_attribute att
- end
-
- true
- end
-
- ##
- # Parses an +include+ in +context+ with +comment+
-
- def parse_include context, comment
- loop do
- skip_tkspace_comment
-
- name = get_constant_with_optional_parens
-
- unless name.empty? then
- incl = context.add_include RDoc::Include.new(name, comment)
- incl.record_location @top_level
- end
-
- return unless TkCOMMA === peek_tk
-
- get_tk
- end
- end
-
- ##
- # Parses a meta-programmed attribute and creates an RDoc::Attr.
- #
- # To create foo and bar attributes on class C with comment "My attributes":
- #
- # class C
- #
- # ##
- # # :attr:
- # #
- # # My attributes
- #
- # my_attr :foo, :bar
- #
- # end
- #
- # To create a foo attribute on class C with comment "My attribute":
- #
- # class C
- #
- # ##
- # # :attr: foo
- # #
- # # My attribute
- #
- # my_attr :foo, :bar
- #
- # end
-
- def parse_meta_attr(context, single, tk, comment)
- args = parse_symbol_arg
- rw = "?"
-
- # If nodoc is given, don't document any of them
-
- tmp = RDoc::CodeObject.new
- read_documentation_modifiers tmp, RDoc::ATTR_MODIFIERS
-
- if comment.sub!(/^# +:?(attr(_reader|_writer|_accessor)?): *(\S*).*?\n/i, '') then
- rw = case $1
- when 'attr_reader' then 'R'
- when 'attr_writer' then 'W'
- else 'RW'
- end
- name = $3 unless $3.empty?
- end
-
- if name then
- att = RDoc::Attr.new get_tkread, name, rw, comment, single == SINGLE
- att.record_location @top_level
-
- context.add_attribute att
- @stats.add_attribute att
- else
- args.each do |attr_name|
- att = RDoc::Attr.new(get_tkread, attr_name, rw, comment,
- single == SINGLE)
- att.record_location @top_level
-
- context.add_attribute att
- @stats.add_attribute att
- end
- end
- end
-
- ##
- # Parses a meta-programmed method
-
- def parse_meta_method(container, single, tk, comment)
- column = tk.char_no
- offset = tk.seek
- line_no = tk.line_no
-
- start_collecting_tokens
- add_token tk
- add_token_listener self
-
- skip_tkspace false
-
- singleton = !!comment.sub!(/(^# +:?)(singleton-)(method:)/, '\1\3')
-
- if comment.sub!(/^# +:?method: *(\S*).*?\n/i, '') then
- name = $1 unless $1.empty?
- end
-
- if name.nil? then
- name_t = get_tk
- case name_t
- when TkSYMBOL then
- name = name_t.text[1..-1]
- when TkSTRING then
- name = name_t.value[1..-2]
- when TkASSIGN then # ignore
- remove_token_listener self
- return
- else
- warn "unknown name token #{name_t.inspect} for meta-method '#{tk.name}'"
- name = 'unknown'
- end
- end
-
- meth = RDoc::MetaMethod.new get_tkread, name
- meth.record_location @top_level
- meth.offset = offset
- meth.line = line_no
- meth.singleton = singleton
-
- remove_token_listener self
-
- meth.start_collecting_tokens
- indent = TkSPACE.new nil, 1, 1
- indent.set_text " " * column
-
- position_comment = TkCOMMENT.new nil, line_no, 1
- position_comment.value = "# File #{@top_level.absolute_name}, line #{line_no}"
- meth.add_tokens [position_comment, NEWLINE_TOKEN, indent]
- meth.add_tokens @token_stream
-
- token_listener meth do
- meth.params = ''
-
- extract_call_seq comment, meth
-
- container.add_method meth
-
- last_tk = tk
-
- while tk = get_tk do
- case tk
- when TkSEMICOLON then
- break
- when TkNL then
- break unless last_tk and TkCOMMA === last_tk
- when TkSPACE then
- # expression continues
- when TkDO then
- unget_tk tk
- parse_statements container, single, meth
- break
- else
- last_tk = tk
- end
- end
- end
-
- meth.comment = comment
-
- @stats.add_method meth
- end
-
- ##
- # Parses a normal method defined by +def+
-
- def parse_method(container, single, tk, comment)
- added_container = nil
- meth = nil
- name = nil
- column = tk.char_no
- offset = tk.seek
- line_no = tk.line_no
-
- start_collecting_tokens
- add_token tk
-
- token_listener self do
- @scanner.instance_eval do @lex_state = EXPR_FNAME end
-
- skip_tkspace
- name_t = get_tk
- back_tk = skip_tkspace
- meth = nil
- added_container = false
-
- dot = get_tk
- if TkDOT === dot or TkCOLON2 === dot then
- @scanner.instance_eval do @lex_state = EXPR_FNAME end
- skip_tkspace
- name_t2 = get_tk
-
- case name_t
- when TkSELF, TkMOD then
- name = name_t2.name
- when TkCONSTANT then
- name = name_t2.name
- prev_container = container
- container = container.find_module_named(name_t.name)
- unless container then
- added_container = true
- obj = name_t.name.split("::").inject(Object) do |state, item|
- state.const_get(item)
- end rescue nil
-
- type = obj.class == Class ? RDoc::NormalClass : RDoc::NormalModule
-
- unless [Class, Module].include?(obj.class) then
- warn("Couldn't find #{name_t.name}. Assuming it's a module")
- end
-
- if type == RDoc::NormalClass then
- sclass = obj.superclass ? obj.superclass.name : nil
- container = prev_container.add_class type, name_t.name, sclass
- else
- container = prev_container.add_module type, name_t.name
- end
-
- container.record_location @top_level
- end
- when TkIDENTIFIER, TkIVAR, TkGVAR then
- dummy = RDoc::Context.new
- dummy.parent = container
- skip_method dummy
- return
- when TkTRUE, TkFALSE, TkNIL then
- klass_name = "#{name_t.name.capitalize}Class"
- container = RDoc::TopLevel.find_class_named klass_name
- container ||= @top_level.add_class RDoc::NormalClass, klass_name
-
- name = name_t2.name
- else
- warn "unexpected method name token #{name_t.inspect}"
- # break
- skip_method container
- return
- end
-
- meth = RDoc::AnyMethod.new(get_tkread, name)
- meth.singleton = true
- else
- unget_tk dot
- back_tk.reverse_each do |token|
- unget_tk token
- end
-
- name = case name_t
- when TkSTAR, TkAMPER then
- name_t.text
- else
- unless name_t.respond_to? :name then
- warn "expected method name token, . or ::, got #{name_t.inspect}"
- skip_method container
- return
- end
- name_t.name
- end
-
- meth = RDoc::AnyMethod.new get_tkread, name
- meth.singleton = (single == SINGLE)
- end
- end
-
- meth.record_location @top_level
- meth.offset = offset
- meth.line = line_no
-
- meth.start_collecting_tokens
- indent = TkSPACE.new nil, 1, 1
- indent.set_text " " * column
-
- token = TkCOMMENT.new nil, line_no, 1
- token.set_text "# File #{@top_level.absolute_name}, line #{line_no}"
- meth.add_tokens [token, NEWLINE_TOKEN, indent]
- meth.add_tokens @token_stream
-
- token_listener meth do
- @scanner.instance_eval do @continue = false end
- parse_method_parameters meth
-
- if meth.document_self then
- container.add_method meth
- elsif added_container then
- container.document_self = false
- end
-
- # Having now read the method parameters and documentation modifiers, we
- # now know whether we have to rename #initialize to ::new
-
- if name == "initialize" && !meth.singleton then
- if meth.dont_rename_initialize then
- meth.visibility = :protected
- else
- meth.singleton = true
- meth.name = "new"
- meth.visibility = :public
- end
- end
-
- parse_statements container, single, meth
- end
-
- extract_call_seq comment, meth
-
- meth.comment = comment
-
- @stats.add_method meth
- end
-
- ##
- # Extracts +yield+ parameters from +method+
-
- def parse_method_or_yield_parameters(method = nil,
- modifiers = RDoc::METHOD_MODIFIERS)
- skip_tkspace false
- tk = get_tk
-
- # Little hack going on here. In the statement
- # f = 2*(1+yield)
- # We see the RPAREN as the next token, so we need
- # to exit early. This still won't catch all cases
- # (such as "a = yield + 1"
- end_token = case tk
- when TkLPAREN, TkfLPAREN
- TkRPAREN
- when TkRPAREN
- return ""
- else
- TkNL
- end
- nest = 0
-
- loop do
- case tk
- when TkSEMICOLON then
- break if nest == 0
- when TkLBRACE, TkfLBRACE then
- nest += 1
- when TkRBRACE then
- nest -= 1
- if nest <= 0
- # we might have a.each { |i| yield i }
- unget_tk(tk) if nest < 0
- break
- end
- when TkLPAREN, TkfLPAREN then
- nest += 1
- when end_token then
- if end_token == TkRPAREN
- nest -= 1
- break if @scanner.lex_state == EXPR_END and nest <= 0
- else
- break unless @scanner.continue
- end
- when TkRPAREN then
- nest -= 1
- when method && method.block_params.nil? && TkCOMMENT then
- unget_tk tk
- read_documentation_modifiers method, modifiers
- @read.pop
- when TkCOMMENT then
- @read.pop
- when nil then
- break
- end
- tk = get_tk
- end
-
- res = get_tkread.gsub(/\s+/, ' ').strip
- res = '' if res == ';'
- res
- end
-
- ##
- # Capture the method's parameters. Along the way, look for a comment
- # containing:
- #
- # # yields: ....
- #
- # and add this as the block_params for the method
-
- def parse_method_parameters(method)
- res = parse_method_or_yield_parameters method
-
- res = "(#{res})" unless res =~ /\A\(/
- method.params = res unless method.params
-
- if method.block_params.nil? then
- skip_tkspace false
- read_documentation_modifiers method, RDoc::METHOD_MODIFIERS
- end
- end
-
- ##
- # Parses an RDoc::NormalModule in +container+ with +comment+
-
- def parse_module(container, single, tk, comment)
- container, name_t, = get_class_or_module container
-
- name = name_t.name
-
- mod = container.add_module RDoc::NormalModule, name
- mod.record_location @top_level
-
- read_documentation_modifiers mod, RDoc::CLASS_MODIFIERS
- mod.add_comment comment, @top_level
- parse_statements(mod)
-
- @top_level.add_to_classes_or_modules mod
- @stats.add_module mod
- end
-
- ##
- # Parses an RDoc::Require in +context+ containing +comment+
-
- def parse_require(context, comment)
- skip_tkspace_comment
- tk = get_tk
-
- if TkLPAREN === tk then
- skip_tkspace_comment
- tk = get_tk
- end
-
- name = tk.text if TkSTRING === tk
-
- if name then
- @top_level.add_require RDoc::Require.new(name, comment)
- else
- unget_tk tk
- end
- end
-
- ##
- # The core of the ruby parser.
-
- def parse_statements(container, single = NORMAL, current_method = nil,
- comment = '')
- comment.force_encoding @encoding if @encoding
-
- nest = 1
- save_visibility = container.visibility
-
- non_comment_seen = true
-
- while tk = get_tk do
- keep_comment = false
- try_parse_comment = false
-
- non_comment_seen = true unless TkCOMMENT === tk
-
- case tk
- when TkNL then
- skip_tkspace
- tk = get_tk
-
- if TkCOMMENT === tk then
- if non_comment_seen then
- # Look for RDoc in a comment about to be thrown away
- non_comment_seen = parse_comment container, tk, comment unless
- comment.empty?
-
- comment = ''
- comment.force_encoding @encoding if @encoding
- end
-
- while TkCOMMENT === tk do
- comment << tk.text << "\n"
-
- tk = get_tk
-
- if TkNL === tk then
- skip_tkspace false # leading spaces
- tk = get_tk
- end
- end
-
- unless comment.empty? then
- look_for_directives_in container, comment
-
- if container.done_documenting then
- container.ongoing_visibility = save_visibility
- end
- end
-
- keep_comment = true
- else
- non_comment_seen = true
- end
-
- unget_tk tk # TODO peek instead of get then unget
- keep_comment = true
-
- when TkCLASS then
- parse_class container, single, tk, comment
-
- when TkMODULE then
- if container.document_children then
- parse_module container, single, tk, comment
- else
- nest += 1
- end
-
- when TkDEF then
- parse_method container, single, tk, comment
-
- when TkCONSTANT then
- unless parse_constant container, tk, comment then
- try_parse_comment = true
- end
-
- when TkALIAS then
- parse_alias container, single, tk, comment unless current_method
-
- when TkYIELD then
- if current_method.nil? then
- warn "Warning: yield outside of method" if container.document_self
- else
- parse_yield container, single, tk, current_method
- end
-
- # Until and While can have a 'do', which shouldn't increase the nesting.
- # We can't solve the general case, but we can handle most occurrences by
- # ignoring a do at the end of a line.
-
- when TkUNTIL, TkWHILE then
- nest += 1
- skip_optional_do_after_expression
-
- # 'for' is trickier
- when TkFOR then
- nest += 1
- skip_for_variable
- skip_optional_do_after_expression
-
- when TkCASE, TkDO, TkIF, TkUNLESS, TkBEGIN then
- nest += 1
-
- when TkIDENTIFIER then
- if nest == 1 and current_method.nil? then
- case tk.name
- when 'private', 'protected', 'public', 'private_class_method',
- 'public_class_method', 'module_function' then
- parse_visibility container, single, tk
- keep_comment = true
- when 'attr' then
- parse_attr container, single, tk, comment
- when /^attr_(reader|writer|accessor)$/ then
- parse_attr_accessor container, single, tk, comment
- when 'alias_method' then
- parse_alias container, single, tk, comment
- when 'require', 'include' then
- # ignore
- else
- if comment =~ /\A#\#$/ then
- case comment
- when /^# +:?attr(_reader|_writer|_accessor)?:/ then
- parse_meta_attr container, single, tk, comment
- else
- parse_meta_method container, single, tk, comment
- end
- end
- end
- end
-
- case tk.name
- when "require" then
- parse_require container, comment
- when "include" then
- parse_include container, comment
- end
-
- when TkEND then
- nest -= 1
- if nest == 0 then
- read_documentation_modifiers container, RDoc::CLASS_MODIFIERS
- container.ongoing_visibility = save_visibility
-
- parse_comment container, tk, comment unless comment.empty?
-
- return
- end
- else
- try_parse_comment = nest == 1
- end
-
- if try_parse_comment then
- non_comment_seen = parse_comment container, tk, comment unless
- comment.empty?
-
- keep_comment = false
- end
-
- unless keep_comment then
- comment = ''
- comment.force_encoding @encoding if @encoding
- end
-
- begin
- get_tkread
- skip_tkspace false
- end while peek_tk == TkNL
- end
- end
-
- ##
- # Parse up to +no+ symbol arguments
-
- def parse_symbol_arg(no = nil)
- args = []
-
- skip_tkspace_comment
-
- case tk = get_tk
- when TkLPAREN
- loop do
- skip_tkspace_comment
- if tk1 = parse_symbol_in_arg
- args.push tk1
- break if no and args.size >= no
- end
-
- skip_tkspace_comment
- case tk2 = get_tk
- when TkRPAREN
- break
- when TkCOMMA
- else
- warn("unexpected token: '#{tk2.inspect}'") if $DEBUG_RDOC
- break
- end
- end
- else
- unget_tk tk
- if tk = parse_symbol_in_arg
- args.push tk
- return args if no and args.size >= no
- end
-
- loop do
- skip_tkspace false
-
- tk1 = get_tk
- unless TkCOMMA === tk1 then
- unget_tk tk1
- break
- end
-
- skip_tkspace_comment
- if tk = parse_symbol_in_arg
- args.push tk
- break if no and args.size >= no
- end
- end
- end
-
- args
- end
-
- ##
- # Returns symbol text from the next token
-
- def parse_symbol_in_arg
- case tk = get_tk
- when TkSYMBOL
- tk.text.sub(/^:/, '')
- when TkSTRING
- eval @read[-1]
- when TkDSTRING, TkIDENTIFIER then
- nil # ignore
- else
- warn("Expected symbol or string, got #{tk.inspect}") if $DEBUG_RDOC
- nil
- end
- end
-
- ##
- # Parses statements in the top-level +container+
-
- def parse_top_level_statements container
- comment = collect_first_comment
- look_for_directives_in container, comment
-
- # HACK move if to RDoc::Context#comment=
- container.comment = comment if container.document_self unless comment.empty?
-
- parse_statements container, NORMAL, nil, comment
- end
-
- ##
- # Determines the visibility in +container+ from +tk+
-
- def parse_visibility(container, single, tk)
- singleton = (single == SINGLE)
-
- vis_type = tk.name
-
- vis = case vis_type
- when 'private' then :private
- when 'protected' then :protected
- when 'public' then :public
- when 'private_class_method' then
- singleton = true
- :private
- when 'public_class_method' then
- singleton = true
- :public
- when 'module_function' then
- singleton = true
- :public
- else
- raise RDoc::Error, "Invalid visibility: #{tk.name}"
- end
-
- skip_tkspace_comment false
-
- case peek_tk
- # Ryan Davis suggested the extension to ignore modifiers, because he
- # often writes
- #
- # protected unless $TESTING
- #
- when TkNL, TkUNLESS_MOD, TkIF_MOD, TkSEMICOLON then
- container.ongoing_visibility = vis
- else
- new_methods = []
-
- case vis_type
- when 'module_function' then
- args = parse_symbol_arg
- container.set_visibility_for args, :private, false
-
- container.methods_matching args do |m|
- s_m = m.dup
- s_m.record_location @top_level
- s_m.singleton = true
- new_methods << s_m
- end
- when 'public_class_method', 'private_class_method' then
- args = parse_symbol_arg
-
- container.methods_matching args, true do |m|
- if m.parent != container then
- m = m.dup
- m.record_location @top_level
- new_methods << m
- end
-
- m.visibility = vis
- end
- else
- args = parse_symbol_arg
- container.set_visibility_for args, vis, singleton
- end
-
- new_methods.each do |method|
- case method
- when RDoc::AnyMethod then
- container.add_method method
- when RDoc::Attr then
- container.add_attribute method
- end
- method.visibility = vis
- end
- end
- end
-
- ##
- # Determines the block parameter for +context+
-
- def parse_yield(context, single, tk, method)
- return if method.block_params
-
- get_tkread
- @scanner.instance_eval { @continue = false }
- method.block_params = parse_method_or_yield_parameters
- end
-
- ##
- # Directives are modifier comments that can appear after class, module, or
- # method names. For example:
- #
- # def fred # :yields: a, b
- #
- # or:
- #
- # class MyClass # :nodoc:
- #
- # We return the directive name and any parameters as a two element array
-
- def read_directive allowed
- tk = get_tk
-
- if TkCOMMENT === tk then
- return unless tk.text =~ /\s*:?(\w+):\s*(.*)/
-
- directive = $1.downcase
-
- return [directive, $2] if allowed.include? directive
- else
- unget_tk tk
- end
- end
-
- ##
- # Handles the directive for +context+ if the directive is listed in +allow+.
- # This method is called for directives following a definition.
-
- def read_documentation_modifiers context, allow
- directive, value = read_directive allow
-
- return unless directive
-
- @preprocess.handle_directive '', directive, value, context do |dir, param|
- if %w[notnew not_new not-new].include? dir then
- context.dont_rename_initialize = true
-
- true
- end
- end
- end
-
- ##
- # Removes private comments from +comment+
-
- def remove_private_comments(comment)
- empty = ''
- empty.force_encoding comment.encoding if Object.const_defined? :Encoding
-
- comment.gsub!(/^#--.*?^#\+\+\n?/m, empty)
- comment.sub!(/^#--.*/m, '')
- end
-
- ##
- # Scans this ruby file for ruby constructs
-
- def scan
- reset
-
- catch :eof do
- begin
- parse_top_level_statements @top_level
- rescue StandardError => e
- bytes = ''
-
- 20.times do @scanner.ungetc end
- count = 0
- 60.times do |i|
- count = i
- byte = @scanner.getc
- break unless byte
- bytes << byte
- end
- count -= 20
- count.times do @scanner.ungetc end
-
- $stderr.puts <<-EOF
-
-#{self.class} failure around line #{@scanner.line_no} of
-#{@file_name}
-
- EOF
-
- unless bytes.empty? then
- $stderr.puts
- $stderr.puts bytes.inspect
- end
-
- raise e
- end
- end
-
- @top_level
- end
-
- ##
- # while, until, and for have an optional do
-
- def skip_optional_do_after_expression
- skip_tkspace false
- tk = get_tk
- case tk
- when TkLPAREN, TkfLPAREN then
- end_token = TkRPAREN
- else
- end_token = TkNL
- end
-
- b_nest = 0
- nest = 0
- @scanner.instance_eval { @continue = false }
-
- loop do
- case tk
- when TkSEMICOLON then
- break if b_nest.zero?
- when TkLPAREN, TkfLPAREN then
- nest += 1
- when TkBEGIN then
- b_nest += 1
- when TkEND then
- b_nest -= 1
- when TkDO
- break if nest.zero?
- when end_token then
- if end_token == TkRPAREN
- nest -= 1
- break if @scanner.lex_state == EXPR_END and nest.zero?
- else
- break unless @scanner.continue
- end
- when nil then
- break
- end
- tk = get_tk
- end
-
- skip_tkspace false
-
- get_tk if TkDO === peek_tk
- end
-
- ##
- # skip the var [in] part of a 'for' statement
-
- def skip_for_variable
- skip_tkspace false
- tk = get_tk
- skip_tkspace false
- tk = get_tk
- unget_tk(tk) unless TkIN === tk
- end
-
- ##
- # Skips the next method in +container+
-
- def skip_method container
- meth = RDoc::AnyMethod.new "", "anon"
- parse_method_parameters meth
- parse_statements container, false, meth
- end
-
- ##
- # Skip spaces until a comment is found
-
- def skip_tkspace_comment(skip_nl = true)
- loop do
- skip_tkspace skip_nl
- return unless TkCOMMENT === peek_tk
- get_tk
- end
- end
-
- ##
- # Prints +msg+ to +$stderr+ unless we're being quiet
-
- def warn(msg)
- return if @options.quiet
- msg = make_message msg
- $stderr.puts msg
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/parser/ruby_tools.rb b/ruby_1_9_3/lib/rdoc/parser/ruby_tools.rb
deleted file mode 100644
index 678f721624..0000000000
--- a/ruby_1_9_3/lib/rdoc/parser/ruby_tools.rb
+++ /dev/null
@@ -1,162 +0,0 @@
-##
-# Collection of methods for writing parsers against RDoc::RubyLex and
-# RDoc::RubyToken
-
-module RDoc::Parser::RubyTools
-
- include RDoc::RubyToken
-
- ##
- # Adds a token listener +obj+, but you should probably use token_listener
-
- def add_token_listener(obj)
- @token_listeners ||= []
- @token_listeners << obj
- end
-
- ##
- # Fetches the next token from the scanner
-
- def get_tk
- tk = nil
-
- if @tokens.empty? then
- tk = @scanner.token
- @read.push @scanner.get_readed
- 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
-
- tk = nil if TkEND_OF_SCRIPT === tk
-
- if TkSYMBEG === tk then
- set_token_position tk.line_no, tk.char_no
-
- case tk1 = get_tk
- when TkId, TkOp, TkSTRING, TkDSTRING, TkSTAR, TkAMPER then
- if tk1.respond_to?(:name) then
- tk = Token(TkSYMBOL).set_text(":" + tk1.name)
- else
- tk = Token(TkSYMBOL).set_text(":" + tk1.text)
- end
-
- # 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
- tk = tk1
- end
- end
-
- # inform any listeners of our shiny new token
- @token_listeners.each do |obj|
- obj.add_token(tk)
- end if @token_listeners
-
- tk
- end
-
- ##
- # Reads and returns all tokens up to one of +tokens+. Leaves the matched
- # token in the token list.
-
- def get_tk_until(*tokens)
- read = []
-
- loop do
- tk = get_tk
- case tk when *tokens then unget_tk tk; break end
- read << tk
- end
-
- read
- end
-
- ##
- # Retrieves a String representation of the read tokens
-
- def get_tkread
- read = @read.join("")
- @read = []
- read
- end
-
- ##
- # Peek equivalent for get_tkread
-
- def peek_read
- @read.join('')
- end
-
- ##
- # Peek at the next token, but don't remove it from the stream
-
- def peek_tk
- unget_tk(tk = get_tk)
- tk
- end
-
- ##
- # Removes the token listener +obj+
-
- def remove_token_listener(obj)
- @token_listeners.delete(obj)
- end
-
- ##
- # Resets the tools
-
- def reset
- @read = []
- @tokens = []
- @unget_read = []
- @nest = 0
- end
-
- ##
- # Skips whitespace tokens including newlines if +skip_nl+ is true
-
- def skip_tkspace(skip_nl = true) # HACK dup
- tokens = []
-
- while TkSPACE === (tk = get_tk) or (skip_nl and TkNL === tk) do
- tokens.push tk
- end
-
- unget_tk tk
- tokens
- end
-
- ##
- # Has +obj+ listen to tokens
-
- def token_listener(obj)
- add_token_listener obj
- yield
- ensure
- remove_token_listener obj
- end
-
- ##
- # Returns +tk+ to the scanner
-
- def unget_tk(tk)
- @tokens.unshift tk
- @unget_read.unshift @read.pop
-
- # Remove this token from any listeners
- @token_listeners.each do |obj|
- obj.pop_token
- end if @token_listeners
-
- nil
- end
-
-end
-
-
diff --git a/ruby_1_9_3/lib/rdoc/parser/simple.rb b/ruby_1_9_3/lib/rdoc/parser/simple.rb
deleted file mode 100644
index 1e82eb5097..0000000000
--- a/ruby_1_9_3/lib/rdoc/parser/simple.rb
+++ /dev/null
@@ -1,49 +0,0 @@
-##
-# Parse a non-source file. We basically take the whole thing as one big
-# comment.
-
-class RDoc::Parser::Simple < RDoc::Parser
-
- parse_files_matching(//)
-
- attr_reader :content # :nodoc:
-
- ##
- # Prepare to parse a plain file
-
- def initialize(top_level, file_name, content, options, stats)
- super
-
- preprocess = RDoc::Markup::PreProcess.new @file_name, @options.rdoc_include
-
- preprocess.handle @content, @top_level
- end
-
- ##
- # Extract the file contents and attach them to the TopLevel as a comment
-
- def scan
- comment = remove_coding_comment @content
- comment = remove_private_comments comment
-
- @top_level.comment = comment
- @top_level.parser = self.class
- @top_level
- end
-
- ##
- # Removes comments wrapped in <tt>--/++</tt>
-
- def remove_private_comments text
- text.gsub(/^--\n.*?^\+\+/m, '').sub(/^--\n.*/m, '')
- end
-
- ##
- # Removes the encoding magic comment from +text+
-
- def remove_coding_comment text
- text.sub(/\A# .*coding[=:].*$/, '')
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/rdoc.rb b/ruby_1_9_3/lib/rdoc/rdoc.rb
deleted file mode 100644
index 95ba9ae8ab..0000000000
--- a/ruby_1_9_3/lib/rdoc/rdoc.rb
+++ /dev/null
@@ -1,520 +0,0 @@
-require 'rdoc'
-
-require 'rdoc/encoding'
-require 'rdoc/parser'
-
-# Simple must come first
-require 'rdoc/parser/simple'
-require 'rdoc/parser/ruby'
-require 'rdoc/parser/c'
-
-require 'rdoc/stats'
-require 'rdoc/options'
-
-require 'find'
-require 'fileutils'
-require 'time'
-
-##
-# 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 <tt>rdoc --help<tt> for details.
-#
-# = Plugins
-#
-# When you <tt>require 'rdoc/rdoc'</tt> RDoc looks for 'rdoc/discover' files
-# in your installed gems. This can be used to load alternate generators or
-# add additional preprocessor directives.
-#
-# You will want to wrap your plugin loading in an RDoc version check.
-# Something like:
-#
-# begin
-# gem 'rdoc', '~> 3'
-# require 'path/to/my/awesome/rdoc/plugin'
-# rescue Gem::LoadError
-# end
-#
-# The most obvious plugin type is a new output generator. See RDoc::Generator
-# for details.
-#
-# You can also hook into RDoc::Markup to add new directives (:nodoc: is a
-# directive). See RDoc::Markup::PreProcess::register for details.
-
-class RDoc::RDoc
-
- ##
- # File pattern to exclude
-
- attr_accessor :exclude
-
- ##
- # Generator instance used for creating output
-
- attr_accessor :generator
-
- ##
- # Hash of files and their last modified times.
-
- attr_reader :last_modified
-
- ##
- # RDoc options
-
- attr_accessor :options
-
- ##
- # Accessor for statistics. Available after each call to parse_files
-
- attr_reader :stats
-
- ##
- # This is the list of supported output generators
-
- GENERATORS = {}
-
- ##
- # Add +klass+ that can generate output after parsing
-
- def self.add_generator(klass)
- name = klass.name.sub(/^RDoc::Generator::/, '').downcase
- GENERATORS[name] = klass
- end
-
- ##
- # Active RDoc::RDoc instance
-
- def self.current
- @current
- end
-
- ##
- # Sets the active RDoc::RDoc instance
-
- def self.current=(rdoc)
- @current = rdoc
- end
-
- ##
- # Resets all internal state
-
- def self.reset
- RDoc::TopLevel.reset
- RDoc::Parser::C.reset
- end
-
- ##
- # Creates a new RDoc::RDoc instance. Call #document to parse files and
- # generate documentation.
-
- def initialize
- @current = nil
- @exclude = nil
- @generator = nil
- @last_modified = {}
- @old_siginfo = nil
- @options = nil
- @stats = nil
- end
-
- ##
- # Report an error message and exit
-
- def error(msg)
- raise RDoc::Error, msg
- end
-
- ##
- # Gathers a set of parseable files from the files and directories listed in
- # +files+.
-
- def gather_files files
- files = ["."] if files.empty?
-
- file_list = normalized_file_list files, true, @exclude
-
- file_list = file_list.uniq
-
- file_list = remove_unparseable file_list
- end
-
- ##
- # Turns RDoc from stdin into HTML
-
- def handle_pipe
- @html = RDoc::Markup::ToHtml.new
-
- out = @html.convert $stdin.read
-
- $stdout.write out
- end
-
- ##
- # Installs a siginfo handler that prints the current filename.
-
- def install_siginfo_handler
- return unless Signal.list.include? 'INFO'
-
- @old_siginfo = trap 'INFO' do
- puts @current if @current
- end
- 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(dir, force)
- flag_file = output_flag_file dir
-
- last = {}
-
- if @options.dry_run then
- # do nothing
- elsif File.exist? dir then
- error "#{dir} exists and is not a directory" unless File.directory? dir
-
- begin
- open flag_file do |io|
- unless force then
- Time.parse io.gets
-
- io.each do |line|
- file, time = line.split "\t", 2
- time = Time.parse(time) rescue next
- last[file] = time
- end
- end
- end
- rescue SystemCallError, TypeError
- error <<-ERROR
-
-Directory #{dir} already exists, but it looks like it isn't an RDoc directory.
-
-Because RDoc doesn't want to risk destroying any of your existing files,
-you'll need to specify a different output directory name (using the --op <dir>
-option)
-
- ERROR
- end unless @options.force_output
- else
- FileUtils.mkdir_p dir
- FileUtils.touch output_flag_file dir
- end
-
- last
- end
-
- ##
- # Update the flag file in an output directory.
-
- def update_output_dir(op_dir, time, last = {})
- return if @options.dry_run or not @options.update_output_dir
-
- open output_flag_file(op_dir), "w" do |f|
- f.puts time.rfc2822
- last.each do |n, t|
- f.puts "#{n}\t#{t.rfc2822}"
- end
- end
- 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
- # 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(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 explicitly.
-
- def normalized_file_list(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 rescue next
-
- case type = stat.ftype
- when "file" then
- next if last_modified = @last_modified[rel_file_name] and
- stat.mtime.to_i <= last_modified.to_i
-
- if force_doc or RDoc::Parser.can_parse(rel_file_name) then
- file_list << rel_file_name.sub(/^\.\//, '')
- @last_modified[rel_file_name] = stat.mtime
- end
- when "directory" then
- next if rel_file_name == "CVS" || rel_file_name == ".svn"
-
- dot_doc = File.join rel_file_name, RDoc::DOT_DOC_FILENAME
-
- if File.file? dot_doc then
- file_list << parse_dot_doc_file(rel_file_name, dot_doc)
- else
- file_list << list_files_in_directory(rel_file_name)
- end
- else
- raise RDoc::Error, "I can't deal with a #{type} #{rel_file_name}"
- end
- end
-
- file_list.flatten
- 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
- files = Dir.glob File.join(dir, "*")
-
- normalized_file_list files, false, @options.exclude
- end
-
- ##
- # Parses +filename+ and returns an RDoc::TopLevel
-
- def parse_file filename
- if defined?(Encoding) then
- encoding = @options.encoding
- filename = filename.encode encoding
- end
-
- @stats.add_file filename
-
- content = RDoc::Encoding.read_file filename, encoding
-
- return unless content
-
- top_level = RDoc::TopLevel.new filename
-
- parser = RDoc::Parser.for top_level, filename, content, @options, @stats
-
- return unless parser
-
- parser.scan
-
- # restart documentation for the classes & modules found
- top_level.classes_or_modules.each do |cm|
- cm.done_documenting = false
- end
-
- top_level
-
- rescue => e
- $stderr.puts <<-EOF
-Before reporting this, could you check that the file you're documenting
-has proper syntax:
-
- #{Gem.ruby} -c #{filename}
-
-RDoc is not a full Ruby parser and will fail when fed invalid ruby programs.
-
-The internal error was:
-
-\t(#{e.class}) #{e.message}
-
- EOF
-
- $stderr.puts e.backtrace.join("\n\t") if $DEBUG_RDOC
-
- raise e
- nil
- end
-
- ##
- # Parse each file on the command line, recursively entering directories.
-
- def parse_files files
- file_list = gather_files files
- @stats = RDoc::Stats.new file_list.size, @options.verbosity
-
- return [] if file_list.empty?
-
- file_info = []
-
- @stats.begin_adding
-
- file_info = file_list.map do |filename|
- @current = filename
- parse_file filename
- end.compact
-
- @stats.done_adding
-
- file_info
- end
-
- ##
- # Removes file extensions known to be unparseable from +files+
-
- def remove_unparseable files
- files.reject do |file|
- file =~ /\.(?:class|eps|erb|scpt\.txt|ttf|yml)$/i
- end
- end
-
- ##
- # Generates documentation or a coverage report depending upon the settings
- # in +options+.
- #
- # +options+ can be either an RDoc::Options instance or an array of strings
- # equivalent to the strings that would be passed on the command line like
- # <tt>%w[-q -o doc -t My\ Doc\ Title]</tt>. #document will automatically
- # call RDoc::Options#finish if an options instance was given.
- #
- # For a list of options, see either RDoc::Options or <tt>rdoc --help</tt>.
- #
- # By default, output will be stored in a directory called "doc" below the
- # current directory, so make sure you're somewhere writable before invoking.
-
- def document options
- RDoc::RDoc.reset
-
- if RDoc::Options === options then
- @options = options
- @options.finish
- else
- @options = RDoc::Options.new
- @options.parse options
- end
-
- if @options.pipe then
- handle_pipe
- exit
- end
-
- @exclude = @options.exclude
-
- unless @options.coverage_report then
- @last_modified = setup_output_dir @options.op_dir, @options.force_update
- end
-
- @start_time = Time.now
-
- file_info = parse_files @options.files
-
- @options.default_title = "RDoc Documentation"
-
- RDoc::TopLevel.complete @options.visibility
-
- @stats.coverage_level = @options.coverage_report
-
- if @options.coverage_report then
- puts
-
- puts @stats.report
- elsif file_info.empty? then
- $stderr.puts "\nNo newer files." unless @options.quiet
- else
- gen_klass = @options.generator
-
- @generator = gen_klass.new @options
-
- generate file_info
- end
-
- if @stats and (@options.coverage_report or not @options.quiet) then
- puts
- puts @stats.summary
- end
-
- exit @stats.fully_documented? if @options.coverage_report
- end
-
- ##
- # Generates documentation for +file_info+ (from #parse_files) into the
- # output dir using the generator selected
- # by the RDoc options
-
- def generate file_info
- Dir.chdir @options.op_dir do
- begin
- self.class.current = self
-
- unless @options.quiet then
- $stderr.puts "\nGenerating #{@generator.class.name.sub(/^.*::/, '')} format into #{Dir.pwd}..."
- end
-
- @generator.generate file_info
- update_output_dir '.', @start_time, @last_modified
- ensure
- self.class.current = nil
- end
- end
- end
-
- ##
- # Removes a siginfo handler and replaces the previous
-
- def remove_siginfo_handler
- return unless Signal.list.key? 'INFO'
-
- handler = @old_siginfo || 'DEFAULT'
-
- trap 'INFO', handler
- end
-
-end
-
-begin
- require 'rubygems'
-
- if Gem.respond_to? :find_files then
- rdoc_extensions = Gem.find_files 'rdoc/discover'
-
- rdoc_extensions.each do |extension|
- begin
- load extension
- rescue => e
- warn "error loading #{extension.inspect}: #{e.message} (#{e.class})"
- warn "\t#{e.backtrace.join "\n\t"}" if $DEBUG
- end
- end
- end
-rescue LoadError
-end
-
-# require built-in generators after discovery in case they've been replaced
-require 'rdoc/generator/darkfish'
-require 'rdoc/generator/ri'
-
diff --git a/ruby_1_9_3/lib/rdoc/require.rb b/ruby_1_9_3/lib/rdoc/require.rb
deleted file mode 100644
index 65d3d464da..0000000000
--- a/ruby_1_9_3/lib/rdoc/require.rb
+++ /dev/null
@@ -1,53 +0,0 @@
-require 'rdoc/code_object'
-
-##
-# A file loaded by \#require
-
-class RDoc::Require < RDoc::CodeObject
-
- ##
- # Name of the required file
-
- attr_accessor :name
-
- ##
- # Creates a new Require that loads +name+ with +comment+
-
- def initialize(name, comment)
- super()
- @name = name.gsub(/'|"/, "") #'
- @top_level = nil
- self.comment = comment
- end
-
- def inspect # :nodoc:
- "#<%s:0x%x require '%s' in %s>" % [
- self.class,
- object_id,
- @name,
- parent_file_name,
- ]
- end
-
- def to_s # :nodoc:
- "require #{name} in: #{parent}"
- end
-
- ##
- # The RDoc::TopLevel corresponding to this require, or +nil+ if not found.
-
- def top_level
- @top_level ||= begin
- tl = RDoc::TopLevel.all_files_hash[name + '.rb']
-
- if tl.nil? and RDoc::TopLevel.all_files.first.full_name =~ %r(^lib/) then
- # second chance
- tl = RDoc::TopLevel.all_files_hash['lib/' + name + '.rb']
- end
-
- tl
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/ri.rb b/ruby_1_9_3/lib/rdoc/ri.rb
deleted file mode 100644
index 17da3fbe83..0000000000
--- a/ruby_1_9_3/lib/rdoc/ri.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-require 'rdoc'
-
-##
-# Namespace for the ri command line tool's implementation.
-#
-# See <tt>ri --help</tt> for details.
-
-module RDoc::RI
-
- ##
- # Base RI error class
-
- class Error < RDoc::Error; end
-
-end
-
-require 'rdoc/ri/store'
-
diff --git a/ruby_1_9_3/lib/rdoc/ri/driver.rb b/ruby_1_9_3/lib/rdoc/ri/driver.rb
deleted file mode 100644
index 26304dca96..0000000000
--- a/ruby_1_9_3/lib/rdoc/ri/driver.rb
+++ /dev/null
@@ -1,1178 +0,0 @@
-require 'abbrev'
-require 'optparse'
-
-begin
- require 'readline'
-rescue LoadError
-end
-
-begin
- require 'win32console'
-rescue LoadError
-end
-
-require 'rdoc/ri'
-require 'rdoc/ri/paths'
-require 'rdoc/markup'
-require 'rdoc/markup/formatter'
-require 'rdoc/text'
-
-##
-# For RubyGems backwards compatibility
-
-require 'rdoc/ri/formatter'
-
-##
-# The RI driver implements the command-line ri tool.
-#
-# The driver supports:
-# * loading RI data from:
-# * Ruby's standard library
-# * RubyGems
-# * ~/.rdoc
-# * A user-supplied directory
-# * Paging output (uses RI_PAGER environment variable, PAGER environment
-# variable or the less, more and pager programs)
-# * Interactive mode with tab-completion
-# * Abbreviated names (ri Zl shows Zlib documentation)
-# * Colorized output
-# * Merging output from multiple RI data sources
-
-class RDoc::RI::Driver
-
- ##
- # Base Driver error class
-
- class Error < RDoc::RI::Error; end
-
- ##
- # Raised when a name isn't found in the ri data stores
-
- class NotFoundError < Error
-
- ##
- # Name that wasn't found
-
- alias name message
-
- def message # :nodoc:
- "Nothing known about #{super}"
- end
- end
-
- ##
- # An RDoc::RI::Store for each entry in the RI path
-
- attr_accessor :stores
-
- ##
- # Controls the user of the pager vs $stdout
-
- attr_accessor :use_stdout
-
- ##
- # Default options for ri
-
- def self.default_options
- options = {}
- options[:use_stdout] = !$stdout.tty?
- options[:width] = 72
- options[:interactive] = false
- options[:use_cache] = true
- options[:profile] = false
-
- # By default all standard paths are used.
- options[:use_system] = true
- options[:use_site] = true
- options[:use_home] = true
- options[:use_gems] = true
- options[:extra_doc_dirs] = []
-
- return options
- end
-
- ##
- # Dump +data_path+ using pp
-
- def self.dump data_path
- require 'pp'
-
- open data_path, 'rb' do |io|
- pp Marshal.load(io.read)
- end
- end
-
- ##
- # Parses +argv+ and returns a Hash of options
-
- def self.process_args argv
- options = default_options
-
- opts = OptionParser.new do |opt|
- opt.accept File do |file,|
- File.readable?(file) and not File.directory?(file) and file
- end
-
- opt.program_name = File.basename $0
- opt.version = RDoc::VERSION
- opt.release = nil
- opt.summary_indent = ' ' * 4
-
- opt.banner = <<-EOT
-Usage: #{opt.program_name} [options] [names...]
-
-Where name can be:
-
- Class | Class::method | Class#method | Class.method | method
-
-All class names may be abbreviated to their minimum unambiguous form. If a name
-is ambiguous, all valid options will be listed.
-
-A '.' matches either class or instance methods, while #method
-matches only instance and ::method matches only class methods.
-
-For example:
-
- #{opt.program_name} Fil
- #{opt.program_name} File
- #{opt.program_name} File.new
- #{opt.program_name} zip
-
-Note that shell quoting or escaping may be required for method names containing
-punctuation:
-
- #{opt.program_name} 'Array.[]'
- #{opt.program_name} compact\\!
-
-To see the default directories ri will search, run:
-
- #{opt.program_name} --list-doc-dirs
-
-Specifying the --system, --site, --home, --gems or --doc-dir options will
-limit ri to searching only the specified directories.
-
-Options may also be set in the 'RI' environment variable.
- EOT
-
- opt.separator nil
- opt.separator "Options:"
-
- opt.separator nil
-
- formatters = RDoc::Markup.constants.grep(/^To[A-Z][a-z]+$/).sort
- formatters = formatters.sort.map do |formatter|
- formatter.to_s.sub('To', '').downcase
- end
-
- opt.on("--format=NAME", "-f",
- "Uses the selected formatter. The default",
- "formatter is bs for paged output and ansi",
- "otherwise. Valid formatters are:",
- formatters.join(' '), formatters) do |value|
- options[:formatter] = RDoc::Markup.const_get "To#{value.capitalize}"
- end
-
- opt.separator nil
-
- opt.on("--no-pager", "-T",
- "Send output directly to stdout,",
- "rather than to a pager.") do
- options[:use_stdout] = true
- end
-
- opt.separator nil
-
- opt.on("--width=WIDTH", "-w", OptionParser::DecimalInteger,
- "Set the width of the output.") do |value|
- options[:width] = value
- end
-
- opt.separator nil
-
- opt.on("--interactive", "-i",
- "In interactive mode you can repeatedly",
- "look up methods with autocomplete.") do
- options[:interactive] = true
- end
-
- opt.separator nil
-
- opt.on("--list", "-l",
- "List classes ri knows about.") do
- options[:list] = true
- end
-
- opt.separator nil
-
- opt.on("--[no-]profile",
- "Run with the ruby profiler") do |value|
- options[:profile] = value
- end
-
- opt.separator nil
- opt.separator "Data source options:"
- opt.separator nil
-
- opt.on("--list-doc-dirs",
- "List the directories from which ri will",
- "source documentation on stdout and exit.") do
- options[:list_doc_dirs] = true
- end
-
- opt.separator nil
-
- opt.on("--doc-dir=DIRNAME", "-d", Array,
- "List of directories from which to source",
- "documentation in addition to the standard",
- "directories. May be repeated.") do |value|
- value.each do |dir|
- unless File.directory? dir then
- raise OptionParser::InvalidArgument, "#{dir} is not a directory"
- end
-
- options[:extra_doc_dirs] << File.expand_path(dir)
- end
- end
-
- opt.separator nil
-
- opt.on("--no-standard-docs",
- "Do not include documentation from",
- "the Ruby standard library, site_lib,",
- "installed gems, or ~/.rdoc.",
- "Use with --doc-dir") do
- options[:use_system] = false
- options[:use_site] = false
- options[:use_gems] = false
- options[:use_home] = false
- end
-
- opt.separator nil
-
- opt.on("--[no-]system",
- "Include documentation from Ruby's standard",
- "library. Defaults to true.") do |value|
- options[:use_system] = value
- end
-
- opt.separator nil
-
- opt.on("--[no-]site",
- "Include documentation from libraries",
- "installed in site_lib.",
- "Defaults to true.") do |value|
- options[:use_site] = value
- end
-
- opt.separator nil
-
- opt.on("--[no-]gems",
- "Include documentation from RubyGems.",
- "Defaults to true.") do |value|
- options[:use_gems] = value
- end
-
- opt.separator nil
-
- opt.on("--[no-]home",
- "Include documentation stored in ~/.rdoc.",
- "Defaults to true.") do |value|
- options[:use_home] = value
- end
-
- opt.separator nil
- opt.separator "Debug options:"
- opt.separator nil
-
- opt.on("--dump=CACHE", File,
- "Dumps data from an ri cache or data file") do |value|
- options[:dump_path] = value
- end
- end
-
- argv = ENV['RI'].to_s.split.concat argv
-
- opts.parse! argv
-
- options[:names] = argv
-
- options[:use_stdout] ||= !$stdout.tty?
- options[:use_stdout] ||= options[:interactive]
- options[:width] ||= 72
-
- options
-
- rescue OptionParser::InvalidArgument, OptionParser::InvalidOption => e
- puts opts
- puts
- puts e
- exit 1
- end
-
- ##
- # Runs the ri command line executable using +argv+
-
- def self.run argv = ARGV
- options = process_args argv
-
- if options[:dump_path] then
- dump options[:dump_path]
- return
- end
-
- ri = new options
- ri.run
- end
-
- ##
- # Creates a new driver using +initial_options+ from ::process_args
-
- def initialize initial_options = {}
- @paging = false
- @classes = nil
-
- options = self.class.default_options.update(initial_options)
-
- @formatter_klass = options[:formatter]
-
- require 'profile' if options[:profile]
-
- @names = options[:names]
- @list = options[:list]
-
- @doc_dirs = []
- @stores = []
-
- RDoc::RI::Paths.each(options[:use_system], options[:use_site],
- options[:use_home], options[:use_gems],
- *options[:extra_doc_dirs]) do |path, type|
- @doc_dirs << path
-
- store = RDoc::RI::Store.new path, type
- store.load_cache
- @stores << store
- end
-
- @list_doc_dirs = options[:list_doc_dirs]
-
- @interactive = options[:interactive]
- @use_stdout = options[:use_stdout]
- end
-
- ##
- # Adds paths for undocumented classes +also_in+ to +out+
-
- def add_also_in out, also_in
- return if also_in.empty?
-
- out << RDoc::Markup::Rule.new(1)
- out << RDoc::Markup::Paragraph.new("Also found in:")
-
- paths = RDoc::Markup::Verbatim.new
- also_in.each do |store|
- paths.parts.push store.friendly_path, "\n"
- end
- out << paths
- end
-
- ##
- # Adds a class header to +out+ for class +name+ which is described in
- # +classes+.
-
- def add_class out, name, classes
- heading = if classes.all? { |klass| klass.module? } then
- name
- else
- superclass = classes.map do |klass|
- klass.superclass unless klass.module?
- end.compact.shift || 'Object'
-
- superclass = superclass.full_name unless String === superclass
-
- "#{name} < #{superclass}"
- end
-
- out << RDoc::Markup::Heading.new(1, heading)
- out << RDoc::Markup::BlankLine.new
- end
-
- ##
- # Adds "(from ...)" to +out+ for +store+
-
- def add_from out, store
- out << RDoc::Markup::Paragraph.new("(from #{store.friendly_path})")
- end
-
- ##
- # Adds +includes+ to +out+
-
- def add_includes out, includes
- return if includes.empty?
-
- out << RDoc::Markup::Rule.new(1)
- out << RDoc::Markup::Heading.new(1, "Includes:")
-
- includes.each do |modules, store|
- if modules.length == 1 then
- include = modules.first
- name = include.name
- path = store.friendly_path
- out << RDoc::Markup::Paragraph.new("#{name} (from #{path})")
-
- if include.comment then
- out << RDoc::Markup::BlankLine.new
- out << include.comment
- end
- else
- out << RDoc::Markup::Paragraph.new("(from #{store.friendly_path})")
-
- wout, with = modules.partition { |incl| incl.comment.empty? }
-
- out << RDoc::Markup::BlankLine.new unless with.empty?
-
- with.each do |incl|
- out << RDoc::Markup::Paragraph.new(incl.name)
- out << RDoc::Markup::BlankLine.new
- out << incl.comment
- end
-
- unless wout.empty? then
- verb = RDoc::Markup::Verbatim.new
-
- wout.each do |incl|
- verb.push incl.name, "\n"
- end
-
- out << verb
- end
- end
- end
- end
-
- ##
- # Adds a list of +methods+ to +out+ with a heading of +name+
-
- def add_method_list out, methods, name
- return if methods.empty?
-
- out << RDoc::Markup::Heading.new(1, "#{name}:")
- out << RDoc::Markup::BlankLine.new
-
- if @use_stdout and !@interactive
- out.push(*methods.map do |method|
- RDoc::Markup::Verbatim.new method
- end)
- else
- out << RDoc::Markup::IndentedParagraph.new(2, methods.join(', '))
- end
-
- out << RDoc::Markup::BlankLine.new
- end
-
- ##
- # Returns ancestor classes of +klass+
-
- def ancestors_of klass
- ancestors = []
-
- unexamined = [klass]
- seen = []
-
- loop do
- break if unexamined.empty?
- current = unexamined.shift
- seen << current
-
- stores = classes[current]
-
- break unless stores and not stores.empty?
-
- klasses = stores.map do |store|
- store.ancestors[current]
- end.flatten.uniq
-
- klasses = klasses - seen
-
- ancestors.push(*klasses)
- unexamined.push(*klasses)
- end
-
- ancestors.reverse
- end
-
- ##
- # For RubyGems backwards compatibility
-
- def class_cache # :nodoc:
- end
-
- ##
- # Builds a RDoc::Markup::Document from +found+, +klasess+ and +includes+
-
- def class_document name, found, klasses, includes
- also_in = []
-
- out = RDoc::Markup::Document.new
-
- add_class out, name, klasses
-
- add_includes out, includes
-
- found.each do |store, klass|
- comment = klass.comment
- # TODO the store's cache should always return an empty Array
- class_methods = store.class_methods[klass.full_name] || []
- instance_methods = store.instance_methods[klass.full_name] || []
- attributes = store.attributes[klass.full_name] || []
-
- if comment.empty? and
- instance_methods.empty? and class_methods.empty? then
- also_in << store
- next
- end
-
- add_from out, store
-
- unless comment.empty? then
- out << RDoc::Markup::Rule.new(1)
-
- if comment.merged? then
- parts = comment.parts
- parts = parts.zip [RDoc::Markup::BlankLine.new] * parts.length
- parts.flatten!
- parts.pop
-
- out.push(*parts)
- else
- out << comment
- end
- end
-
- if class_methods or instance_methods or not klass.constants.empty? then
- out << RDoc::Markup::Rule.new(1)
- end
-
- unless klass.constants.empty? then
- out << RDoc::Markup::Heading.new(1, "Constants:")
- out << RDoc::Markup::BlankLine.new
- list = RDoc::Markup::List.new :NOTE
-
- constants = klass.constants.sort_by { |constant| constant.name }
-
- list.push(*constants.map do |constant|
- parts = constant.comment.parts if constant.comment
- parts << RDoc::Markup::Paragraph.new('[not documented]') if
- parts.empty?
-
- RDoc::Markup::ListItem.new(constant.name, *parts)
- end)
-
- out << list
- out << RDoc::Markup::BlankLine.new
- end
-
- add_method_list out, class_methods, 'Class methods'
- add_method_list out, instance_methods, 'Instance methods'
- add_method_list out, attributes, 'Attributes'
- end
-
- add_also_in out, also_in
-
- out
- end
-
- ##
- # Hash mapping a known class or module to the stores it can be loaded from
-
- def classes
- return @classes if @classes
-
- @classes = {}
-
- @stores.each do |store|
- store.cache[:modules].each do |mod|
- # using default block causes searched-for modules to be added
- @classes[mod] ||= []
- @classes[mod] << store
- end
- end
-
- @classes
- end
-
- ##
- # Returns the stores wherin +name+ is found along with the classes and
- # includes that match it
-
- def classes_and_includes_for name
- klasses = []
- includes = []
-
- found = @stores.map do |store|
- begin
- klass = store.load_class name
- klasses << klass
- includes << [klass.includes, store] if klass.includes
- [store, klass]
- rescue Errno::ENOENT
- end
- end.compact
-
- includes.reject! do |modules,| modules.empty? end
-
- [found, klasses, includes]
- end
-
- ##
- # Completes +name+ based on the caches. For Readline
-
- def complete name
- klasses = classes.keys
- completions = []
-
- klass, selector, method = parse_name name
-
- # may need to include Foo when given Foo::
- klass_name = method ? name : klass
-
- if name !~ /#|\./ then
- completions = klasses.grep(/^#{Regexp.escape klass_name}[^:]*$/)
- completions.concat klasses.grep(/^#{Regexp.escape name}[^:]*$/) if
- name =~ /::$/
-
- completions << klass if classes.key? klass # to complete a method name
- elsif selector then
- completions << klass if classes.key? klass
- elsif classes.key? klass_name then
- completions << klass_name
- end
-
- if completions.include? klass and name =~ /#|\.|::/ then
- methods = list_methods_matching name
-
- if not methods.empty? then
- # remove Foo if given Foo:: and a method was found
- completions.delete klass
- elsif selector then
- # replace Foo with Foo:: as given
- completions.delete klass
- completions << "#{klass}#{selector}"
- end
-
- completions.push(*methods)
- end
-
- completions.sort.uniq
- end
-
- ##
- # Converts +document+ to text and writes it to the pager
-
- def display document
- page do |io|
- text = document.accept formatter(io)
-
- io.write text
- end
- end
-
- ##
- # Outputs formatted RI data for class +name+. Groups undocumented classes
-
- def display_class name
- return if name =~ /#|\./
-
- found, klasses, includes = classes_and_includes_for name
-
- return if found.empty?
-
- out = class_document name, found, klasses, includes
-
- display out
- end
-
- ##
- # Outputs formatted RI data for method +name+
-
- def display_method name
- found = load_methods_matching name
-
- raise NotFoundError, name if found.empty?
-
- filtered = filter_methods found, name
-
- out = method_document name, filtered
-
- display out
- end
-
- ##
- # Outputs formatted RI data for the class or method +name+.
- #
- # Returns true if +name+ was found, false if it was not an alternative could
- # be guessed, raises an error if +name+ couldn't be guessed.
-
- def display_name name
- return true if display_class name
-
- display_method name if name =~ /::|#|\./
-
- true
- rescue NotFoundError
- matches = list_methods_matching name if name =~ /::|#|\./
- matches = classes.keys.grep(/^#{name}/) if matches.empty?
-
- raise if matches.empty?
-
- page do |io|
- io.puts "#{name} not found, maybe you meant:"
- io.puts
- io.puts matches.join("\n")
- end
-
- false
- end
-
- ##
- # Displays each name in +name+
-
- def display_names names
- names.each do |name|
- name = expand_name name
-
- display_name name
- end
- end
-
- ##
- # Expands abbreviated klass +klass+ into a fully-qualified class. "Zl::Da"
- # will be expanded to Zlib::DataError.
-
- def expand_class klass
- klass.split('::').inject '' do |expanded, klass_part|
- expanded << '::' unless expanded.empty?
- short = expanded << klass_part
-
- subset = classes.keys.select do |klass_name|
- klass_name =~ /^#{expanded}[^:]*$/
- end
-
- abbrevs = Abbrev.abbrev subset
-
- expanded = abbrevs[short]
-
- raise NotFoundError, short unless expanded
-
- expanded.dup
- end
- end
-
- ##
- # Expands the class portion of +name+ into a fully-qualified class. See
- # #expand_class.
-
- def expand_name name
- klass, selector, method = parse_name name
-
- return [selector, method].join if klass.empty?
-
- "#{expand_class klass}#{selector}#{method}"
- end
-
- ##
- # Filters the methods in +found+ trying to find a match for +name+.
-
- def filter_methods found, name
- regexp = name_regexp name
-
- filtered = found.find_all do |store, methods|
- methods.any? { |method| method.full_name =~ regexp }
- end
-
- return filtered unless filtered.empty?
-
- found
- end
-
- ##
- # Yields items matching +name+ including the store they were found in, the
- # class being searched for, the class they were found in (an ancestor) the
- # types of methods to look up (from #method_type), and the method name being
- # searched for
-
- def find_methods name
- klass, selector, method = parse_name name
-
- types = method_type selector
-
- klasses = nil
- ambiguous = klass.empty?
-
- if ambiguous then
- klasses = classes.keys
- else
- klasses = ancestors_of klass
- klasses.unshift klass
- end
-
- methods = []
-
- klasses.each do |ancestor|
- ancestors = classes[ancestor]
-
- next unless ancestors
-
- klass = ancestor if ambiguous
-
- ancestors.each do |store|
- methods << [store, klass, ancestor, types, method]
- end
- end
-
- methods = methods.sort_by do |_, k, a, _, m|
- [k, a, m].compact
- end
-
- methods.each do |item|
- yield(*item) # :yields: store, klass, ancestor, types, method
- end
-
- self
- end
-
- ##
- # Creates a new RDoc::Markup::Formatter. If a formatter is given with -f,
- # use it. If we're outputting to a pager, use bs, otherwise ansi.
-
- def formatter(io)
- if @formatter_klass then
- @formatter_klass.new
- elsif paging? or !io.tty? then
- RDoc::Markup::ToBs.new
- else
- RDoc::Markup::ToAnsi.new
- end
- end
-
- ##
- # Runs ri interactively using Readline if it is available.
-
- def interactive
- puts "\nEnter the method name you want to look up."
-
- if defined? Readline then
- Readline.completion_proc = method :complete
- puts "You can use tab to autocomplete."
- end
-
- puts "Enter a blank line to exit.\n\n"
-
- loop do
- name = if defined? Readline then
- Readline.readline ">> "
- else
- print ">> "
- $stdin.gets
- end
-
- return if name.nil? or name.empty?
-
- name = expand_name name.strip
-
- begin
- display_name name
- rescue NotFoundError => e
- puts e.message
- end
- end
-
- rescue Interrupt
- exit
- end
-
- ##
- # Is +file+ in ENV['PATH']?
-
- def in_path? file
- return true if file =~ %r%\A/% and File.exist? file
-
- ENV['PATH'].split(File::PATH_SEPARATOR).any? do |path|
- File.exist? File.join(path, file)
- end
- end
-
- ##
- # Lists classes known to ri starting with +names+. If +names+ is empty all
- # known classes are shown.
-
- def list_known_classes names = []
- classes = []
-
- stores.each do |store|
- classes << store.modules
- end
-
- classes = classes.flatten.uniq.sort
-
- unless names.empty? then
- filter = Regexp.union names.map { |name| /^#{name}/ }
-
- classes = classes.grep filter
- end
-
- page do |io|
- if paging? or io.tty? then
- if names.empty? then
- io.puts "Classes and Modules known to ri:"
- else
- io.puts "Classes and Modules starting with #{names.join ', '}:"
- end
- io.puts
- end
-
- io.puts classes.join("\n")
- end
- end
-
- ##
- # Returns an Array of methods matching +name+
-
- def list_methods_matching name
- found = []
-
- find_methods name do |store, klass, ancestor, types, method|
- if types == :instance or types == :both then
- methods = store.instance_methods[ancestor]
-
- if methods then
- matches = methods.grep(/^#{Regexp.escape method.to_s}/)
-
- matches = matches.map do |match|
- "#{klass}##{match}"
- end
-
- found.push(*matches)
- end
- end
-
- if types == :class or types == :both then
- methods = store.class_methods[ancestor]
-
- next unless methods
- matches = methods.grep(/^#{Regexp.escape method.to_s}/)
-
- matches = matches.map do |match|
- "#{klass}::#{match}"
- end
-
- found.push(*matches)
- end
- end
-
- found.uniq
- end
-
- ##
- # Loads RI data for method +name+ on +klass+ from +store+. +type+ and
- # +cache+ indicate if it is a class or instance method.
-
- def load_method store, cache, klass, type, name
- methods = store.send(cache)[klass]
-
- return unless methods
-
- method = methods.find do |method_name|
- method_name == name
- end
-
- return unless method
-
- store.load_method klass, "#{type}#{method}"
- end
-
- ##
- # Returns an Array of RI data for methods matching +name+
-
- def load_methods_matching name
- found = []
-
- find_methods name do |store, klass, ancestor, types, method|
- methods = []
-
- methods << load_method(store, :class_methods, ancestor, '::', method) if
- [:class, :both].include? types
-
- methods << load_method(store, :instance_methods, ancestor, '#', method) if
- [:instance, :both].include? types
-
- found << [store, methods.compact]
- end
-
- found.reject do |path, methods| methods.empty? end
- end
-
- ##
- # Builds a RDoc::Markup::Document from +found+, +klasess+ and +includes+
-
- def method_document name, filtered
- out = RDoc::Markup::Document.new
-
- out << RDoc::Markup::Heading.new(1, name)
- out << RDoc::Markup::BlankLine.new
-
- filtered.each do |store, methods|
- methods.each do |method|
- out << RDoc::Markup::Paragraph.new("(from #{store.friendly_path})")
-
- unless name =~ /^#{Regexp.escape method.parent_name}/ then
- out << RDoc::Markup::Heading.new(3, "Implementation from #{method.parent_name}")
- end
- out << RDoc::Markup::Rule.new(1)
-
- if method.arglists then
- arglists = method.arglists.chomp.split "\n"
- arglists = arglists.map { |line| line + "\n" }
- out << RDoc::Markup::Verbatim.new(*arglists)
- out << RDoc::Markup::Rule.new(1)
- end
-
- out << RDoc::Markup::BlankLine.new
- out << method.comment
- out << RDoc::Markup::BlankLine.new
- end
- end
-
- out
- end
-
- ##
- # Returns the type of method (:both, :instance, :class) for +selector+
-
- def method_type selector
- case selector
- when '.', nil then :both
- when '#' then :instance
- else :class
- end
- end
-
- ##
- # Returns a regular expression for +name+ that will match an
- # RDoc::AnyMethod's name.
-
- def name_regexp name
- klass, type, name = parse_name name
-
- case type
- when '#', '::' then
- /^#{klass}#{type}#{Regexp.escape name}$/
- else
- /^#{klass}(#|::)#{Regexp.escape name}$/
- end
- end
-
- ##
- # Paginates output through a pager program.
-
- def page
- if pager = setup_pager then
- begin
- yield pager
- ensure
- pager.close
- end
- else
- yield $stdout
- end
- rescue Errno::EPIPE
- ensure
- @paging = false
- end
-
- ##
- # Are we using a pager?
-
- def paging?
- @paging
- end
-
- ##
- # Extracts the class, selector and method name parts from +name+ like
- # Foo::Bar#baz.
- #
- # NOTE: Given Foo::Bar, Bar is considered a class even though it may be a
- # method
-
- def parse_name name
- parts = name.split(/(::|#|\.)/)
-
- if parts.length == 1 then
- if parts.first =~ /^[a-z]|^([%&*+\/<>^`|~-]|\+@|-@|<<|<=>?|===?|=>|=~|>>|\[\]=?|~@)$/ then
- type = '.'
- meth = parts.pop
- else
- type = nil
- meth = nil
- end
- elsif parts.length == 2 or parts.last =~ /::|#|\./ then
- type = parts.pop
- meth = nil
- elsif parts[-2] != '::' or parts.last !~ /^[A-Z]/ then
- meth = parts.pop
- type = parts.pop
- end
-
- klass = parts.join
-
- [klass, type, meth]
- end
-
- ##
- # Looks up and displays ri data according to the options given.
-
- def run
- if @list_doc_dirs then
- puts @doc_dirs
- elsif @list then
- list_known_classes @names
- elsif @interactive or @names.empty? then
- interactive
- else
- display_names @names
- end
- rescue NotFoundError => e
- abort e.message
- end
-
- ##
- # Sets up a pager program to pass output through. Tries the RI_PAGER and
- # PAGER environment variables followed by pager, less then more.
-
- def setup_pager
- return if @use_stdout
-
- pagers = [ENV['RI_PAGER'], ENV['PAGER'], 'pager', 'less', 'more']
-
- pagers.compact.uniq.each do |pager|
- next unless pager
-
- pager_cmd = pager.split.first
-
- next unless in_path? pager_cmd
-
- io = IO.popen(pager, 'w') rescue next
-
- next if $? and $?.exited? # pager didn't work
-
- @paging = true
-
- return io
- end
-
- @use_stdout = true
-
- nil
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/ri/formatter.rb b/ruby_1_9_3/lib/rdoc/ri/formatter.rb
deleted file mode 100644
index 84d37a9d31..0000000000
--- a/ruby_1_9_3/lib/rdoc/ri/formatter.rb
+++ /dev/null
@@ -1,5 +0,0 @@
-##
-# For RubyGems backwards compatibility
-
-module RDoc::RI::Formatter # :nodoc:
-end
diff --git a/ruby_1_9_3/lib/rdoc/ri/paths.rb b/ruby_1_9_3/lib/rdoc/ri/paths.rb
deleted file mode 100644
index a3c65bf928..0000000000
--- a/ruby_1_9_3/lib/rdoc/ri/paths.rb
+++ /dev/null
@@ -1,128 +0,0 @@
-require 'rdoc/ri'
-
-##
-# The directories where ri data lives.
-
-module RDoc::RI::Paths
-
- #:stopdoc:
- require 'rbconfig'
-
- version = RbConfig::CONFIG['ruby_version']
-
- base = if RbConfig::CONFIG.key? 'ridir' then
- File.join RbConfig::CONFIG['ridir'], version
- else
- File.join RbConfig::CONFIG['datadir'], 'ri', version
- end
-
- SYSDIR = File.join base, "system"
- SITEDIR = File.join base, "site"
-
- homedir = begin
- File.expand_path('~')
- rescue ArgumentError
- end
-
- homedir ||= ENV['HOME'] ||
- ENV['USERPROFILE'] || ENV['HOMEPATH'] # for 1.8 compatibility
-
- HOMEDIR = if homedir then
- File.join homedir, ".rdoc"
- end
- #:startdoc:
-
- @gemdirs = nil
-
- ##
- # Iterates over each selected path yielding the directory and type.
- #
- # Yielded types:
- # :system:: Where Ruby's ri data is stored. Yielded when +system+ is
- # true
- # :site:: Where ri for installed libraries are stored. Yielded when
- # +site+ is true. Normally no ri data is stored here.
- # :home:: ~/.rdoc. Yielded when +home+ is true.
- # :gem:: ri data for an installed gem. Yielded when +gems+ is true.
- # :extra:: ri data directory from the command line. Yielded for each
- # entry in +extra_dirs+
-
- def self.each system, site, home, gems, *extra_dirs # :yields: directory, type
- extra_dirs.each do |dir|
- yield dir, :extra
- end
-
- yield SYSDIR, :system if system
- yield SITEDIR, :site if site
- yield HOMEDIR, :home if home and HOMEDIR
-
- gemdirs.each do |dir|
- yield dir, :gem
- end if gems
-
- nil
- end
-
- ##
- # The latest installed gems' ri directories
-
- def self.gemdirs
- return @gemdirs if @gemdirs
-
- require 'rubygems' unless defined?(Gem)
-
- # 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
- rescue LoadError
- @gemdirs = []
- end
-
- ##
- # Returns existing directories from the selected documentation directories
- # as an Array.
- #
- # See also ::each
-
- def self.path(system, site, home, gems, *extra_dirs)
- path = raw_path system, site, home, gems, *extra_dirs
-
- path.select { |directory| File.directory? directory }
- end
-
- ##
- # Returns selected documentation directories including nonexistent
- # directories.
- #
- # See also ::each
-
- def self.raw_path(system, site, home, gems, *extra_dirs)
- path = []
-
- each(system, site, home, gems, *extra_dirs) do |dir, type|
- path << dir
- end
-
- path.compact
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/ri/store.rb b/ruby_1_9_3/lib/rdoc/ri/store.rb
deleted file mode 100644
index fe4ccc244d..0000000000
--- a/ruby_1_9_3/lib/rdoc/ri/store.rb
+++ /dev/null
@@ -1,358 +0,0 @@
-require 'rdoc/code_objects'
-require 'fileutils'
-
-##
-# A set of ri data.
-#
-# The store manages reading and writing ri data for a project (gem, path,
-# etc.) and maintains a cache of methods, classes and ancestors in the
-# store.
-#
-# The store maintains a #cache of its contents for faster lookup. After
-# adding items to the store it must be flushed using #save_cache. The cache
-# contains the following structures:
-#
-# @cache = {
-# :class_methods => {}, # class name => class methods
-# :instance_methods => {}, # class name => instance methods
-# :attributes => {}, # class name => attributes
-# :modules => [], # classes and modules in this store
-# :ancestors => {}, # class name => ancestor names
-# }
-#--
-# TODO need to store the list of files and prune classes
-
-class RDoc::RI::Store
-
- ##
- # If true this Store will not write any files
-
- attr_accessor :dry_run
-
- ##
- # Path this store reads or writes
-
- attr_accessor :path
-
- ##
- # Type of ri datastore this was loaded from. See RDoc::RI::Driver,
- # RDoc::RI::Paths.
-
- attr_accessor :type
-
- ##
- # The contents of the Store
-
- attr_reader :cache
-
- ##
- # The encoding of the contents in the Store
-
- attr_accessor :encoding
-
- ##
- # Creates a new Store of +type+ that will load or save to +path+
-
- def initialize path, type = nil
- @dry_run = false
- @type = type
- @path = path
- @encoding = nil
-
- @cache = {
- :ancestors => {},
- :attributes => {},
- :class_methods => {},
- :encoding => @encoding,
- :instance_methods => {},
- :modules => [],
- }
- end
-
- ##
- # Ancestors cache accessor. Maps a klass name to an Array of its ancestors
- # in this store. If Foo in this store inherits from Object, Kernel won't be
- # listed (it will be included from ruby's ri store).
-
- def ancestors
- @cache[:ancestors]
- end
-
- ##
- # Attributes cache accessor. Maps a class to an Array of its attributes.
-
- def attributes
- @cache[:attributes]
- end
-
- ##
- # Path to the cache file
-
- def cache_path
- File.join @path, 'cache.ri'
- end
-
- ##
- # Path to the ri data for +klass_name+
-
- def class_file klass_name
- name = klass_name.split('::').last
- File.join class_path(klass_name), "cdesc-#{name}.ri"
- end
-
- ##
- # Class methods cache accessor. Maps a class to an Array of its class
- # methods (not full name).
-
- def class_methods
- @cache[:class_methods]
- end
-
- ##
- # Path where data for +klass_name+ will be stored (methods or class data)
-
- def class_path klass_name
- File.join @path, *klass_name.split('::')
- end
-
- ##
- # Removes empty items and ensures item in each collection are unique and
- # sorted
-
- def clean_cache_collection collection # :nodoc:
- collection.each do |name, item|
- if item.empty? then
- collection.delete name
- else
- # HACK mongrel-1.1.5 documents its files twice
- item.uniq!
- item.sort!
- end
- end
- end
-
- ##
- # Friendly rendition of #path
-
- def friendly_path
- case type
- when :gem then
- sep = Regexp.union(*['/', File::ALT_SEPARATOR].compact)
- @path =~ /#{sep}doc#{sep}(.*?)#{sep}ri$/
- "gem #{$1}"
- when :home then '~/.ri'
- when :site then 'ruby site'
- when :system then 'ruby core'
- else @path
- end
- end
-
- def inspect # :nodoc:
- "#<%s:0x%x %s %p>" % [self.class, object_id, @path, modules.sort]
- end
-
- ##
- # Instance methods cache accessor. Maps a class to an Array of its
- # instance methods (not full name).
-
- def instance_methods
- @cache[:instance_methods]
- end
-
- ##
- # Loads cache file for this store
-
- def load_cache
- #orig_enc = @encoding
-
- open cache_path, 'rb' do |io|
- @cache = Marshal.load io.read
- end
-
- load_enc = @cache[:encoding]
-
- # TODO this feature will be time-consuming to add:
- # a) Encodings may be incompatible but transcodeable
- # b) Need to warn in the appropriate spots, wherever they may be
- # c) Need to handle cross-cache differences in encodings
- # d) Need to warn when generating into a cache with diffent encodings
- #
- #if orig_enc and load_enc != orig_enc then
- # warn "Cached encoding #{load_enc} is incompatible with #{orig_enc}\n" \
- # "from #{path}/cache.ri" unless
- # Encoding.compatible? orig_enc, load_enc
- #end
-
- @encoding = load_enc unless @encoding
-
- @cache
- rescue Errno::ENOENT
- end
-
- ##
- # Loads ri data for +klass_name+
-
- def load_class klass_name
- open class_file(klass_name), 'rb' do |io|
- Marshal.load io.read
- end
- end
-
- ##
- # Loads ri data for +method_name+ in +klass_name+
-
- def load_method klass_name, method_name
- open method_file(klass_name, method_name), 'rb' do |io|
- Marshal.load io.read
- end
- end
-
- ##
- # Path to the ri data for +method_name+ in +klass_name+
-
- def method_file klass_name, method_name
- method_name = method_name.split('::').last
- method_name =~ /#(.*)/
- method_type = $1 ? 'i' : 'c'
- method_name = $1 if $1
-
- method_name = if ''.respond_to? :ord then
- method_name.gsub(/\W/) { "%%%02x" % $&[0].ord }
- else
- method_name.gsub(/\W/) { "%%%02x" % $&[0] }
- end
-
- File.join class_path(klass_name), "#{method_name}-#{method_type}.ri"
- end
-
- ##
- # Modules cache accessor. An Array of all the modules (and classes) in the
- # store.
-
- def modules
- @cache[:modules]
- end
-
- ##
- # Writes the cache file for this store
-
- def save_cache
- clean_cache_collection @cache[:ancestors]
- clean_cache_collection @cache[:attributes]
- clean_cache_collection @cache[:class_methods]
- clean_cache_collection @cache[:instance_methods]
-
- @cache[:modules].uniq!
- @cache[:modules].sort!
- @cache[:encoding] = @encoding # this gets set twice due to assert_cache
-
- return if @dry_run
-
- marshal = Marshal.dump @cache
-
- open cache_path, 'wb' do |io|
- io.write marshal
- end
- end
-
- ##
- # Writes the ri data for +klass+
-
- def save_class klass
- full_name = klass.full_name
-
- FileUtils.mkdir_p class_path(full_name) unless @dry_run
-
- @cache[:modules] << full_name
-
- path = class_file full_name
-
- begin
- disk_klass = load_class full_name
-
- klass = disk_klass.merge klass
- rescue Errno::ENOENT
- end
-
- # BasicObject has no ancestors
- ancestors = klass.ancestors.compact.map do |ancestor|
- # HACK for classes we don't know about (class X < RuntimeError)
- String === ancestor ? ancestor : ancestor.full_name
- end
-
- @cache[:ancestors][full_name] ||= []
- @cache[:ancestors][full_name].push(*ancestors)
-
- attributes = klass.attributes.map do |attribute|
- "#{attribute.definition} #{attribute.name}"
- end
-
- unless attributes.empty? then
- @cache[:attributes][full_name] ||= []
- @cache[:attributes][full_name].push(*attributes)
- end
-
- to_delete = []
-
- unless klass.method_list.empty? then
- @cache[:class_methods][full_name] ||= []
- @cache[:instance_methods][full_name] ||= []
-
- class_methods, instance_methods =
- klass.method_list.partition { |meth| meth.singleton }
-
- class_methods = class_methods. map { |method| method.name }
- instance_methods = instance_methods.map { |method| method.name }
-
- old = @cache[:class_methods][full_name] - class_methods
- to_delete.concat old.map { |method|
- method_file full_name, "#{full_name}::#{method}"
- }
-
- old = @cache[:instance_methods][full_name] - instance_methods
- to_delete.concat old.map { |method|
- method_file full_name, "#{full_name}##{method}"
- }
-
- @cache[:class_methods][full_name] = class_methods
- @cache[:instance_methods][full_name] = instance_methods
- end
-
- return if @dry_run
-
- FileUtils.rm_f to_delete
-
- marshal = Marshal.dump klass
-
- open path, 'wb' do |io|
- io.write marshal
- end
- end
-
- ##
- # Writes the ri data for +method+ on +klass+
-
- def save_method klass, method
- full_name = klass.full_name
-
- FileUtils.mkdir_p class_path(full_name) unless @dry_run
-
- cache = if method.singleton then
- @cache[:class_methods]
- else
- @cache[:instance_methods]
- end
- cache[full_name] ||= []
- cache[full_name] << method.name
-
- return if @dry_run
-
- marshal = Marshal.dump method
-
- open method_file(full_name, method.full_name), 'wb' do |io|
- io.write marshal
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/ruby_lex.rb b/ruby_1_9_3/lib/rdoc/ruby_lex.rb
deleted file mode 100644
index 4392cea9cf..0000000000
--- a/ruby_1_9_3/lib/rdoc/ruby_lex.rb
+++ /dev/null
@@ -1,1297 +0,0 @@
-# coding: US-ASCII
-
-#--
-# irb/ruby-lex.rb - ruby lexcal analyzer
-# $Release Version: 0.9.5$
-# $Revision: 17979 $
-# $Date: 2008-07-09 10:17:05 -0700 (Wed, 09 Jul 2008) $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-#++
-
-require "e2mmap"
-require "irb/slex"
-require "rdoc/ruby_token"
-require "stringio"
-
-##
-# Ruby lexer adapted from irb.
-#
-# The internals are not documented because they are scary.
-
-class RDoc::RubyLex
-
- # :stopdoc:
-
- 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")
-
- def_exception(:TerminateLineInput, "Terminate Line Input")
-
- include RDoc::RubyToken
- include IRB
-
- attr_reader :continue
- attr_reader :lex_state
- attr_reader :reader
-
- class << self
- attr_accessor :debug_level
- end
-
- def self.debug?
- @debug_level > 0
- end
-
- self.debug_level = 0
-
- def initialize(content, options)
- lex_init
-
- if /\t/ =~ content then
- tab_width = options.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 << "\n" unless content[-1, 1] == "\n"
-
- set_input StringIO.new content
-
- @base_char_no = 0
- @char_no = 0
- @exp_line_no = @line_no = 1
- @here_readed = []
- @readed = []
- @rests = []
- @seek = 0
-
- @here_header = false
- @indent = 0
- @indent_stack = []
- @lex_state = EXPR_BEG
- @space_seen = false
-
- @continue = false
- @line = ""
-
- @skip_space = false
- @readed_auto_clean_up = false
- @exception_on_syntax_error = true
-
- @prompt = nil
- @prev_seek = nil
- end
-
- def inspect # :nodoc:
- "#<%s:0x%x pos %d lex_state %p space_seen %p>" % [
- self.class, object_id,
- @io.pos, @lex_state, @space_seen,
- ]
- end
-
- attr_accessor :skip_space
- attr_accessor :readed_auto_clean_up
- attr_accessor :exception_on_syntax_error
-
- attr_reader :seek
- attr_reader :char_no
- attr_reader :line_no
- attr_reader :indent
-
- # io functions
- def set_input(io, p = nil, &block)
- @io = io
- if p.respond_to?(:call)
- @input = p
- elsif block_given?
- @input = block
- else
- @input = Proc.new{@io.gets}
- end
- end
-
- def get_readed
- if idx = @readed.reverse.index("\n")
- @base_char_no = idx
- else
- @base_char_no += @readed.size
- end
-
- readed = @readed.join("")
- @readed = []
- readed
- end
-
- def getc
- while @rests.empty?
- # return nil unless buf_input
- @rests.push nil unless buf_input
- end
- c = @rests.shift
- if @here_header
- @here_readed.push c
- else
- @readed.push c
- end
- @seek += 1
- if c == "\n"
- @line_no += 1
- @char_no = 0
- else
- @char_no += 1
- end
-
- c
- end
-
- def gets
- l = ""
- while c = getc
- l.concat(c)
- break if c == "\n"
- end
- return nil if l == "" and c.nil?
- l
- end
-
- def eof?
- @io.eof?
- end
-
- def getc_of_rests
- if @rests.empty?
- nil
- else
- getc
- end
- end
-
- def ungetc(c = nil)
- if @here_readed.empty?
- c2 = @readed.pop
- else
- c2 = @here_readed.pop
- end
- c = c2 unless c
- @rests.unshift c #c =
- @seek -= 1
- if c == "\n"
- @line_no -= 1
- if idx = @readed.reverse.index("\n")
- @char_no = @readed.size - idx
- else
- @char_no = @base_char_no + @readed.size
- end
- else
- @char_no -= 1
- end
- end
-
- def peek_equal?(str)
- chrs = str.split(//)
- until @rests.size >= chrs.size
- return false unless buf_input
- end
- @rests[0, chrs.size] == chrs
- end
-
- def peek_match?(regexp)
- while @rests.empty?
- return false unless buf_input
- end
- regexp =~ @rests.join("")
- end
-
- def peek(i = 0)
- while @rests.size <= i
- return nil unless buf_input
- end
- @rests[i]
- end
-
- def buf_input
- prompt
- line = @input.call
- return nil unless line
- @rests.concat line.split(//)
- true
- end
- private :buf_input
-
- def set_prompt(p = nil, &block)
- p = block if block_given?
- if p.respond_to?(:call)
- @prompt = p
- else
- @prompt = Proc.new{print p}
- end
- end
-
- def prompt
- if @prompt
- @prompt.call(@ltype, @indent, @continue, @line_no)
- end
- end
-
- def initialize_input
- @ltype = nil
- @quoted = nil
- @indent = 0
- @indent_stack = []
- @lex_state = EXPR_BEG
- @space_seen = false
- @here_header = false
-
- @continue = false
- prompt
-
- @line = ""
- @exp_line_no = @line_no
- end
-
- def each_top_level_statement
- initialize_input
- catch(:TERM_INPUT) do
- loop do
- begin
- @continue = false
- prompt
- unless l = lex
- throw :TERM_INPUT if @line == ''
- else
- #p l
- @line.concat l
- if @ltype or @continue or @indent > 0
- next
- end
- end
- if @line != "\n"
- yield @line, @exp_line_no
- end
- break unless l
- @line = ''
- @exp_line_no = @line_no
-
- @indent = 0
- @indent_stack = []
- prompt
- rescue TerminateLineInput
- initialize_input
- prompt
- get_readed
- end
- end
- end
- end
-
- def lex
- until (((tk = token).kind_of?(TkNL) || tk.kind_of?(TkEND_OF_SCRIPT)) &&
- !@continue or
- tk.nil?)
- #p tk
- #p @lex_state
- #p self
- end
- line = get_readed
- # print self.inspect
- if line == "" and tk.kind_of?(TkEND_OF_SCRIPT) || tk.nil?
- nil
- else
- line
- end
- end
-
- def token
- # require "tracer"
- # Tracer.on
- @prev_seek = @seek
- @prev_line_no = @line_no
- @prev_char_no = @char_no
- begin
- begin
- tk = @OP.match(self)
- @space_seen = tk.kind_of?(TkSPACE)
- rescue SyntaxError => e
- raise RDoc::Error, "syntax error: #{e.message}" if
- @exception_on_syntax_error
-
- tk = TkError.new(@seek, @line_no, @char_no)
- end
- end while @skip_space and tk.kind_of?(TkSPACE)
-
- if @readed_auto_clean_up
- get_readed
- end
- # Tracer.off
- 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" => "]",
- "W" => "]",
- "s" => ":"
- }
-
- PERCENT_PAREN = {
- "{" => "}",
- "[" => "]",
- "<" => ">",
- "(" => ")"
- }
-
- PERCENT_PAREN_REV = PERCENT_PAREN.invert
-
- Ltype2Token = {
- "\'" => TkSTRING,
- "\"" => TkSTRING,
- "\`" => TkXSTRING,
- "/" => TkREGEXP,
- "]" => TkDSTRING,
- ":" => TkSYMBOL
- }
- DLtype2Token = {
- "\"" => TkDSTRING,
- "\`" => TkDXSTRING,
- "/" => TkDREGEXP,
- }
-
- def lex_init()
- @OP = IRB::SLex.new
- @OP.def_rules("\0", "\004", "\032") do |op, io|
- Token(TkEND_OF_SCRIPT)
- end
-
- @OP.def_rules(" ", "\t", "\f", "\r", "\13") do |op, io|
- @space_seen = true
- str = op
- while (ch = getc) =~ /[ \t\f\r\13]/ do
- str << ch
- end
- ungetc
- Token TkSPACE, str
- end
-
- @OP.def_rule("#") do |op, io|
- identify_comment
- end
-
- @OP.def_rule("=begin",
- proc{|op, io| @prev_char_no == 0 && peek(0) =~ /\s/}) do
- |op, io|
- @ltype = "="
- res = ''
- nil until (ch = getc) == "\n"
-
- until ( peek_equal?("=end") && peek(4) =~ /\s/ ) do
- (ch = getc)
- res << ch
- end
-
- gets # consume =end
-
- @ltype = nil
- Token(TkCOMMENT, res)
- end
-
- @OP.def_rule("\n") do |op, io|
- print "\\n\n" if RDoc::RubyLex.debug?
- case @lex_state
- when EXPR_BEG, EXPR_FNAME, EXPR_DOT
- @continue = true
- else
- @continue = false
- @lex_state = EXPR_BEG
- until (@indent_stack.empty? ||
- [TkLPAREN, TkLBRACK, TkLBRACE,
- TkfLPAREN, TkfLBRACK, TkfLBRACE].include?(@indent_stack.last))
- @indent_stack.pop
- end
- end
- @here_header = false
- @here_readed = []
- Token(TkNL)
- end
-
- @OP.def_rules("*", "**",
- "=", "==", "===",
- "=~", "<=>",
- "<", "<=",
- ">", ">=", ">>") do
- |op, io|
- case @lex_state
- when EXPR_FNAME, EXPR_DOT
- @lex_state = EXPR_ARG
- else
- @lex_state = EXPR_BEG
- end
- Token(op)
- end
-
- @OP.def_rules("!", "!=", "!~") do
- |op, io|
- @lex_state = EXPR_BEG
- Token(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 /\S/ =~ c && (/["'`]/ =~ c || /\w/ =~ c || c == "-")
- tk = identify_here_document
- end
- end
- unless tk
- tk = Token(op)
- case @lex_state
- when EXPR_FNAME, EXPR_DOT
- @lex_state = EXPR_ARG
- else
- @lex_state = EXPR_BEG
- end
- end
- tk
- end
-
- @OP.def_rules("'", '"') do
- |op, io|
- identify_string(op)
- end
-
- @OP.def_rules("`") do
- |op, io|
- if @lex_state == EXPR_FNAME
- @lex_state = EXPR_END
- Token(op)
- else
- identify_string(op)
- end
- end
-
- @OP.def_rules('?') do
- |op, io|
- if @lex_state == EXPR_END
- @lex_state = EXPR_BEG
- Token(TkQUESTION)
- else
- ch = getc
- if @lex_state == EXPR_ARG && ch =~ /\s/
- ungetc
- @lex_state = EXPR_BEG;
- Token(TkQUESTION)
- else
- str = ch
- if ch == '\\'
- str << read_escape
- end
- @lex_state = EXPR_END
- str << (ch.respond_to?(:ord) ? ch.ord : ch[0])
- Token(TkINTEGER, str)
- end
- end
- end
-
- @OP.def_rules("&", "&&", "|", "||") do
- |op, io|
- @lex_state = EXPR_BEG
- Token(op)
- end
-
- @OP.def_rules("+=", "-=", "*=", "**=",
- "&=", "|=", "^=", "<<=", ">>=", "||=", "&&=") do
- |op, io|
- @lex_state = EXPR_BEG
- op =~ /^(.*)=$/
- Token(TkOPASGN, $1)
- end
-
- @OP.def_rule("+@", proc{|op, io| @lex_state == EXPR_FNAME}) do
- |op, io|
- @lex_state = EXPR_ARG
- Token(op)
- end
-
- @OP.def_rule("-@", proc{|op, io| @lex_state == EXPR_FNAME}) do
- |op, io|
- @lex_state = EXPR_ARG
- Token(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)
- end
- end
-
- @OP.def_rule(".") do
- |op, io|
- @lex_state = EXPR_BEG
- if peek(0) =~ /[0-9]/
- ungetc
- identify_number
- else
- # for "obj.if" etc.
- @lex_state = EXPR_DOT
- Token(TkDOT)
- end
- end
-
- @OP.def_rules("..", "...") do
- |op, io|
- @lex_state = EXPR_BEG
- Token(op)
- end
-
- lex_int2
- end
-
- def lex_int2
- @OP.def_rules("]", "}", ")") do
- |op, io|
- @lex_state = EXPR_END
- @indent -= 1
- @indent_stack.pop
- Token(op)
- end
-
- @OP.def_rule(":") do
- |op, io|
- if @lex_state == EXPR_END || peek(0) =~ /\s/
- @lex_state = EXPR_BEG
- Token(TkCOLON)
- else
- @lex_state = EXPR_FNAME;
- Token(TkSYMBEG)
- end
- end
-
- @OP.def_rule("::") do
- |op, io|
- # p @lex_state.id2name, @space_seen
- if @lex_state == EXPR_BEG or @lex_state == EXPR_ARG && @space_seen
- @lex_state = EXPR_BEG
- Token(TkCOLON3)
- else
- @lex_state = EXPR_DOT
- Token(TkCOLON2)
- end
- 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, "/") #/)
- elsif @lex_state == EXPR_ARG and @space_seen and peek(0) !~ /\s/
- identify_string(op)
- else
- @lex_state = EXPR_BEG
- Token("/") #/)
- end
- end
-
- @OP.def_rules("^") do
- |op, io|
- @lex_state = EXPR_BEG
- Token("^")
- end
-
- # @OP.def_rules("^=") do
- # @lex_state = EXPR_BEG
- # Token(OP_ASGN, :^)
- # end
-
- @OP.def_rules(",") do
- |op, io|
- @lex_state = EXPR_BEG
- Token(op)
- end
-
- @OP.def_rules(";") do
- |op, io|
- @lex_state = EXPR_BEG
- until (@indent_stack.empty? ||
- [TkLPAREN, TkLBRACK, TkLBRACE,
- TkfLPAREN, TkfLBRACK, TkfLBRACE].include?(@indent_stack.last))
- @indent_stack.pop
- end
- Token(op)
- end
-
- @OP.def_rule("~") do
- |op, io|
- @lex_state = EXPR_BEG
- Token("~")
- end
-
- @OP.def_rule("~@", proc{|op, io| @lex_state == EXPR_FNAME}) do
- |op, io|
- @lex_state = EXPR_BEG
- Token("~")
- end
-
- @OP.def_rule("(") do
- |op, io|
- @indent += 1
- if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
- @lex_state = EXPR_BEG
- tk_c = TkfLPAREN
- else
- @lex_state = EXPR_BEG
- tk_c = TkLPAREN
- end
- @indent_stack.push tk_c
- Token tk_c
- end
-
- @OP.def_rule("[]", proc{|op, io| @lex_state == EXPR_FNAME}) do
- |op, io|
- @lex_state = EXPR_ARG
- Token("[]")
- end
-
- @OP.def_rule("[]=", proc{|op, io| @lex_state == EXPR_FNAME}) do
- |op, io|
- @lex_state = EXPR_ARG
- Token("[]=")
- end
-
- @OP.def_rule("[") do
- |op, io|
- @indent += 1
- if @lex_state == EXPR_FNAME
- tk_c = TkfLBRACK
- else
- if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
- tk_c = TkLBRACK
- elsif @lex_state == EXPR_ARG && @space_seen
- tk_c = TkLBRACK
- else
- tk_c = TkfLBRACK
- end
- @lex_state = EXPR_BEG
- end
- @indent_stack.push tk_c
- Token(tk_c)
- end
-
- @OP.def_rule("{") do
- |op, io|
- @indent += 1
- if @lex_state != EXPR_END && @lex_state != EXPR_ARG
- tk_c = TkLBRACE
- else
- tk_c = TkfLBRACE
- end
- @lex_state = EXPR_BEG
- @indent_stack.push tk_c
- Token(tk_c)
- end
-
- @OP.def_rule('\\') do
- |op, io|
- if getc == "\n"
- @space_seen = true
- @continue = true
- Token(TkSPACE)
- else
- ungetc
- Token("\\")
- 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, :%)
- elsif @lex_state == EXPR_ARG and @space_seen and peek(0) !~ /\s/
- identify_quotation
- else
- @lex_state = EXPR_BEG
- Token("%") #))
- end
- end
-
- @OP.def_rule('$') do
- |op, io|
- identify_gvar
- end
-
- @OP.def_rule('@') do
- |op, io|
- if peek(0) =~ /[\w@]/
- ungetc
- identify_identifier
- else
- Token("@")
- 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("_") do
- if peek_match?(/_END__/) and @lex_state == EXPR_BEG then
- Token(TkEND_OF_SCRIPT)
- else
- ungetc
- identify_identifier
- end
- end
-
- @OP.def_rule("") do
- |op, io|
- printf "MATCH: start %s: %s\n", op, io.inspect if RDoc::RubyLex.debug?
- if peek(0) =~ /[0-9]/
- t = identify_number
- else
- t = identify_identifier
- end
- printf "MATCH: end %s: %s\n", op, io.inspect if RDoc::RubyLex.debug?
- t
- end
-
- p @OP if RDoc::RubyLex.debug?
- end
-
- def identify_gvar
- @lex_state = EXPR_END
-
- case ch = getc
- when /[~_*$?!@\/\\;,=:<>".]/ #"
- Token(TkGVAR, "$" + ch)
- when "-"
- Token(TkGVAR, "$-" + getc)
- when "&", "`", "'", "+"
- Token(TkBACK_REF, "$"+ch)
- when /[1-9]/
- ref = ch
- while (ch = getc) =~ /[0-9]/ do ref << ch end
- ungetc
- Token(TkNTH_REF, "$#{ref}")
- when /\w/
- ungetc
- ungetc
- identify_identifier
- else
- ungetc
- Token("$")
- end
- end
-
- IDENT_RE = if defined? Encoding then
- /[\w\u0080-\uFFFF]/u
- else
- /[\w\x80-\xFF]/
- end
-
- def identify_identifier
- token = ""
- if peek(0) =~ /[$@]/
- token.concat(c = getc)
- if c == "@" and peek(0) == "@"
- token.concat getc
- end
- end
-
- while (ch = getc) =~ IDENT_RE do
- print " :#{ch}: " if RDoc::RubyLex.debug?
- token.concat ch
- end
-
- ungetc
-
- if (ch == "!" || ch == "?") && token[0,1] =~ /\w/ && peek(0) != "="
- token.concat getc
- end
-
- # almost fix token
-
- case token
- when /^\$/
- return Token(TkGVAR, token)
- when /^\@\@/
- @lex_state = EXPR_END
- # p Token(TkCVAR, token)
- return Token(TkCVAR, token)
- when /^\@/
- @lex_state = EXPR_END
- return Token(TkIVAR, token)
- end
-
- if @lex_state != EXPR_DOT
- print token, "\n" if RDoc::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)
- # check for ``class = val'' etc.
- valid = true
- case token
- when "class"
- valid = false unless peek_match?(/^\s*(<<|\w|::)/)
- when "def"
- valid = false if peek_match?(/^\s*(([+-\/*&\|^]|<<|>>|\|\||\&\&)=|\&\&|\|\|)/)
- when "do"
- valid = false if peek_match?(/^\s*([+-\/*]?=|\*|<|>|\&)/)
- when *ENINDENT_CLAUSE
- valid = false if peek_match?(/^\s*([+-\/*]?=|\*|<|>|\&|\|)/)
- else
- # no nothing
- end
- if valid
- if token == "do"
- if ![TkFOR, TkWHILE, TkUNTIL].include?(@indent_stack.last)
- @indent += 1
- @indent_stack.push token_c
- end
- else
- @indent += 1
- @indent_stack.push token_c
- end
- end
-
- elsif DEINDENT_CLAUSE.include?(token)
- @indent -= 1
- @indent_stack.pop
- end
- @lex_state = trans[0]
- else
- @lex_state = EXPR_END
- end
- end
- return Token(token_c, 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)
- elsif token[token.size - 1, 1] =~ /[!?]/
- return Token(TkFID, token)
- else
- return Token(TkIDENTIFIER, token)
- end
- end
-
- def identify_here_document
- ch = getc
- # if lt = PERCENT_LTYPE[ch]
- 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.push ch
- if ch == "\\"
- reserve.push ch = getc
- elsif ch == "\n"
- break
- end
- end
-
- @here_header = false
- doc = ''
- while l = gets
- l = l.sub(/(:?\r)?\n\z/, '')
- if (indent ? l.strip : l) == quoted
- break
- end
- doc << l
- end
-
- @here_header = true
- @here_readed.concat reserve
- while ch = reserve.pop
- ungetc ch
- end
-
- @ltype = ltback
- @lex_state = EXPR_END
- Token(Ltype2Token[lt], doc)
- end
-
- def identify_quotation
- ch = getc
- if lt = PERCENT_LTYPE[ch]
- ch = getc
- elsif ch =~ /\W/
- lt = "\""
- else
- raise RDoc::Error, "unknown type of %string #{ch.inspect}"
- end
- # if ch !~ /\W/
- # ungetc
- # next
- # end
- #@ltype = lt
- @quoted = ch unless @quoted = PERCENT_PAREN[ch]
- identify_string(lt, @quoted)
- end
-
- def identify_number(op = "")
- @lex_state = EXPR_END
-
- num = op
-
- if peek(0) == "0" && peek(1) !~ /[.eE]/
- num << getc
-
- case peek(0)
- when /[xX]/
- ch = getc
- match = /[0-9a-fA-F_]/
- when /[bB]/
- ch = getc
- match = /[01_]/
- when /[oO]/
- ch = getc
- match = /[0-7_]/
- when /[dD]/
- ch = getc
- match = /[0-9_]/
- when /[0-7]/
- match = /[0-7_]/
- when /[89]/
- raise RDoc::Error, "Illegal octal digit"
- else
- return Token(TkINTEGER, num)
- end
-
- num << ch if ch
-
- len0 = true
- non_digit = false
- while ch = getc
- num << ch
- if match =~ ch
- if ch == "_"
- if non_digit
- raise RDoc::Error, "trailing `#{ch}' in number"
- else
- non_digit = ch
- end
- else
- non_digit = false
- len0 = false
- end
- else
- ungetc
- num[-1, 1] = ''
- if len0
- raise RDoc::Error, "numeric literal without digits"
- end
- if non_digit
- raise RDoc::Error, "trailing `#{non_digit}' in number"
- end
- break
- end
- end
- return Token(TkINTEGER, num)
- end
-
- type = TkINTEGER
- allow_point = true
- allow_e = true
- non_digit = false
- while ch = getc
- num << ch
- case ch
- when /[0-9]/
- non_digit = false
- when "_"
- non_digit = ch
- when allow_point && "."
- if non_digit
- raise RDoc::Error, "trailing `#{non_digit}' in number"
- end
- type = TkFLOAT
- if peek(0) !~ /[0-9]/
- type = TkINTEGER
- ungetc
- num[-1, 1] = ''
- break
- end
- allow_point = false
- when allow_e && "e", allow_e && "E"
- if non_digit
- raise RDoc::Error, "trailing `#{non_digit}' in number"
- end
- type = TkFLOAT
- if peek(0) =~ /[+-]/
- num << getc
- end
- allow_e = false
- allow_point = false
- non_digit = ch
- else
- if non_digit
- raise RDoc::Error, "trailing `#{non_digit}' in number"
- end
- ungetc
- num[-1, 1] = ''
- break
- end
- end
-
- Token(type, num)
- end
-
- def identify_string(ltype, quoted = ltype)
- @ltype = ltype
- @quoted = quoted
-
- str = if ltype == quoted then
- ltype.dup
- else
- "%#{PERCENT_PAREN_REV[quoted]}"
- end
-
- subtype = nil
- begin
- nest = 0
-
- while ch = getc
- str << ch
-
- if @quoted == ch and nest == 0
- break
- elsif @ltype != "'" && @ltype != "]" && @ltype != ":" and ch == "#"
- ch = getc
- subtype = true
- if ch == "{" then
- str << ch << skip_inner_expression
- next
- else
- ungetc
- end
- elsif ch == '\\' and @ltype == "'" #'
- case ch = getc
- when "\\", "\n", "'"
- else
- ungetc
- end
- elsif ch == '\\' #'
- str << read_escape
- end
-
- if PERCENT_PAREN.values.include?(@quoted)
- if PERCENT_PAREN[ch] == @quoted
- nest += 1
- elsif ch == @quoted
- nest -= 1
- end
- end
- end
-
- if @ltype == "/"
- if peek(0) =~ /i|m|x|o|e|s|u|n/
- getc
- end
- end
-
- if subtype
- Token(DLtype2Token[ltype], str)
- else
- Token(Ltype2Token[ltype], str)
- end
- 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 == "\\" #"
- # read_escape
- # end
- if ch == "\n"
- @ltype = nil
- ungetc
- break
- end
-
- comment << ch
- end
-
- return Token(TkCOMMENT, comment)
- end
-
- def read_escape
- escape = ''
- ch = getc
- escape << ch
-
- case ch
- when "\n", "\r", "\f"
- when "\\", "n", "t", "r", "f", "v", "a", "e", "b", "s" #"
- when /[0-7]/
- ungetc ch
- 3.times do
- ch = getc
- escape << ch
- case ch
- when /[0-7]/
- when nil
- break
- else
- ungetc
- break
- end
- end
-
- when "x"
- 2.times do
- ch = getc
- escape << ch
- case ch
- when /[0-9a-fA-F]/
- when nil
- break
- else
- ungetc
- break
- end
- end
-
- when "M"
- ch = getc
- escape << ch
- if ch != '-'
- ungetc
- else
- ch = getc
- escape << ch
- if ch == "\\" #"
- escape << read_escape
- end
- end
-
- when "C", "c" #, "^"
- if ch == "C" and (ch = getc) != "-"
- escape << ch
- ungetc
- elsif (ch = getc) == "\\" #"
- escape << ch << read_escape
- end
- else
- # other characters
- end
-
- escape
- end
-
- # :startdoc:
-
-end
-
-#RDoc::RubyLex.debug_level = 1
-
diff --git a/ruby_1_9_3/lib/rdoc/ruby_token.rb b/ruby_1_9_3/lib/rdoc/ruby_token.rb
deleted file mode 100644
index 93b7a5cbc8..0000000000
--- a/ruby_1_9_3/lib/rdoc/ruby_token.rb
+++ /dev/null
@@ -1,416 +0,0 @@
-#--
-# irb/ruby-token.rb - ruby tokens
-# $Release Version: 0.9.5$
-# $Revision: 11708 $
-# $Date: 2007-02-12 15:01:19 -0800 (Mon, 12 Feb 2007) $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#++
-# Definitions of all tokens involved in the lexical analysis.
-#
-# This class is not documented because it is so deep in the internals.
-
-module RDoc::RubyToken
- # :stopdoc:
-
- 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
-
- # for ruby 1.4X
- if !defined?(Symbol)
- Symbol = Integer
- end
-
- def set_token_position(line, char)
- @prev_line_no = line
- @prev_char_no = char
- end
-
- class Token
- def initialize(seek, line_no, char_no, text = nil)
- @seek = seek
- @line_no = line_no
- @char_no = char_no
- @text = text
- end
-
- attr :seek
- attr :line_no
- attr :char_no
-
- attr_accessor :text
-
- def ==(other)
- self.class == other.class and
- other.line_no == @line_no and
- other.char_no == @char_no and
- other.text == @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
-
- end
-
- class TkNode < Token
- def initialize(seek, line_no, char_no, node = nil)
- super seek, line_no, char_no
- @node = node
- end
-
- attr :node
-
- def ==(other)
- self.class == other.class and
- other.line_no == @line_no and
- other.char_no == @char_no and
- other.node == @node
- end
-
- def set_text text
- @node = text
- self
- end
-
- alias text node
- end
-
- class TkId < Token
- def initialize(seek, line_no, char_no, name)
- super(seek, line_no, char_no)
- @name = name
- end
- attr :name
-
- def ==(other)
- self.class == other.class and
- other.line_no == @line_no and
- other.char_no == @char_no and
- other.name == @name
- end
-
- def set_text text
- @name = text
- self
- end
-
- alias text name
- end
-
- class TkKW < TkId
- end
-
- class TkVal < Token
- def initialize(seek, line_no, char_no, value = nil)
- super(seek, line_no, char_no)
- @value = value
- end
- attr_accessor :value
-
- def ==(other)
- self.class == other.class and
- other.line_no == @line_no and
- other.char_no == @char_no and
- other.value == @value
- end
-
- def set_text text
- @value = text
- self
- end
-
- alias text value
- end
-
- class TkOp < Token
- def initialize(seek, line_no, char_no, name = nil)
- super seek, line_no, char_no
- @name = name
- end
-
- attr_accessor :name
-
- def ==(other)
- self.class == other.class and
- other.line_no == @line_no and
- other.char_no == @char_no and
- other.name == @name
- end
-
- def set_text text
- @name = text
- self
- end
-
- alias text name
- end
-
- class TkOPASGN < TkOp
- def initialize(seek, line_no, char_no, op)
- super(seek, line_no, char_no)
- op = TkReading2Token[op][0] unless op.kind_of?(Symbol)
- @op = op
- @text = nil
- end
-
- attr :op
-
- def ==(other)
- self.class == other.class and
- other.line_no == @line_no and
- other.char_no == @char_no and
- other.op == @op
- end
-
- def text
- @text ||= "#{TkToken2Reading[op]}="
- end
- end
-
- class TkUnknownChar < Token
- def initialize(seek, line_no, char_no, name)
- super(seek, line_no, char_no)
- @name = name
- end
- attr :name
-
- def ==(other)
- self.class == other.class and
- other.line_no == @line_no and
- other.char_no == @char_no and
- other.name == @name
- end
-
- def set_text text
- @name = text
- self
- end
-
- alias text name
- end
-
- class TkError < Token
- end
-
- def Token(token, value = nil)
- value ||= TkToken2Reading[token]
-
- case token
- when String
- if (tk = TkReading2Token[token]).nil?
- IRB.fail TkReading2TokenNoKey, token
- end
-
- tk = Token(tk[0], value)
-
- if tk.kind_of?(TkOp) then
- tk.name = token
- end
- when Symbol
- if (tk = TkSymbol2Token[token]).nil?
- IRB.fail TkSymbol2TokenNoKey, token
- end
-
- tk = Token(tk[0], value)
- else
- if token.instance_method(:initialize).arity == 3 then
- tk = token.new(@prev_seek, @prev_line_no, @prev_char_no)
- tk.set_text value
- else
- tk = token.new(@prev_seek, @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_MID],
- [: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],
- [:TkCVAR, TkId],
- [:TkIVAR, TkId],
- [:TkCONSTANT, TkId],
-
- [:TkINTEGER, TkVal],
- [:TkFLOAT, TkVal],
- [:TkSTRING, TkVal],
- [:TkXSTRING, TkVal],
- [:TkREGEXP, TkVal],
- [:TkSYMBOL, TkVal],
-
- [:TkDSTRING, TkNode],
- [:TkDXSTRING, TkNode],
- [:TkDREGEXP, TkNode],
- [:TkNTH_REF, TkNode],
- [:TkBACK_REF, TkNode],
-
- [: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, Token, "("], # func( #
- [:TkfLBRACK, Token, "["], # func[ #
- [:TkfLBRACE, Token, "{"], # func{ #
- [:TkSTAR, Token, "*"], # *arg
- [:TkAMPER, Token, "&"], # &arg #
- [:TkSYMBEG, Token, ":"], # :SYMBOL
-
- [: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, ";"],
-
- [:TkCOMMENT, TkVal],
- [:TkRD_COMMENT],
- [:TkSPACE, Token, " "],
- [:TkNL, Token, "\n"],
- [:TkEND_OF_SCRIPT],
-
- [:TkBACKSLASH, TkUnknownChar, "\\"],
- [:TkAT, TkUnknownChar, "@"],
- [:TkDOLLAR, TkUnknownChar, "$"],
- ]
-
- # {reading => token_class}
- # {reading => [token_class, *opt]}
- TkReading2Token = {}
- TkToken2Reading = {}
- TkSymbol2Token = {}
-
- def self.def_token(token_n, super_token = Token, reading = nil, *opts)
- token_n = token_n.id2name if token_n.kind_of?(Symbol)
- if const_defined?(token_n)
- IRB.fail AlreadyDefinedToken, token_n
- end
- token_c = eval("class #{token_n} < #{super_token}; end; #{token_n}")
-
- if reading
- TkToken2Reading[token_c] = reading
-
- return if TkReading2Token[reading]
-
- if opts.empty?
- TkReading2Token[reading] = [token_c]
- else
- TkReading2Token[reading] = [token_c].concat(opts)
- end
- end
- TkSymbol2Token[token_n.intern] = token_c
- end
-
- for defs in TokenDefinitions
- def_token(*defs)
- end
-
- NEWLINE_TOKEN = TkNL.new nil, 0, 0, "\n"
-
- class TkSYMBOL
-
- def to_sym
- @sym ||= text[1..-1].intern
- end
-
- end
-
- # :startdoc:
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/rubygems_hook.rb b/ruby_1_9_3/lib/rdoc/rubygems_hook.rb
deleted file mode 100644
index 178ca1d2ae..0000000000
--- a/ruby_1_9_3/lib/rdoc/rubygems_hook.rb
+++ /dev/null
@@ -1,220 +0,0 @@
-require 'rubygems'
-require 'rubygems/user_interaction'
-require 'fileutils'
-require 'rdoc'
-
-##
-# Gem::RDoc provides methods to generate RDoc and ri data for installed gems
-# upon gem installation.
-#
-# This file is automatically required by RubyGems 1.9 and newer.
-
-class RDoc::RubygemsHook
-
- include Gem::UserInteraction
-
- @rdoc_version = nil
- @specs = []
-
- ##
- # Force installation of documentation?
-
- attr_accessor :force
-
- ##
- # Generate rdoc?
-
- attr_accessor :generate_rdoc
-
- ##
- # Generate ri data?
-
- attr_accessor :generate_ri
-
- class << self
-
- ##
- # Loaded version of RDoc. Set by ::load_rdoc
-
- attr_reader :rdoc_version
-
- end
-
- ##
- # Post installs hook that generates documentation for each specification in
- # +specs+
-
- def self.generation_hook installer, specs
- types = installer.document
-
- generate_rdoc = types.include? 'rdoc'
- generate_ri = types.include? 'ri'
-
- specs.each do |spec|
- new(spec, generate_rdoc, generate_ri).generate
- end
- end
-
- ##
- # Loads the RDoc generator
-
- def self.load_rdoc
- return if @rdoc_version
-
- require 'rdoc/rdoc'
-
- @rdoc_version = Gem::Version.new ::RDoc::VERSION
- end
-
- ##
- # Creates a new documentation generator for +spec+. RDoc and ri data
- # generation can be disabled through +generate_rdoc+ and +generate_ri+
- # respectively.
-
- def initialize spec, generate_rdoc = true, generate_ri = true
- @doc_dir = spec.doc_dir
- @file_info = nil
- @force = false
- @rdoc = nil
- @spec = spec
-
- @generate_rdoc = generate_rdoc
- @generate_ri = generate_ri
-
- @rdoc_dir = spec.doc_dir 'rdoc'
- @ri_dir = spec.doc_dir 'ri'
- end
-
- ##
- # Removes legacy rdoc arguments from +args+
- #--
- # TODO move to RDoc::Options
-
- def delete_legacy_args args
- args.delete '--inline-source'
- args.delete '--promiscuous'
- args.delete '-p'
- args.delete '--one-file'
- end
-
- ##
- # Generates documentation using the named +generator+ ("darkfish" or "ri")
- # and following the given +options+.
- #
- # Documentation will be generated into +destination+
-
- def document generator, options, destination
- options = options.dup
- options.exclude ||= [] # TODO maybe move to RDoc::Options#finish
- options.setup_generator generator
- options.op_dir = destination
- options.finish
-
- @rdoc.options = options
- @rdoc.generator = options.generator.new options
-
- say "Installing #{generator} documentation for #{@spec.full_name}"
-
- FileUtils.mkdir_p options.op_dir
-
- Dir.chdir options.op_dir do
- begin
- @rdoc.class.current = @rdoc
- @rdoc.generator.generate @file_info
- ensure
- @rdoc.class.current = nil
- end
- end
- end
-
- ##
- # Generates RDoc and ri data
-
- def generate
- return unless @generate_ri or @generate_rdoc
-
- setup
-
- ::RDoc::RDoc.reset
-
- options = ::RDoc::Options.new
- options.default_title = "#{@spec.full_name} Documentation"
- options.files = []
- options.files.push(*@spec.require_paths)
- options.files.push(*@spec.extra_rdoc_files)
-
- args = @spec.rdoc_options
-
- case config_args = Gem.configuration[:rdoc]
- when String then
- args = args.concat config_args.split
- when Array then
- args = args.concat config_args
- end
-
- delete_legacy_args args
- options.parse args
- options.quiet = !Gem.configuration.really_verbose
-
- @rdoc = new_rdoc
- @rdoc.options = options
-
- Dir.chdir @spec.full_gem_path do
- @file_info = @rdoc.parse_files options.files
- end
-
- document 'ri', options, @ri_dir if
- @generate_ri and (@force or not File.exist? @ri_dir)
-
- document 'darkfish', options, @rdoc_dir if
- @generate_rdoc and (@force or not File.exist? @rdoc_dir)
- end
-
- ##
- # #new_rdoc creates a new RDoc instance. This method is provided only to
- # make testing easier.
-
- def new_rdoc # :nodoc:
- ::RDoc::RDoc.new
- end
-
- ##
- # Is rdoc documentation installed?
-
- def rdoc_installed?
- File.exist? @rdoc_dir
- end
-
- ##
- # Removes generated RDoc and ri data
-
- def remove
- base_dir = @spec.base_dir
-
- raise Gem::FilePermissionError, base_dir unless File.writable? base_dir
-
- FileUtils.rm_rf @rdoc_dir
- FileUtils.rm_rf @ri_dir
- end
-
- ##
- # Is ri data installed?
-
- def ri_installed?
- File.exist? @ri_dir
- end
-
- ##
- # Prepares the spec for documentation generation
-
- def setup
- self.class.load_rdoc
-
- raise Gem::FilePermissionError, @doc_dir if
- File.exist?(@doc_dir) and not File.writable?(@doc_dir)
-
- FileUtils.mkdir_p @doc_dir unless File.exist? @doc_dir
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/single_class.rb b/ruby_1_9_3/lib/rdoc/single_class.rb
deleted file mode 100644
index e48758d9c8..0000000000
--- a/ruby_1_9_3/lib/rdoc/single_class.rb
+++ /dev/null
@@ -1,23 +0,0 @@
-require 'rdoc/class_module'
-
-##
-# A singleton class
-
-class RDoc::SingleClass < RDoc::ClassModule
-
- ##
- # Adds the superclass to the included modules.
-
- def ancestors
- superclass ? super + [superclass] : super
- end
-
- ##
- # The definition of this singleton class, <tt>class << MyClassName</tt>
-
- def definition
- "class << #{full_name}"
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/stats.rb b/ruby_1_9_3/lib/rdoc/stats.rb
deleted file mode 100644
index e6101bb457..0000000000
--- a/ruby_1_9_3/lib/rdoc/stats.rb
+++ /dev/null
@@ -1,438 +0,0 @@
-require 'rdoc'
-
-##
-# RDoc statistics collector which prints a summary and report of a project's
-# documentation totals.
-
-class RDoc::Stats
-
- ##
- # Output level for the coverage report
-
- attr_reader :coverage_level
-
- ##
- # Count of files parsed during parsing
-
- attr_reader :files_so_far
-
- ##
- # Total number of files found
-
- attr_reader :num_files
-
- ##
- # Creates a new Stats that will have +num_files+. +verbosity+ defaults to 1
- # which will create an RDoc::Stats::Normal outputter.
-
- def initialize num_files, verbosity = 1
- @files_so_far = 0
- @num_files = num_files
-
- @coverage_level = 0
- @doc_items = nil
- @fully_documented = false
- @num_params = 0
- @percent_doc = nil
- @start = Time.now
- @undoc_params = 0
-
- @display = case verbosity
- when 0 then Quiet.new num_files
- when 1 then Normal.new num_files
- else Verbose.new num_files
- end
- end
-
- ##
- # Records the parsing of an alias +as+.
-
- def add_alias as
- @display.print_alias as
- end
-
- ##
- # Records the parsing of an attribute +attribute+
-
- def add_attribute attribute
- @display.print_attribute attribute
- end
-
- ##
- # Records the parsing of a class +klass+
-
- def add_class klass
- @display.print_class klass
- end
-
- ##
- # Records the parsing of +constant+
-
- def add_constant constant
- @display.print_constant constant
- end
-
- ##
- # Records the parsing of +file+
-
- def add_file(file)
- @files_so_far += 1
- @display.print_file @files_so_far, file
- end
-
- ##
- # Records the parsing of +method+
-
- def add_method(method)
- @display.print_method method
- end
-
- ##
- # Records the parsing of a module +mod+
-
- def add_module(mod)
- @display.print_module mod
- end
-
- ##
- # Call this to mark the beginning of parsing for display purposes
-
- def begin_adding
- @display.begin_adding
- end
-
- ##
- # Calculates documentation totals and percentages for classes, modules,
- # constants, attributes and methods.
-
- def calculate
- return if @doc_items
-
- ucm = RDoc::TopLevel.unique_classes_and_modules
- constants = []
- ucm.each { |cm| constants.concat cm.constants }
-
- methods = []
- ucm.each { |cm| methods.concat cm.method_list }
-
- attributes = []
- ucm.each { |cm| attributes.concat cm.attributes }
-
- @num_attributes, @undoc_attributes = doc_stats attributes
- @num_classes, @undoc_classes = doc_stats RDoc::TopLevel.unique_classes
- @num_constants, @undoc_constants = doc_stats constants
- @num_methods, @undoc_methods = doc_stats methods
- @num_modules, @undoc_modules = doc_stats RDoc::TopLevel.unique_modules
-
- @num_items =
- @num_attributes +
- @num_classes +
- @num_constants +
- @num_methods +
- @num_modules +
- @num_params
-
- @undoc_items =
- @undoc_attributes +
- @undoc_classes +
- @undoc_constants +
- @undoc_methods +
- @undoc_modules +
- @undoc_params
-
- @doc_items = @num_items - @undoc_items
- end
-
- ##
- # Sets coverage report level. Accepted values are:
- #
- # false or nil:: No report
- # 0:: Classes, modules, constants, attributes, methods
- # 1:: Level 0 + method parameters
-
- def coverage_level= level
- level = -1 unless level
-
- @coverage_level = level
- end
-
- ##
- # Returns the length and number of undocumented items in +collection+.
-
- def doc_stats collection
- [collection.length, collection.count { |item| not item.documented? }]
- end
-
- ##
- # Call this to mark the end of parsing for display purposes
-
- def done_adding
- @display.done_adding
- end
-
- ##
- # The documentation status of this project. +true+ when 100%, +false+ when
- # less than 100% and +nil+ when unknown.
- #
- # Set by calling #calculate
-
- def fully_documented?
- @fully_documented
- end
-
- ##
- # A report that says you did a great job!
-
- def great_job
- report = []
- report << '100% documentation!'
- report << nil
- report << 'Great Job!'
-
- report.join "\n"
- end
-
- ##
- # Calculates the percentage of items documented.
-
- def percent_doc
- return @percent_doc if @percent_doc
-
- @fully_documented = (@num_items - @doc_items) == 0
-
- @percent_doc = @doc_items.to_f / @num_items * 100 if @num_items.nonzero?
- @percent_doc ||= 0
-
- @percent_doc
- end
-
- ##
- # Returns a report on which items are not documented
-
- def report
- if @coverage_level > 0 then
- require 'rdoc/markup/to_tt_only'
- require 'rdoc/generator/markup'
- require 'rdoc/text'
- extend RDoc::Text
- end
-
- report = []
-
- if @coverage_level.zero? then
- calculate
-
- return great_job if @num_items == @doc_items
- end
-
- ucm = RDoc::TopLevel.unique_classes_and_modules
-
- ucm.sort.each do |cm|
- report << report_class_module(cm) {
- [
- report_constants(cm),
- report_attributes(cm),
- report_methods(cm),
- ].compact
- }
- end
-
- if @coverage_level > 0 then
- calculate
-
- return great_job if @num_items == @doc_items
- end
-
- report.unshift nil
- report.unshift 'The following items are not documented:'
-
- report.join "\n"
- end
-
- ##
- # Returns a report on undocumented attributes in ClassModule +cm+
-
- def report_attributes cm
- return if cm.attributes.empty?
-
- report = []
-
- cm.each_attribute do |attr|
- next if attr.documented?
- report << " #{attr.definition} :#{attr.name} " \
- "# in file #{attr.file.full_name}"
- end
-
- report
- end
-
- ##
- # Returns a report on undocumented items in ClassModule +cm+
-
- def report_class_module cm
- return if cm.fully_documented? and @coverage_level.zero?
-
- report = []
-
- if cm.in_files.empty? then
- report << "# #{cm.definition} is referenced but empty."
- report << '#'
- report << '# It probably came from another project. ' \
- "I'm sorry I'm holding it against you."
- report << nil
-
- return report
- elsif cm.documented? then
- documented = true
- report << "#{cm.definition} # is documented"
- else
- report << '# in files:'
-
- cm.in_files.each do |file|
- report << "# #{file.full_name}"
- end
-
- report << nil
-
- report << "#{cm.definition}"
- end
-
- body = yield.flatten # HACK remove #flatten
-
- return if body.empty? and documented
-
- report << nil << body unless body.empty?
-
- report << 'end'
- report << nil
-
- report
- end
-
- ##
- # Returns a report on undocumented constants in ClassModule +cm+
-
- def report_constants cm
- return if cm.constants.empty?
-
- report = []
-
- cm.each_constant do |constant|
- # TODO constant aliases are listed in the summary but not reported
- # figure out what to do here
- next if constant.documented? || constant.is_alias_for
- report << " # in file #{constant.file.full_name}"
- report << " #{constant.name} = nil"
- end
-
- report
- end
-
- ##
- # Returns a report on undocumented methods in ClassModule +cm+
-
- def report_methods cm
- return if cm.method_list.empty?
-
- report = []
-
- cm.each_method do |method|
- next if method.documented? and @coverage_level.zero?
-
- if @coverage_level > 0 then
- params, undoc = undoc_params method
-
- @num_params += params
-
- unless undoc.empty? then
- @undoc_params += undoc.length
-
- undoc = undoc.map do |param| "+#{param}+" end
- param_report = " # #{undoc.join ', '} is not documented"
- end
- end
-
- next if method.documented? and not param_report
- report << " # in file #{method.file.full_name}"
- report << param_report if param_report
- report << " def #{method.name}#{method.params}; end"
- report << nil
- end
-
- report
- end
-
- ##
- # Returns a summary of the collected statistics.
-
- def summary
- calculate
-
- num_width = [@num_files, @num_items].max.to_s.length
- undoc_width = [
- @undoc_attributes,
- @undoc_classes,
- @undoc_constants,
- @undoc_items,
- @undoc_methods,
- @undoc_modules,
- @undoc_params,
- ].max.to_s.length
-
- report = []
- report << 'Files: %*d' % [num_width, @num_files]
-
- report << nil
-
- report << 'Classes: %*d (%*d undocumented)' % [
- num_width, @num_classes, undoc_width, @undoc_classes]
- report << 'Modules: %*d (%*d undocumented)' % [
- num_width, @num_modules, undoc_width, @undoc_modules]
- report << 'Constants: %*d (%*d undocumented)' % [
- num_width, @num_constants, undoc_width, @undoc_constants]
- report << 'Attributes: %*d (%*d undocumented)' % [
- num_width, @num_attributes, undoc_width, @undoc_attributes]
- report << 'Methods: %*d (%*d undocumented)' % [
- num_width, @num_methods, undoc_width, @undoc_methods]
- report << 'Parameters: %*d (%*d undocumented)' % [
- num_width, @num_params, undoc_width, @undoc_params] if
- @coverage_level > 0
-
- report << nil
-
- report << 'Total: %*d (%*d undocumented)' % [
- num_width, @num_items, undoc_width, @undoc_items]
-
- report << '%6.2f%% documented' % percent_doc
- report << nil
- report << 'Elapsed: %0.1fs' % (Time.now - @start)
-
- report.join "\n"
- end
-
- ##
- # Determines which parameters in +method+ were not documented. Returns a
- # total parameter count and an Array of undocumented methods.
-
- def undoc_params method
- @formatter ||= RDoc::Markup::ToTtOnly.new
-
- params = method.param_list
-
- return 0, [] if params.empty?
-
- document = parse method.comment
-
- tts = document.accept @formatter
-
- undoc = params - tts
-
- [params.length, undoc]
- end
-
- autoload :Quiet, 'rdoc/stats/quiet'
- autoload :Normal, 'rdoc/stats/normal'
- autoload :Verbose, 'rdoc/stats/verbose'
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/stats/normal.rb b/ruby_1_9_3/lib/rdoc/stats/normal.rb
deleted file mode 100644
index c971973bf1..0000000000
--- a/ruby_1_9_3/lib/rdoc/stats/normal.rb
+++ /dev/null
@@ -1,48 +0,0 @@
-##
-# Stats printer that prints just the files being documented with a progress
-# bar
-
-class RDoc::Stats::Normal < RDoc::Stats::Quiet
-
- def begin_adding # :nodoc:
- puts "Parsing sources..." if $stdout.tty?
- end
-
- ##
- # Prints a file with a progress bar
-
- def print_file files_so_far, filename
- return unless $stdout.tty?
-
- progress_bar = sprintf("%3d%% [%2d/%2d] ",
- 100 * files_so_far / @num_files,
- files_so_far,
- @num_files)
-
- # Print a progress bar, but make sure it fits on a single line. Filename
- # will be truncated if necessary.
- terminal_width = (ENV['COLUMNS'] || 80).to_i
- max_filename_size = terminal_width - progress_bar.size
-
- if filename.size > max_filename_size then
- # Turn "some_long_filename.rb" to "...ong_filename.rb"
- filename = filename[(filename.size - max_filename_size) .. -1]
- filename[0..2] = "..."
- end
-
- # Pad the line with whitespaces so that leftover output from the
- # previous line doesn't show up.
- line = "#{progress_bar}#{filename}"
- padding = terminal_width - line.size
- line << (" " * padding) if padding > 0
-
- $stdout.print("#{line}\r")
- $stdout.flush
- end
-
- def done_adding # :nodoc:
- puts if $stdout.tty?
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/stats/quiet.rb b/ruby_1_9_3/lib/rdoc/stats/quiet.rb
deleted file mode 100644
index eed27b2a88..0000000000
--- a/ruby_1_9_3/lib/rdoc/stats/quiet.rb
+++ /dev/null
@@ -1,59 +0,0 @@
-##
-# Stats printer that prints nothing
-
-class RDoc::Stats::Quiet
-
- ##
- # Creates a new Quiet that will print nothing
-
- def initialize num_files
- @num_files = num_files
- end
-
- ##
- # Prints a message at the beginning of parsing
-
- def begin_adding(*) end
-
- ##
- # Prints when an alias is added
-
- def print_alias(*) end
-
- ##
- # Prints when an attribute is added
-
- def print_attribute(*) end
-
- ##
- # Prints when a class is added
-
- def print_class(*) end
-
- ##
- # Prints when a constant is added
-
- def print_constant(*) end
-
- ##
- # Prints when a file is added
-
- def print_file(*) end
-
- ##
- # Prints when a method is added
-
- def print_method(*) end
-
- ##
- # Prints when a module is added
-
- def print_module(*) end
-
- ##
- # Prints when RDoc is done
-
- def done_adding(*) end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/stats/verbose.rb b/ruby_1_9_3/lib/rdoc/stats/verbose.rb
deleted file mode 100644
index 430809ae07..0000000000
--- a/ruby_1_9_3/lib/rdoc/stats/verbose.rb
+++ /dev/null
@@ -1,45 +0,0 @@
-##
-# Stats printer that prints everything documented, including the documented
-# status
-
-class RDoc::Stats::Verbose < RDoc::Stats::Normal
-
- ##
- # Returns a marker for RDoc::CodeObject +co+ being undocumented
-
- def nodoc co
- " (undocumented)" unless co.documented?
- end
-
- def print_alias as # :nodoc:
- puts " alias #{as.new_name} #{as.old_name}#{nodoc as}"
- end
-
- def print_attribute attribute # :nodoc:
- puts " #{attribute.definition} #{attribute.name}#{nodoc attribute}"
- end
-
- def print_class(klass) # :nodoc:
- puts " class #{klass.full_name}#{nodoc klass}"
- end
-
- def print_constant(constant) # :nodoc:
- puts " #{constant.name}#{nodoc constant}"
- end
-
- def print_file(files_so_far, file) # :nodoc:
- super
- puts
- end
-
- def print_method(method) # :nodoc:
- puts " #{method.singleton ? '::' : '#'}#{method.name}#{nodoc method}"
- end
-
- def print_module(mod) # :nodoc:
- puts " module #{mod.full_name}#{nodoc mod}"
- end
-
-end
-
-
diff --git a/ruby_1_9_3/lib/rdoc/task.rb b/ruby_1_9_3/lib/rdoc/task.rb
deleted file mode 100644
index ec7459729a..0000000000
--- a/ruby_1_9_3/lib/rdoc/task.rb
+++ /dev/null
@@ -1,326 +0,0 @@
-#--
-# Copyright (c) 2003, 2004 Jim Weirich, 2009 Eric Hodel
-#
-# Permission is hereby granted, free of charge, to any person obtaining
-# a copy of this software and associated documentation files (the
-# "Software"), to deal in the Software without restriction, including
-# without limitation the rights to use, copy, modify, merge, publish,
-# distribute, sublicense, and/or sell copies of the Software, and to
-# permit persons to whom the Software is furnished to do so, subject to
-# the following conditions:
-#
-# The above copyright notice and this permission notice shall be
-# included in all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-#++
-
-require 'rubygems'
-begin
- gem 'rdoc'
-rescue Gem::LoadError
-end
-
-begin
- gem 'rake'
-rescue Gem::LoadError
-end
-
-require 'rdoc'
-require 'rake'
-require 'rake/tasklib'
-
-##
-# RDoc::Task creates the following rake tasks to generate and clean up RDoc
-# output:
-#
-# [rdoc]
-# Main task for this RDoc task.
-#
-# [clobber_rdoc]
-# Delete all the rdoc files. This target is automatically added to the main
-# clobber target.
-#
-# [rerdoc]
-# Rebuild the rdoc files from scratch, even if they are not out of date.
-#
-# Simple Example:
-#
-# gem 'rdoc'
-# require 'rdoc/task'
-#
-# RDoc::Task.new do |rdoc|
-# rdoc.main = "README.rdoc"
-# rdoc.rdoc_files.include("README.rdoc", "lib/**/*.rb")
-# end
-#
-# The +rdoc+ object passed to the block is an RDoc::Task object. See the
-# attributes list for the RDoc::Task class for available customization options.
-#
-# == Specifying different task names
-#
-# You may wish to give the task a different name, such as if you are
-# generating two sets of documentation. For instance, if you want to have a
-# development set of documentation including private methods:
-#
-# gem 'rdoc'
-# require 'rdoc/task'
-#
-# RDoc::Task.new :rdoc_dev do |rdoc|
-# rdoc.main = "README.doc"
-# rdoc.rdoc_files.include("README.rdoc", "lib/**/*.rb")
-# rdoc.options << "--all"
-# end
-#
-# The tasks would then be named :<em>rdoc_dev</em>,
-# :clobber_<em>rdoc_dev</em>, and :re<em>rdoc_dev</em>.
-#
-# If you wish to have completely different task names, then pass a Hash as
-# first argument. With the <tt>:rdoc</tt>, <tt>:clobber_rdoc</tt> and
-# <tt>:rerdoc</tt> options, you can customize the task names to your liking.
-#
-# For example:
-#
-# gem 'rdoc'
-# require 'rdoc/task'
-#
-# RDoc::Task.new(:rdoc => "rdoc", :clobber_rdoc => "rdoc:clean",
-# :rerdoc => "rdoc:force")
-#
-# This will create the tasks <tt>:rdoc</tt>, <tt>:rdoc:clean</tt> and
-# <tt>:rdoc:force</tt>.
-
-class RDoc::Task < Rake::TaskLib
-
- ##
- # Name of the main, top level task. (default is :rdoc)
-
- attr_accessor :name
-
- ##
- # Name of directory to receive the html output files. (default is "html")
-
- attr_accessor :rdoc_dir
-
- ##
- # Title of RDoc documentation. (defaults to rdoc's default)
-
- attr_accessor :title
-
- ##
- # Name of file to be used as the main, top level file of the RDoc. (default
- # is none)
-
- attr_accessor :main
-
- ##
- # Name of template to be used by rdoc. (defaults to rdoc's default)
-
- attr_accessor :template
-
- ##
- # Name of format generator (--fmt) used by rdoc. (defaults to rdoc's default)
-
- attr_accessor :generator
-
- ##
- # List of files to be included in the rdoc generation. (default is [])
-
- attr_accessor :rdoc_files
-
- ##
- # Additional list of options to be passed rdoc. (default is [])
-
- attr_accessor :options
-
- ##
- # Whether to run the rdoc process as an external shell (default is false)
-
- attr_accessor :external
-
- ##
- # Create an RDoc task with the given name. See the RDoc::Task class overview
- # for documentation.
-
- def initialize name = :rdoc # :yield: self
- defaults
-
- check_names name
-
- @name = name
-
- yield self if block_given?
-
- define
- end
-
- ##
- # Ensures that +names+ only includes names for the :rdoc, :clobber_rdoc and
- # :rerdoc. If other names are given an ArgumentError is raised.
-
- def check_names names
- return unless Hash === names
-
- invalid_options =
- names.keys.map { |k| k.to_sym } - [:rdoc, :clobber_rdoc, :rerdoc]
-
- unless invalid_options.empty? then
- raise ArgumentError, "invalid options: #{invalid_options.join ', '}"
- end
- end
-
- ##
- # Task description for the clobber rdoc task or its renamed equivalent
-
- def clobber_task_description
- "Remove RDoc HTML files"
- end
-
- ##
- # Sets default task values
-
- def defaults
- @name = :rdoc
- @rdoc_files = Rake::FileList.new
- @rdoc_dir = 'html'
- @main = nil
- @title = nil
- @template = nil
- @generator = nil
- @options = []
- end
-
- ##
- # All source is inline now. This method is deprecated
-
- def inline_source # :nodoc:
- warn "RDoc::Task#inline_source is deprecated"
- true
- end
-
- ##
- # All source is inline now. This method is deprecated
-
- def inline_source=(value) # :nodoc:
- warn "RDoc::Task#inline_source is deprecated"
- end
-
- ##
- # Create the tasks defined by this task lib.
-
- def define
- desc rdoc_task_description
- task rdoc_task_name
-
- desc rerdoc_task_description
- task rerdoc_task_name => [clobber_task_name, rdoc_task_name]
-
- desc clobber_task_description
- task clobber_task_name do
- rm_r @rdoc_dir rescue nil
- end
-
- task :clobber => [clobber_task_name]
-
- directory @rdoc_dir
-
- rdoc_target_deps = [
- @rdoc_files,
- Rake.application.rakefile
- ].flatten.compact
-
- task rdoc_task_name => [rdoc_target]
- file rdoc_target => rdoc_target_deps do
- @before_running_rdoc.call if @before_running_rdoc
- args = option_list + @rdoc_files
-
- $stderr.puts "rdoc #{args.join ' '}" if Rake.application.options.trace
- require 'rdoc/rdoc'
- RDoc::RDoc.new.document args
- end
-
- self
- end
-
- ##
- # List of options that will be supplied to RDoc
-
- def option_list
- result = @options.dup
- result << "-o" << @rdoc_dir
- result << "--main" << main if main
- result << "--title" << title if title
- result << "-T" << template if template
- result << '-f' << generator if generator
- result
- end
-
- ##
- # The block passed to this method will be called just before running the
- # RDoc generator. It is allowed to modify RDoc::Task attributes inside the
- # block.
-
- def before_running_rdoc(&block)
- @before_running_rdoc = block
- end
-
- ##
- # Task description for the rdoc task or its renamed equivalent
-
- def rdoc_task_description
- 'Build RDoc HTML files'
- end
-
- ##
- # Task description for the rerdoc task or its renamed description
-
- def rerdoc_task_description
- "Rebuild RDoc HTML files"
- end
-
- private
-
- def rdoc_target
- "#{rdoc_dir}/index.html"
- end
-
- def rdoc_task_name
- case name
- when Hash then (name[:rdoc] || "rdoc").to_s
- else name.to_s
- end
- end
-
- def clobber_task_name
- case name
- when Hash then (name[:clobber_rdoc] || "clobber_rdoc").to_s
- else "clobber_#{name}"
- end
- end
-
- def rerdoc_task_name
- case name
- when Hash then (name[:rerdoc] || "rerdoc").to_s
- else "re#{name}"
- end
- end
-
-end
-
-# :stopdoc:
-module Rake
-
- ##
- # For backwards compatibility
-
- RDocTask = RDoc::Task
-
-end
-# :startdoc:
-
diff --git a/ruby_1_9_3/lib/rdoc/text.rb b/ruby_1_9_3/lib/rdoc/text.rb
deleted file mode 100644
index 3ac55ed560..0000000000
--- a/ruby_1_9_3/lib/rdoc/text.rb
+++ /dev/null
@@ -1,302 +0,0 @@
-# coding: utf-8
-
-##
-# For RDoc::Text#to_html
-
-require 'strscan'
-
-##
-# Methods for manipulating comment text
-
-module RDoc::Text
-
- ##
- # Maps an encoding to a Hash of characters properly transcoded for that
- # encoding.
- #
- # See also encode_fallback.
-
- TO_HTML_CHARACTERS = Hash.new do |h, encoding|
- h[encoding] = {
- :close_dquote => encode_fallback('â€', encoding, '"'),
- :close_squote => encode_fallback('’', encoding, '\''),
- :copyright => encode_fallback('©', encoding, '(c)'),
- :ellipsis => encode_fallback('…', encoding, '...'),
- :em_dash => encode_fallback('—', encoding, '---'),
- :en_dash => encode_fallback('–', encoding, '--'),
- :open_dquote => encode_fallback('“', encoding, '"'),
- :open_squote => encode_fallback('‘', encoding, '\''),
- :trademark => encode_fallback('®', encoding, '(r)'),
- }
- end if Object.const_defined? :Encoding
-
- ##
- # Transcodes +character+ to +encoding+ with a +fallback+ character.
-
- def self.encode_fallback character, encoding, fallback
- character.encode(encoding, :fallback => { character => fallback },
- :undef => :replace, :replace => fallback)
- end
-
- ##
- # Expands tab characters in +text+ to eight spaces
-
- def expand_tabs text
- expanded = []
-
- text.each_line do |line|
- line.gsub!(/^(.{8}*?)([^\t\r\n]{0,7})\t/) do
- r = "#{$1}#{$2}#{' ' * (8 - $2.size)}"
- r.force_encoding text.encoding if Object.const_defined? :Encoding
- r
- end until line !~ /\t/
-
- expanded << line
- end
-
- expanded.join
- end
-
- ##
- # Flush +text+ left based on the shortest line
-
- def flush_left text
- indent = 9999
-
- text.each_line do |line|
- line_indent = line =~ /\S/ || 9999
- indent = line_indent if indent > line_indent
- end
-
- empty = ''
- empty.force_encoding text.encoding if Object.const_defined? :Encoding
-
- text.gsub(/^ {0,#{indent}}/, empty)
- end
-
- ##
- # Convert a string in markup format into HTML.
- #
- # Requires the including class to implement #formatter
-
- def markup text
- document = parse text
-
- document.accept formatter
- end
-
- ##
- # Strips hashes, expands tabs then flushes +text+ to the left
-
- def normalize_comment text
- return text if text.empty?
-
- text = strip_hashes text
- text = expand_tabs text
- text = flush_left text
- text = strip_newlines text
- text
- end
-
- ##
- # Normalizes +text+ then builds a RDoc::Markup::Document from it
-
- def parse text
- return text if RDoc::Markup::Document === text
-
- text = normalize_comment text
-
- return RDoc::Markup::Document.new if text =~ /\A\n*\z/
-
- RDoc::Markup::Parser.parse text
- rescue RDoc::Markup::Parser::Error => e
- $stderr.puts <<-EOF
-While parsing markup, RDoc encountered a #{e.class}:
-
-#{e}
-\tfrom #{e.backtrace.join "\n\tfrom "}
-
----8<---
-#{text}
----8<---
-
-RDoc #{RDoc::VERSION}
-
-Ruby #{RUBY_VERSION}-p#{RUBY_PATCHLEVEL} #{RUBY_RELEASE_DATE}
-
-Please file a bug report with the above information at:
-
-https://github.com/rdoc/rdoc/issues
-
- EOF
- raise
- end
-
- ##
- # Strips leading # characters from +text+
-
- def strip_hashes text
- return text if text =~ /^(?>\s*)[^\#]/
-
- empty = ''
- empty.force_encoding text.encoding if Object.const_defined? :Encoding
-
- text.gsub(/^\s*(#+)/) { $1.tr '#', ' ' }.gsub(/^\s+$/, empty)
- end
-
- ##
- # Strips leading and trailing \n characters from +text+
-
- def strip_newlines text
- text.gsub(/\A\n*(.*?)\n*\z/m) do $1 end # block preserves String encoding
- end
-
- ##
- # Strips /* */ style comments
-
- def strip_stars text
- encoding = text.encoding if Object.const_defined? :Encoding
-
- text = text.gsub %r%Document-method:\s+[\w:.#=!?]+%, ''
-
- space = ' '
- space.force_encoding encoding if encoding
-
- text.sub! %r%/\*+% do space * $&.length end
- text.sub! %r%\*+/% do space * $&.length end
- text.gsub! %r%^[ \t]*\*%m do space * $&.length end
-
- empty = ''
- empty.force_encoding encoding if encoding
- text.gsub(/^\s+$/, empty)
- end
-
- ##
- # Converts ampersand, dashes, ellipsis, quotes, copyright and registered
- # trademark symbols in +text+ to properly encoded characters.
-
- def to_html text
- if Object.const_defined? :Encoding then
- html = ''.encode text.encoding
-
- encoded = RDoc::Text::TO_HTML_CHARACTERS[text.encoding]
- else
- html = ''
- encoded = {
- :close_dquote => 'â€',
- :close_squote => '’',
- :copyright => '©',
- :ellipsis => '…',
- :em_dash => '—',
- :en_dash => '–',
- :open_dquote => '“',
- :open_squote => '‘',
- :trademark => '®',
- }
- end
-
- s = StringScanner.new text
- insquotes = false
- indquotes = false
- after_word = nil
-
- until s.eos? do
- case
- when s.scan(/<tt>.*?<\/tt>/) then # skip contents of tt
- html << s.matched.gsub('\\\\', '\\')
- when s.scan(/<tt>.*?/) then
- warn 'mismatched <tt> tag' # TODO signal file/line
- html << s.matched
- when s.scan(/<[^>]+\/?s*>/) then # skip HTML tags
- html << s.matched
- when s.scan(/\\(\S)/) then # unhandled suppressed crossref
- html << s[1]
- after_word = nil
- when s.scan(/\.\.\.(\.?)/) then
- html << s[1] << encoded[:ellipsis]
- after_word = nil
- when s.scan(/\(c\)/) then
- html << encoded[:copyright]
- after_word = nil
- when s.scan(/\(r\)/) then
- html << encoded[:trademark]
- after_word = nil
- when s.scan(/---/) then
- html << encoded[:em_dash]
- after_word = nil
- when s.scan(/--/) then
- html << encoded[:en_dash]
- after_word = nil
- when s.scan(/&quot;|"/) then
- html << encoded[indquotes ? :close_dquote : :open_dquote]
- indquotes = !indquotes
- after_word = nil
- when s.scan(/``/) then # backtick double quote
- html << encoded[:open_dquote]
- after_word = nil
- when s.scan(/''/) then # tick double quote
- html << encoded[:close_dquote]
- after_word = nil
- when s.scan(/'/) then # single quote
- if insquotes
- html << encoded[:close_squote]
- insquotes = false
- elsif after_word
- # Mary's dog, my parents' house: do not start paired quotes
- html << encoded[:close_squote]
- else
- html << encoded[:open_squote]
- insquotes = true
- end
-
- after_word = nil
- else # advance to the next potentially significant character
- match = s.scan(/.+?(?=[<\\.("'`&-])/) #"
-
- if match then
- html << match
- after_word = match =~ /\w$/
- else
- html << s.rest
- break
- end
- end
- end
-
- html
- end
-
- ##
- # Wraps +txt+ to +line_len+
-
- 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.join.strip
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/token_stream.rb b/ruby_1_9_3/lib/rdoc/token_stream.rb
deleted file mode 100644
index fb887f2fa4..0000000000
--- a/ruby_1_9_3/lib/rdoc/token_stream.rb
+++ /dev/null
@@ -1,50 +0,0 @@
-##
-# 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 RDoc::TokenStream
-
- ##
- # Adds +tokens+ to the collected tokens
-
- def add_tokens(*tokens)
- tokens.flatten.each { |token| @token_stream << token }
- end
-
- alias add_token add_tokens
-
- ##
- # Starts collecting tokens
-
- def collect_tokens
- @token_stream = []
- end
-
- alias start_collecting_tokens collect_tokens
-
- ##
- # Remove the last token from the collected tokens
-
- def pop_token
- @token_stream.pop
- end
-
- ##
- # Current token stream
-
- def token_stream
- @token_stream
- end
-
- ##
- # Returns a string representation of the token stream
-
- def tokens_to_s
- token_stream.map { |token| token.text }.join ''
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rdoc/top_level.rb b/ruby_1_9_3/lib/rdoc/top_level.rb
deleted file mode 100644
index 3825a091fe..0000000000
--- a/ruby_1_9_3/lib/rdoc/top_level.rb
+++ /dev/null
@@ -1,474 +0,0 @@
-require 'rdoc/context'
-
-##
-# A TopLevel context is a representation of the contents of a single file
-
-class RDoc::TopLevel < RDoc::Context
-
- ##
- # This TopLevel's File::Stat struct
-
- attr_accessor :file_stat
-
- ##
- # Relative name of this file
-
- attr_accessor :relative_name
-
- ##
- # Absolute name of this file
-
- attr_accessor :absolute_name
-
- ##
- # All the classes or modules that were declared in
- # this file. These are assigned to either +#classes_hash+
- # or +#modules_hash+ once we know what they really are.
-
- attr_reader :classes_or_modules
-
- attr_accessor :diagram # :nodoc:
-
- ##
- # The parser that processed this file
-
- attr_accessor :parser
-
- ##
- # Returns all classes discovered by RDoc
-
- def self.all_classes
- @all_classes_hash.values
- end
-
- ##
- # Returns all classes and modules discovered by RDoc
-
- def self.all_classes_and_modules
- @all_classes_hash.values + @all_modules_hash.values
- end
-
- ##
- # Hash of all classes known to RDoc
-
- def self.all_classes_hash
- @all_classes_hash
- end
-
- ##
- # All TopLevels known to RDoc
-
- def self.all_files
- @all_files_hash.values
- end
-
- ##
- # Hash of all files known to RDoc
-
- def self.all_files_hash
- @all_files_hash
- end
-
- ##
- # Returns all modules discovered by RDoc
-
- def self.all_modules
- all_modules_hash.values
- end
-
- ##
- # Hash of all modules known to RDoc
-
- def self.all_modules_hash
- @all_modules_hash
- end
-
- ##
- # Prepares the RDoc code object tree for use by a generator.
- #
- # It finds unique classes/modules defined, and replaces classes/modules that
- # are aliases for another one by a copy with RDoc::ClassModule#is_alias_for
- # set.
- #
- # It updates the RDoc::ClassModule#constant_aliases attribute of "real"
- # classes or modules.
- #
- # It also completely removes the classes and modules that should be removed
- # from the documentation and the methods that have a visibility below
- # +min_visibility+, which is the <tt>--visibility</tt> option.
- #
- # See also RDoc::Context#remove_from_documentation?
-
- def self.complete min_visibility
- fix_basic_object_inheritance
-
- # cache included modules before they are removed from the documentation
- all_classes_and_modules.each { |cm| cm.ancestors }
-
- remove_nodoc @all_classes_hash
- remove_nodoc @all_modules_hash
-
- @unique_classes = find_unique @all_classes_hash
- @unique_modules = find_unique @all_modules_hash
-
- unique_classes_and_modules.each do |cm|
- cm.complete min_visibility
- end
-
- @all_files_hash.each_key do |file_name|
- tl = @all_files_hash[file_name]
-
- unless RDoc::Parser::Simple === tl.parser then
- tl.modules_hash.clear
- tl.classes_hash.clear
-
- tl.classes_or_modules.each do |cm|
- name = cm.full_name
- if cm.type == 'class' then
- tl.classes_hash[name] = cm if @all_classes_hash[name]
- else
- tl.modules_hash[name] = cm if @all_modules_hash[name]
- end
- end
- end
- end
- end
-
- ##
- # Finds the class with +name+ in all discovered classes
-
- def self.find_class_named(name)
- @all_classes_hash[name]
- end
-
- ##
- # Finds the class with +name+ starting in namespace +from+
-
- def self.find_class_named_from name, from
- from = find_class_named from unless RDoc::Context === from
-
- until RDoc::TopLevel === from do
- return nil unless from
-
- klass = from.find_class_named name
- return klass if klass
-
- from = from.parent
- end
-
- find_class_named name
- end
-
- ##
- # Finds the class or module with +name+
-
- def self.find_class_or_module(name)
- name = $' if name =~ /^::/
- RDoc::TopLevel.classes_hash[name] || RDoc::TopLevel.modules_hash[name]
- end
-
- ##
- # Finds the file with +name+ in all discovered files
-
- def self.find_file_named(name)
- @all_files_hash[name]
- end
-
- ##
- # Finds the module with +name+ in all discovered modules
-
- def self.find_module_named(name)
- modules_hash[name]
- end
-
- ##
- # Finds unique classes/modules defined in +all_hash+,
- # and returns them as an array. Performs the alias
- # updates in +all_hash+: see ::complete.
- #--
- # TODO aliases should be registered by Context#add_module_alias
-
- def self.find_unique(all_hash)
- unique = []
-
- all_hash.each_pair do |full_name, cm|
- unique << cm if full_name == cm.full_name
- end
-
- unique
- end
-
- ##
- # Fixes the erroneous <tt>BasicObject < Object</tt> in 1.9.
- #
- # Because we assumed all classes without a stated superclass
- # inherit from Object, we have the above wrong inheritance.
- #
- # We fix BasicObject right away if we are running in a Ruby
- # version >= 1.9. If not, we may be documenting 1.9 source
- # while running under 1.8: we search the files of BasicObject
- # for "object.c", and fix the inheritance if we find it.
-
- def self.fix_basic_object_inheritance
- basic = all_classes_hash['BasicObject']
- return unless basic
- if RUBY_VERSION >= '1.9'
- basic.superclass = nil
- elsif basic.in_files.any? { |f| File.basename(f.full_name) == 'object.c' }
- basic.superclass = nil
- end
- end
-
- ##
- # Creates a new RDoc::TopLevel with +file_name+ only if one with the same
- # name does not exist in all_files.
-
- def self.new file_name
- if top_level = @all_files_hash[file_name] then
- top_level
- else
- top_level = super
- @all_files_hash[file_name] = top_level
- top_level
- end
- end
-
- ##
- # Removes from +all_hash+ the contexts that are nodoc or have no content.
- #
- # See RDoc::Context#remove_from_documentation?
-
- def self.remove_nodoc(all_hash)
- all_hash.keys.each do |name|
- context = all_hash[name]
- all_hash.delete(name) if context.remove_from_documentation?
- end
- end
-
- ##
- # Empties RDoc of stored class, module and file information
-
- def self.reset
- @all_classes_hash = {}
- @all_modules_hash = {}
- @all_files_hash = {}
- end
-
- ##
- # Returns the unique classes discovered by RDoc.
- #
- # ::complete must have been called prior to using this method.
-
- def self.unique_classes
- @unique_classes
- end
-
- ##
- # Returns the unique classes and modules discovered by RDoc.
- # ::complete must have been called prior to using this method.
-
- def self.unique_classes_and_modules
- @unique_classes + @unique_modules
- end
-
- ##
- # Returns the unique modules discovered by RDoc.
- # ::complete must have been called prior to using this method.
-
- def self.unique_modules
- @unique_modules
- end
-
- class << self
- alias classes all_classes
- alias classes_hash all_classes_hash
-
- alias files all_files
- alias files_hash all_files_hash
-
- alias modules all_modules
- alias modules_hash all_modules_hash
- end
-
- reset
-
- ##
- # Creates a new TopLevel for +file_name+
-
- def initialize(file_name)
- super()
- @name = nil
- @relative_name = file_name
- @absolute_name = file_name
- @file_stat = File.stat(file_name) rescue nil # HACK for testing
- @diagram = nil
- @parser = nil
-
- @classes_or_modules = []
-
- RDoc::TopLevel.files_hash[file_name] = self
- end
-
- ##
- # An RDoc::TopLevel is equal to another with the same absolute_name
-
- def == other
- other.class === self and @absolute_name == other.absolute_name
- end
-
- alias eql? ==
-
- ##
- # Adds +an_alias+ to +Object+ instead of +self+.
-
- def add_alias(an_alias)
- object_class.record_location self
- return an_alias unless @document_self
- object_class.add_alias an_alias
- end
-
- ##
- # Adds +constant+ to +Object+ instead of +self+.
-
- def add_constant(constant)
- object_class.record_location self
- return constant unless @document_self
- object_class.add_constant constant
- end
-
- ##
- # Adds +include+ to +Object+ instead of +self+.
-
- def add_include(include)
- object_class.record_location self
- return include unless @document_self
- object_class.add_include include
- end
-
- ##
- # Adds +method+ to +Object+ instead of +self+.
-
- def add_method(method)
- object_class.record_location self
- return method unless @document_self
- object_class.add_method method
- end
-
- ##
- # Adds class or module +mod+. Used in the building phase
- # by the ruby parser.
-
- def add_to_classes_or_modules mod
- @classes_or_modules << mod
- end
-
- ##
- # Base name of this file
-
- def base_name
- File.basename @absolute_name
- end
-
- alias name base_name
-
- ##
- # See RDoc::TopLevel::find_class_or_module
- #--
- # TODO Why do we search through all classes/modules found, not just the
- # ones of this instance?
-
- def find_class_or_module name
- RDoc::TopLevel.find_class_or_module name
- end
-
- ##
- # Finds a class or module named +symbol+
-
- def find_local_symbol(symbol)
- find_class_or_module(symbol) || super
- end
-
- ##
- # Finds a module or class with +name+
-
- def find_module_named(name)
- find_class_or_module(name)
- end
-
- ##
- # Returns the relative name of this file
-
- def full_name
- @relative_name
- end
-
- ##
- # An RDoc::TopLevel has the same hash as another with the same
- # absolute_name
-
- def hash
- @absolute_name.hash
- end
-
- ##
- # URL for this with a +prefix+
-
- def http_url(prefix)
- path = [prefix, @relative_name.tr('.', '_')]
-
- File.join(*path.compact) + '.html'
- end
-
- def inspect # :nodoc:
- "#<%s:0x%x %p modules: %p classes: %p>" % [
- self.class, object_id,
- base_name,
- @modules.map { |n,m| m },
- @classes.map { |n,c| c }
- ]
- end
-
- ##
- # Time this file was last modified, if known
-
- def last_modified
- @file_stat ? file_stat.mtime : nil
- end
-
- ##
- # Returns the NormalClass "Object", creating it if not found.
- #
- # Records +self+ as a location in "Object".
-
- def object_class
- @object_class ||= begin
- oc = self.class.find_class_named('Object') || add_class(RDoc::NormalClass, 'Object')
- oc.record_location self
- oc
- end
- end
-
- ##
- # Path to this file
-
- def path
- http_url RDoc::RDoc.current.generator.file_dir
- end
-
- def pretty_print q # :nodoc:
- q.group 2, "[#{self.class}: ", "]" do
- q.text "base name: #{base_name.inspect}"
- q.breakable
-
- items = @modules.map { |n,m| m }
- items.push(*@modules.map { |n,c| c })
- q.seplist items do |mod| q.pp mod end
- end
- end
-
- def to_s # :nodoc:
- "file #{full_name}"
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/resolv-replace.rb b/ruby_1_9_3/lib/resolv-replace.rb
deleted file mode 100644
index ff34f90db4..0000000000
--- a/ruby_1_9_3/lib/resolv-replace.rb
+++ /dev/null
@@ -1,74 +0,0 @@
-require 'socket'
-require 'resolv'
-
-class << IPSocket
- # :stopdoc:
- alias original_resolv_getaddress getaddress
- # :startdoc:
- def getaddress(host)
- begin
- return Resolv.getaddress(host).to_s
- rescue Resolv::ResolvError
- raise SocketError, "Hostname not known: #{host}"
- end
- end
-end
-
-class TCPSocket < IPSocket
- # :stopdoc:
- alias original_resolv_initialize initialize
- # :startdoc:
- def initialize(host, serv, *rest)
- rest[0] = IPSocket.getaddress(rest[0]) unless rest.empty?
- original_resolv_initialize(IPSocket.getaddress(host), serv, *rest)
- end
-end
-
-class UDPSocket < IPSocket
- # :stopdoc:
- alias original_resolv_bind bind
- # :startdoc:
- def bind(host, port)
- host = IPSocket.getaddress(host) if host != ""
- original_resolv_bind(host, port)
- end
-
- # :stopdoc:
- alias original_resolv_connect connect
- # :startdoc:
- def connect(host, port)
- original_resolv_connect(IPSocket.getaddress(host), port)
- end
-
- # :stopdoc:
- alias original_resolv_send send
- # :startdoc:
- def send(mesg, flags, *rest)
- if rest.length == 2
- host, port = rest
- begin
- addrs = Resolv.getaddresses(host)
- rescue Resolv::ResolvError
- raise SocketError, "Hostname not known: #{host}"
- end
- addrs[0...-1].each {|addr|
- begin
- return original_resolv_send(mesg, flags, addr, port)
- rescue SystemCallError
- end
- }
- original_resolv_send(mesg, flags, addrs[-1], port)
- else
- original_resolv_send(mesg, flags, *rest)
- end
- end
-end
-
-class SOCKSSocket < TCPSocket
- # :stopdoc:
- alias original_resolv_initialize initialize
- # :startdoc:
- def initialize(host, serv)
- original_resolv_initialize(IPSocket.getaddress(host), port)
- end
-end if defined? SOCKSSocket
diff --git a/ruby_1_9_3/lib/resolv.rb b/ruby_1_9_3/lib/resolv.rb
deleted file mode 100644
index 1e1889370a..0000000000
--- a/ruby_1_9_3/lib/resolv.rb
+++ /dev/null
@@ -1,2363 +0,0 @@
-require 'socket'
-require 'fcntl'
-require 'timeout'
-require 'thread'
-
-begin
- require 'securerandom'
-rescue LoadError
-end
-
-# Resolv is a thread-aware DNS resolver library written in Ruby. Resolv can
-# handle multiple DNS requests concurrently without blocking the entire ruby
-# interpreter.
-#
-# See also resolv-replace.rb to replace the libc resolver with Resolv.
-#
-# Resolv can look up various DNS resources using the DNS module directly.
-#
-# Examples:
-#
-# p Resolv.getaddress "www.ruby-lang.org"
-# p Resolv.getname "210.251.121.214"
-#
-# Resolv::DNS.open do |dns|
-# ress = dns.getresources "www.ruby-lang.org", Resolv::DNS::Resource::IN::A
-# p ress.map { |r| r.address }
-# ress = dns.getresources "ruby-lang.org", Resolv::DNS::Resource::IN::MX
-# p ress.map { |r| [r.exchange.to_s, r.preference] }
-# end
-#
-#
-# == Bugs
-#
-# * NIS is not supported.
-# * /etc/nsswitch.conf is not supported.
-
-class Resolv
-
- ##
- # Looks up the first IP address for +name+.
-
- def self.getaddress(name)
- DefaultResolver.getaddress(name)
- end
-
- ##
- # Looks up all IP address for +name+.
-
- def self.getaddresses(name)
- DefaultResolver.getaddresses(name)
- end
-
- ##
- # Iterates over all IP addresses for +name+.
-
- def self.each_address(name, &block)
- DefaultResolver.each_address(name, &block)
- end
-
- ##
- # Looks up the hostname of +address+.
-
- def self.getname(address)
- DefaultResolver.getname(address)
- end
-
- ##
- # Looks up all hostnames for +address+.
-
- def self.getnames(address)
- DefaultResolver.getnames(address)
- end
-
- ##
- # Iterates over all hostnames for +address+.
-
- def self.each_name(address, &proc)
- DefaultResolver.each_name(address, &proc)
- end
-
- ##
- # Creates a new Resolv using +resolvers+.
-
- def initialize(resolvers=[Hosts.new, DNS.new])
- @resolvers = resolvers
- end
-
- ##
- # Looks up the first IP address for +name+.
-
- def getaddress(name)
- each_address(name) {|address| return address}
- raise ResolvError.new("no address for #{name}")
- end
-
- ##
- # Looks up all IP address for +name+.
-
- def getaddresses(name)
- ret = []
- each_address(name) {|address| ret << address}
- return ret
- end
-
- ##
- # Iterates over all IP addresses for +name+.
-
- def each_address(name)
- if AddressRegex =~ name
- yield name
- return
- end
- yielded = false
- @resolvers.each {|r|
- r.each_address(name) {|address|
- yield address.to_s
- yielded = true
- }
- return if yielded
- }
- end
-
- ##
- # Looks up the hostname of +address+.
-
- def getname(address)
- each_name(address) {|name| return name}
- raise ResolvError.new("no name for #{address}")
- end
-
- ##
- # Looks up all hostnames for +address+.
-
- def getnames(address)
- ret = []
- each_name(address) {|name| ret << name}
- return ret
- end
-
- ##
- # Iterates over all hostnames for +address+.
-
- def each_name(address)
- yielded = false
- @resolvers.each {|r|
- r.each_name(address) {|name|
- yield name.to_s
- yielded = true
- }
- return if yielded
- }
- end
-
- ##
- # Indicates a failure to resolve a name or address.
-
- class ResolvError < StandardError; end
-
- ##
- # Indicates a timeout resolving a name or address.
-
- class ResolvTimeout < TimeoutError; end
-
- ##
- # Resolv::Hosts is a hostname resolver that uses the system hosts file.
-
- class Hosts
- if /mswin|mingw|bccwin/ =~ RUBY_PLATFORM
- require 'win32/resolv'
- DefaultFileName = Win32::Resolv.get_hosts_path
- else
- DefaultFileName = '/etc/hosts'
- end
-
- ##
- # Creates a new Resolv::Hosts, using +filename+ for its data source.
-
- def initialize(filename = DefaultFileName)
- @filename = filename
- @mutex = Mutex.new
- @initialized = nil
- end
-
- def lazy_initialize # :nodoc:
- @mutex.synchronize {
- unless @initialized
- @name2addr = {}
- @addr2name = {}
- open(@filename) {|f|
- f.each {|line|
- line.sub!(/#.*/, '')
- addr, hostname, *aliases = line.split(/\s+/)
- next unless addr
- addr.untaint
- hostname.untaint
- @addr2name[addr] = [] unless @addr2name.include? addr
- @addr2name[addr] << hostname
- @addr2name[addr] += aliases
- @name2addr[hostname] = [] unless @name2addr.include? hostname
- @name2addr[hostname] << addr
- aliases.each {|n|
- n.untaint
- @name2addr[n] = [] unless @name2addr.include? n
- @name2addr[n] << addr
- }
- }
- }
- @name2addr.each {|name, arr| arr.reverse!}
- @initialized = true
- end
- }
- self
- end
-
- ##
- # Gets the IP address of +name+ from the hosts file.
-
- def getaddress(name)
- each_address(name) {|address| return address}
- raise ResolvError.new("#{@filename} has no name: #{name}")
- end
-
- ##
- # Gets all IP addresses for +name+ from the hosts file.
-
- def getaddresses(name)
- ret = []
- each_address(name) {|address| ret << address}
- return ret
- end
-
- ##
- # Iterates over all IP addresses for +name+ retrieved from the hosts file.
-
- def each_address(name, &proc)
- lazy_initialize
- if @name2addr.include?(name)
- @name2addr[name].each(&proc)
- end
- end
-
- ##
- # Gets the hostname of +address+ from the hosts file.
-
- def getname(address)
- each_name(address) {|name| return name}
- raise ResolvError.new("#{@filename} has no address: #{address}")
- end
-
- ##
- # Gets all hostnames for +address+ from the hosts file.
-
- def getnames(address)
- ret = []
- each_name(address) {|name| ret << name}
- return ret
- end
-
- ##
- # Iterates over all hostnames for +address+ retrieved from the hosts file.
-
- def each_name(address, &proc)
- lazy_initialize
- if @addr2name.include?(address)
- @addr2name[address].each(&proc)
- end
- end
- end
-
- ##
- # Resolv::DNS is a DNS stub resolver.
- #
- # Information taken from the following places:
- #
- # * STD0013
- # * RFC 1035
- # * ftp://ftp.isi.edu/in-notes/iana/assignments/dns-parameters
- # * etc.
-
- class DNS
-
- ##
- # Default DNS Port
-
- Port = 53
-
- ##
- # Default DNS UDP packet size
-
- UDPSize = 512
-
- ##
- # Creates a new DNS resolver. See Resolv::DNS.new for argument details.
- #
- # Yields the created DNS resolver to the block, if given, otherwise
- # returns it.
-
- def self.open(*args)
- dns = new(*args)
- return dns unless block_given?
- begin
- yield dns
- ensure
- dns.close
- end
- end
-
- ##
- # Creates a new DNS resolver.
- #
- # +config_info+ can be:
- #
- # nil:: Uses /etc/resolv.conf.
- # String:: Path to a file using /etc/resolv.conf's format.
- # Hash:: Must contain :nameserver, :search and :ndots keys.
- # :nameserver_port can be used to specify port number of nameserver address.
- #
- # The value of :nameserver should be an address string or
- # an array of address strings.
- # - :nameserver => '8.8.8.8'
- # - :nameserver => ['8.8.8.8', '8.8.4.4']
- #
- # The value of :nameserver_port should be an array of
- # pair of nameserver address and port number.
- # - :nameserver_port => [['8.8.8.8', 53], ['8.8.4.4', 53]]
- #
- # Example:
- #
- # Resolv::DNS.new(:nameserver => ['210.251.121.21'],
- # :search => ['ruby-lang.org'],
- # :ndots => 1)
-
- def initialize(config_info=nil)
- @mutex = Mutex.new
- @config = Config.new(config_info)
- @initialized = nil
- end
-
- def lazy_initialize # :nodoc:
- @mutex.synchronize {
- unless @initialized
- @config.lazy_initialize
- @initialized = true
- end
- }
- self
- end
-
- ##
- # Closes the DNS resolver.
-
- def close
- @mutex.synchronize {
- if @initialized
- @initialized = false
- end
- }
- end
-
- ##
- # Gets the IP address of +name+ from the DNS resolver.
- #
- # +name+ can be a Resolv::DNS::Name or a String. Retrieved address will
- # be a Resolv::IPv4 or Resolv::IPv6
-
- def getaddress(name)
- each_address(name) {|address| return address}
- raise ResolvError.new("DNS result has no information for #{name}")
- end
-
- ##
- # Gets all IP addresses for +name+ from the DNS resolver.
- #
- # +name+ can be a Resolv::DNS::Name or a String. Retrieved addresses will
- # be a Resolv::IPv4 or Resolv::IPv6
-
- def getaddresses(name)
- ret = []
- each_address(name) {|address| ret << address}
- return ret
- end
-
- ##
- # Iterates over all IP addresses for +name+ retrieved from the DNS
- # resolver.
- #
- # +name+ can be a Resolv::DNS::Name or a String. Retrieved addresses will
- # be a Resolv::IPv4 or Resolv::IPv6
-
- def each_address(name)
- each_resource(name, Resource::IN::A) {|resource| yield resource.address}
- if use_ipv6?
- each_resource(name, Resource::IN::AAAA) {|resource| yield resource.address}
- end
- end
-
- def use_ipv6? # :nodoc:
- begin
- list = Socket.ip_address_list
- rescue NotImplementedError
- return true
- end
- list.any? {|a| a.ipv6? && !a.ipv6_loopback? && !a.ipv6_linklocal? }
- end
- private :use_ipv6?
-
- ##
- # Gets the hostname for +address+ from the DNS resolver.
- #
- # +address+ must be a Resolv::IPv4, Resolv::IPv6 or a String. Retrieved
- # name will be a Resolv::DNS::Name.
-
- def getname(address)
- each_name(address) {|name| return name}
- raise ResolvError.new("DNS result has no information for #{address}")
- end
-
- ##
- # Gets all hostnames for +address+ from the DNS resolver.
- #
- # +address+ must be a Resolv::IPv4, Resolv::IPv6 or a String. Retrieved
- # names will be Resolv::DNS::Name instances.
-
- def getnames(address)
- ret = []
- each_name(address) {|name| ret << name}
- return ret
- end
-
- ##
- # Iterates over all hostnames for +address+ retrieved from the DNS
- # resolver.
- #
- # +address+ must be a Resolv::IPv4, Resolv::IPv6 or a String. Retrieved
- # names will be Resolv::DNS::Name instances.
-
- def each_name(address)
- case address
- when Name
- ptr = address
- when IPv4::Regex
- ptr = IPv4.create(address).to_name
- when IPv6::Regex
- ptr = IPv6.create(address).to_name
- else
- raise ResolvError.new("cannot interpret as address: #{address}")
- end
- each_resource(ptr, Resource::IN::PTR) {|resource| yield resource.name}
- end
-
- ##
- # Look up the +typeclass+ DNS resource of +name+.
- #
- # +name+ must be a Resolv::DNS::Name or a String.
- #
- # +typeclass+ should be one of the following:
- #
- # * Resolv::DNS::Resource::IN::A
- # * Resolv::DNS::Resource::IN::AAAA
- # * Resolv::DNS::Resource::IN::ANY
- # * Resolv::DNS::Resource::IN::CNAME
- # * Resolv::DNS::Resource::IN::HINFO
- # * Resolv::DNS::Resource::IN::MINFO
- # * Resolv::DNS::Resource::IN::MX
- # * Resolv::DNS::Resource::IN::NS
- # * Resolv::DNS::Resource::IN::PTR
- # * Resolv::DNS::Resource::IN::SOA
- # * Resolv::DNS::Resource::IN::TXT
- # * Resolv::DNS::Resource::IN::WKS
- #
- # Returned resource is represented as a Resolv::DNS::Resource instance,
- # i.e. Resolv::DNS::Resource::IN::A.
-
- def getresource(name, typeclass)
- each_resource(name, typeclass) {|resource| return resource}
- raise ResolvError.new("DNS result has no information for #{name}")
- end
-
- ##
- # Looks up all +typeclass+ DNS resources for +name+. See #getresource for
- # argument details.
-
- def getresources(name, typeclass)
- ret = []
- each_resource(name, typeclass) {|resource| ret << resource}
- return ret
- end
-
- ##
- # Iterates over all +typeclass+ DNS resources for +name+. See
- # #getresource for argument details.
-
- def each_resource(name, typeclass, &proc)
- lazy_initialize
- requester = make_udp_requester
- senders = {}
- begin
- @config.resolv(name) {|candidate, tout, nameserver, port|
- msg = Message.new
- msg.rd = 1
- msg.add_question(candidate, typeclass)
- unless sender = senders[[candidate, nameserver, port]]
- sender = senders[[candidate, nameserver, port]] =
- requester.sender(msg, candidate, nameserver, port)
- end
- reply, reply_name = requester.request(sender, tout)
- case reply.rcode
- when RCode::NoError
- if reply.tc == 1 and not Requester::TCP === requester
- requester.close
- # Retry via TCP:
- requester = make_tcp_requester(nameserver, port)
- senders = {}
- # This will use TCP for all remaining candidates (assuming the
- # current candidate does not already respond successfully via
- # TCP). This makes sense because we already know the full
- # response will not fit in an untruncated UDP packet.
- redo
- else
- extract_resources(reply, reply_name, typeclass, &proc)
- end
- return
- when RCode::NXDomain
- raise Config::NXDomain.new(reply_name.to_s)
- else
- raise Config::OtherResolvError.new(reply_name.to_s)
- end
- }
- ensure
- requester.close
- end
- end
-
- def make_udp_requester # :nodoc:
- nameserver_port = @config.nameserver_port
- if nameserver_port.length == 1
- Requester::ConnectedUDP.new(*nameserver_port[0])
- else
- Requester::UnconnectedUDP.new(*nameserver_port)
- end
- end
-
- def make_tcp_requester(host, port) # :nodoc:
- return Requester::TCP.new(host, port)
- end
-
- def extract_resources(msg, name, typeclass) # :nodoc:
- if typeclass < Resource::ANY
- n0 = Name.create(name)
- msg.each_answer {|n, ttl, data|
- yield data if n0 == n
- }
- end
- yielded = false
- n0 = Name.create(name)
- msg.each_answer {|n, ttl, data|
- if n0 == n
- case data
- when typeclass
- yield data
- yielded = true
- when Resource::CNAME
- n0 = data.name
- end
- end
- }
- return if yielded
- msg.each_answer {|n, ttl, data|
- if n0 == n
- case data
- when typeclass
- yield data
- end
- end
- }
- end
-
- if defined? SecureRandom
- def self.random(arg) # :nodoc:
- begin
- SecureRandom.random_number(arg)
- rescue NotImplementedError
- rand(arg)
- end
- end
- else
- def self.random(arg) # :nodoc:
- rand(arg)
- end
- end
-
-
- def self.rangerand(range) # :nodoc:
- base = range.begin
- len = range.end - range.begin
- if !range.exclude_end?
- len += 1
- end
- base + random(len)
- end
-
- RequestID = {} # :nodoc:
- RequestIDMutex = Mutex.new # :nodoc:
-
- def self.allocate_request_id(host, port) # :nodoc:
- id = nil
- RequestIDMutex.synchronize {
- h = (RequestID[[host, port]] ||= {})
- begin
- id = rangerand(0x0000..0xffff)
- end while h[id]
- h[id] = true
- }
- id
- end
-
- def self.free_request_id(host, port, id) # :nodoc:
- RequestIDMutex.synchronize {
- key = [host, port]
- if h = RequestID[key]
- h.delete id
- if h.empty?
- RequestID.delete key
- end
- end
- }
- end
-
- def self.bind_random_port(udpsock, bind_host="0.0.0.0") # :nodoc:
- begin
- port = rangerand(1024..65535)
- udpsock.bind(bind_host, port)
- rescue Errno::EADDRINUSE
- retry
- end
- end
-
- class Requester # :nodoc:
- def initialize
- @senders = {}
- @socks = nil
- end
-
- def request(sender, tout)
- timelimit = Time.now + tout
- sender.send
- while true
- now = Time.now
- timeout = timelimit - now
- if timeout <= 0
- raise ResolvTimeout
- end
- select_result = IO.select(@socks, nil, nil, timeout)
- if !select_result
- raise ResolvTimeout
- end
- begin
- reply, from = recv_reply(select_result[0])
- rescue Errno::ECONNREFUSED, # GNU/Linux, FreeBSD
- Errno::ECONNRESET # Windows
- # No name server running on the server?
- # Don't wait anymore.
- raise ResolvTimeout
- end
- begin
- msg = Message.decode(reply)
- rescue DecodeError
- next # broken DNS message ignored
- end
- if s = @senders[[from,msg.id]]
- break
- else
- # unexpected DNS message ignored
- end
- end
- return msg, s.data
- end
-
- def close
- socks = @socks
- @socks = nil
- if socks
- socks.each {|sock| sock.close }
- end
- end
-
- class Sender # :nodoc:
- def initialize(msg, data, sock)
- @msg = msg
- @data = data
- @sock = sock
- end
- end
-
- class UnconnectedUDP < Requester # :nodoc:
- def initialize(*nameserver_port)
- super()
- @nameserver_port = nameserver_port
- @socks_hash = {}
- @socks = []
- nameserver_port.each {|host, port|
- if host.index(':')
- bind_host = "::"
- af = Socket::AF_INET6
- else
- bind_host = "0.0.0.0"
- af = Socket::AF_INET
- end
- next if @socks_hash[bind_host]
- sock = UDPSocket.new(af)
- sock.do_not_reverse_lookup = true
- sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) if defined? Fcntl::F_SETFD
- DNS.bind_random_port(sock, bind_host)
- @socks << sock
- @socks_hash[bind_host] = sock
- }
- end
-
- def recv_reply(readable_socks)
- reply, from = readable_socks[0].recvfrom(UDPSize)
- return reply, [from[3],from[1]]
- end
-
- def sender(msg, data, host, port=Port)
- service = [host, port]
- id = DNS.allocate_request_id(host, port)
- request = msg.encode
- request[0,2] = [id].pack('n')
- sock = @socks_hash[host.index(':') ? "::" : "0.0.0.0"]
- return @senders[[service, id]] =
- Sender.new(request, data, sock, host, port)
- end
-
- def close
- super
- @senders.each_key {|service, id|
- DNS.free_request_id(service[0], service[1], id)
- }
- end
-
- class Sender < Requester::Sender # :nodoc:
- def initialize(msg, data, sock, host, port)
- super(msg, data, sock)
- @host = host
- @port = port
- end
- attr_reader :data
-
- def send
- @sock.send(@msg, 0, @host, @port)
- end
- end
- end
-
- class ConnectedUDP < Requester # :nodoc:
- def initialize(host, port=Port)
- super()
- @host = host
- @port = port
- is_ipv6 = host.index(':')
- sock = UDPSocket.new(is_ipv6 ? Socket::AF_INET6 : Socket::AF_INET)
- @socks = [sock]
- sock.do_not_reverse_lookup = true
- sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) if defined? Fcntl::F_SETFD
- DNS.bind_random_port(sock, is_ipv6 ? "::" : "0.0.0.0")
- sock.connect(host, port)
- end
-
- def recv_reply(readable_socks)
- reply = readable_socks[0].recv(UDPSize)
- return reply, nil
- end
-
- def sender(msg, data, host=@host, port=@port)
- unless host == @host && port == @port
- raise RequestError.new("host/port don't match: #{host}:#{port}")
- end
- id = DNS.allocate_request_id(@host, @port)
- request = msg.encode
- request[0,2] = [id].pack('n')
- return @senders[[nil,id]] = Sender.new(request, data, @socks[0])
- end
-
- def close
- super
- @senders.each_key {|from, id|
- DNS.free_request_id(@host, @port, id)
- }
- end
-
- class Sender < Requester::Sender # :nodoc:
- def send
- @sock.send(@msg, 0)
- end
- attr_reader :data
- end
- end
-
- class TCP < Requester # :nodoc:
- def initialize(host, port=Port)
- super()
- @host = host
- @port = port
- sock = TCPSocket.new(@host, @port)
- @socks = [sock]
- sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) if defined? Fcntl::F_SETFD
- @senders = {}
- end
-
- def recv_reply(readable_socks)
- len = readable_socks[0].read(2).unpack('n')[0]
- reply = @socks[0].read(len)
- return reply, nil
- end
-
- def sender(msg, data, host=@host, port=@port)
- unless host == @host && port == @port
- raise RequestError.new("host/port don't match: #{host}:#{port}")
- end
- id = DNS.allocate_request_id(@host, @port)
- request = msg.encode
- request[0,2] = [request.length, id].pack('nn')
- return @senders[[nil,id]] = Sender.new(request, data, @socks[0])
- end
-
- class Sender < Requester::Sender # :nodoc:
- def send
- @sock.print(@msg)
- @sock.flush
- end
- attr_reader :data
- end
-
- def close
- super
- @senders.each_key {|from,id|
- DNS.free_request_id(@host, @port, id)
- }
- end
- end
-
- ##
- # Indicates a problem with the DNS request.
-
- class RequestError < StandardError
- end
- end
-
- class Config # :nodoc:
- def initialize(config_info=nil)
- @mutex = Mutex.new
- @config_info = config_info
- @initialized = nil
- end
-
- def Config.parse_resolv_conf(filename)
- nameserver = []
- search = nil
- ndots = 1
- open(filename) {|f|
- f.each {|line|
- line.sub!(/[#;].*/, '')
- keyword, *args = line.split(/\s+/)
- args.each { |arg|
- arg.untaint
- }
- next unless keyword
- case keyword
- when 'nameserver'
- nameserver += args
- when 'domain'
- next if args.empty?
- search = [args[0]]
- when 'search'
- next if args.empty?
- search = args
- when 'options'
- args.each {|arg|
- case arg
- when /\Andots:(\d+)\z/
- ndots = $1.to_i
- end
- }
- end
- }
- }
- return { :nameserver => nameserver, :search => search, :ndots => ndots }
- end
-
- def Config.default_config_hash(filename="/etc/resolv.conf")
- if File.exist? filename
- config_hash = Config.parse_resolv_conf(filename)
- else
- if /mswin|cygwin|mingw|bccwin/ =~ RUBY_PLATFORM
- require 'win32/resolv'
- search, nameserver = Win32::Resolv.get_resolv_info
- config_hash = {}
- config_hash[:nameserver] = nameserver if nameserver
- config_hash[:search] = [search].flatten if search
- end
- end
- config_hash || {}
- end
-
- def lazy_initialize
- @mutex.synchronize {
- unless @initialized
- @nameserver_port = []
- @search = nil
- @ndots = 1
- case @config_info
- when nil
- config_hash = Config.default_config_hash
- when String
- config_hash = Config.parse_resolv_conf(@config_info)
- when Hash
- config_hash = @config_info.dup
- if String === config_hash[:nameserver]
- config_hash[:nameserver] = [config_hash[:nameserver]]
- end
- if String === config_hash[:search]
- config_hash[:search] = [config_hash[:search]]
- end
- else
- raise ArgumentError.new("invalid resolv configuration: #{@config_info.inspect}")
- end
- if config_hash.include? :nameserver
- @nameserver_port = config_hash[:nameserver].map {|ns| [ns, Port] }
- end
- if config_hash.include? :nameserver_port
- @nameserver_port = config_hash[:nameserver_port].map {|ns, port| [ns, (port || Port)] }
- end
- @search = config_hash[:search] if config_hash.include? :search
- @ndots = config_hash[:ndots] if config_hash.include? :ndots
-
- if @nameserver_port.empty?
- @nameserver_port << ['0.0.0.0', Port]
- end
- if @search
- @search = @search.map {|arg| Label.split(arg) }
- else
- hostname = Socket.gethostname
- if /\./ =~ hostname
- @search = [Label.split($')]
- else
- @search = [[]]
- end
- end
-
- if !@nameserver_port.kind_of?(Array) ||
- @nameserver_port.any? {|ns_port|
- !(Array === ns_port) ||
- ns_port.length != 2
- !(String === ns_port[0]) ||
- !(Integer === ns_port[1])
- }
- raise ArgumentError.new("invalid nameserver config: #{@nameserver_port.inspect}")
- end
-
- if !@search.kind_of?(Array) ||
- !@search.all? {|ls| ls.all? {|l| Label::Str === l } }
- raise ArgumentError.new("invalid search config: #{@search.inspect}")
- end
-
- if !@ndots.kind_of?(Integer)
- raise ArgumentError.new("invalid ndots config: #{@ndots.inspect}")
- end
-
- @initialized = true
- end
- }
- self
- end
-
- def single?
- lazy_initialize
- if @nameserver_port.length == 1
- return @nameserver_port[0]
- else
- return nil
- end
- end
-
- def nameserver_port
- @nameserver_port
- end
-
- def generate_candidates(name)
- candidates = nil
- name = Name.create(name)
- if name.absolute?
- candidates = [name]
- else
- if @ndots <= name.length - 1
- candidates = [Name.new(name.to_a)]
- else
- candidates = []
- end
- candidates.concat(@search.map {|domain| Name.new(name.to_a + domain)})
- end
- return candidates
- end
-
- InitialTimeout = 5
-
- def generate_timeouts
- ts = [InitialTimeout]
- ts << ts[-1] * 2 / @nameserver_port.length
- ts << ts[-1] * 2
- ts << ts[-1] * 2
- return ts
- end
-
- def resolv(name)
- candidates = generate_candidates(name)
- timeouts = generate_timeouts
- begin
- candidates.each {|candidate|
- begin
- timeouts.each {|tout|
- @nameserver_port.each {|nameserver, port|
- begin
- yield candidate, tout, nameserver, port
- rescue ResolvTimeout
- end
- }
- }
- raise ResolvError.new("DNS resolv timeout: #{name}")
- rescue NXDomain
- end
- }
- rescue ResolvError
- end
- end
-
- ##
- # Indicates no such domain was found.
-
- class NXDomain < ResolvError
- end
-
- ##
- # Indicates some other unhandled resolver error was encountered.
-
- class OtherResolvError < ResolvError
- end
- end
-
- module OpCode # :nodoc:
- Query = 0
- IQuery = 1
- Status = 2
- Notify = 4
- Update = 5
- end
-
- module RCode # :nodoc:
- NoError = 0
- FormErr = 1
- ServFail = 2
- NXDomain = 3
- NotImp = 4
- Refused = 5
- YXDomain = 6
- YXRRSet = 7
- NXRRSet = 8
- NotAuth = 9
- NotZone = 10
- BADVERS = 16
- BADSIG = 16
- BADKEY = 17
- BADTIME = 18
- BADMODE = 19
- BADNAME = 20
- BADALG = 21
- end
-
- ##
- # Indicates that the DNS response was unable to be decoded.
-
- class DecodeError < StandardError
- end
-
- ##
- # Indicates that the DNS request was unable to be encoded.
-
- class EncodeError < StandardError
- end
-
- module Label # :nodoc:
- def self.split(arg)
- labels = []
- arg.scan(/[^\.]+/) {labels << Str.new($&)}
- return labels
- end
-
- class Str # :nodoc:
- def initialize(string)
- @string = string
- @downcase = string.downcase
- end
- attr_reader :string, :downcase
-
- def to_s
- return @string
- end
-
- def inspect
- return "#<#{self.class} #{self.to_s}>"
- end
-
- def ==(other)
- return @downcase == other.downcase
- end
-
- def eql?(other)
- return self == other
- end
-
- def hash
- return @downcase.hash
- end
- end
- end
-
- ##
- # A representation of a DNS name.
-
- class Name
-
- ##
- # Creates a new DNS name from +arg+. +arg+ can be:
- #
- # Name:: returns +arg+.
- # String:: Creates a new Name.
-
- def self.create(arg)
- case arg
- when Name
- return arg
- when String
- return Name.new(Label.split(arg), /\.\z/ =~ arg ? true : false)
- else
- raise ArgumentError.new("cannot interpret as DNS name: #{arg.inspect}")
- end
- end
-
- def initialize(labels, absolute=true) # :nodoc:
- @labels = labels
- @absolute = absolute
- end
-
- def inspect # :nodoc:
- "#<#{self.class}: #{self.to_s}#{@absolute ? '.' : ''}>"
- end
-
- ##
- # True if this name is absolute.
-
- def absolute?
- return @absolute
- end
-
- def ==(other) # :nodoc:
- return false unless Name === other
- return @labels.join == other.to_a.join && @absolute == other.absolute?
- end
-
- alias eql? == # :nodoc:
-
- ##
- # Returns true if +other+ is a subdomain.
- #
- # Example:
- #
- # domain = Resolv::DNS::Name.create("y.z")
- # p Resolv::DNS::Name.create("w.x.y.z").subdomain_of?(domain) #=> true
- # p Resolv::DNS::Name.create("x.y.z").subdomain_of?(domain) #=> true
- # p Resolv::DNS::Name.create("y.z").subdomain_of?(domain) #=> false
- # p Resolv::DNS::Name.create("z").subdomain_of?(domain) #=> false
- # p Resolv::DNS::Name.create("x.y.z.").subdomain_of?(domain) #=> false
- # p Resolv::DNS::Name.create("w.z").subdomain_of?(domain) #=> false
- #
-
- def subdomain_of?(other)
- raise ArgumentError, "not a domain name: #{other.inspect}" unless Name === other
- return false if @absolute != other.absolute?
- other_len = other.length
- return false if @labels.length <= other_len
- return @labels[-other_len, other_len] == other.to_a
- end
-
- def hash # :nodoc:
- return @labels.hash ^ @absolute.hash
- end
-
- def to_a # :nodoc:
- return @labels
- end
-
- def length # :nodoc:
- return @labels.length
- end
-
- def [](i) # :nodoc:
- return @labels[i]
- end
-
- ##
- # returns the domain name as a string.
- #
- # The domain name doesn't have a trailing dot even if the name object is
- # absolute.
- #
- # Example:
- #
- # p Resolv::DNS::Name.create("x.y.z.").to_s #=> "x.y.z"
- # p Resolv::DNS::Name.create("x.y.z").to_s #=> "x.y.z"
-
- def to_s
- return @labels.join('.')
- end
- end
-
- class Message # :nodoc:
- @@identifier = -1
-
- def initialize(id = (@@identifier += 1) & 0xffff)
- @id = id
- @qr = 0
- @opcode = 0
- @aa = 0
- @tc = 0
- @rd = 0 # recursion desired
- @ra = 0 # recursion available
- @rcode = 0
- @question = []
- @answer = []
- @authority = []
- @additional = []
- end
-
- attr_accessor :id, :qr, :opcode, :aa, :tc, :rd, :ra, :rcode
- attr_reader :question, :answer, :authority, :additional
-
- def ==(other)
- return @id == other.id &&
- @qr == other.qr &&
- @opcode == other.opcode &&
- @aa == other.aa &&
- @tc == other.tc &&
- @rd == other.rd &&
- @ra == other.ra &&
- @rcode == other.rcode &&
- @question == other.question &&
- @answer == other.answer &&
- @authority == other.authority &&
- @additional == other.additional
- end
-
- def add_question(name, typeclass)
- @question << [Name.create(name), typeclass]
- end
-
- def each_question
- @question.each {|name, typeclass|
- yield name, typeclass
- }
- end
-
- def add_answer(name, ttl, data)
- @answer << [Name.create(name), ttl, data]
- end
-
- def each_answer
- @answer.each {|name, ttl, data|
- yield name, ttl, data
- }
- end
-
- def add_authority(name, ttl, data)
- @authority << [Name.create(name), ttl, data]
- end
-
- def each_authority
- @authority.each {|name, ttl, data|
- yield name, ttl, data
- }
- end
-
- def add_additional(name, ttl, data)
- @additional << [Name.create(name), ttl, data]
- end
-
- def each_additional
- @additional.each {|name, ttl, data|
- yield name, ttl, data
- }
- end
-
- def each_resource
- each_answer {|name, ttl, data| yield name, ttl, data}
- each_authority {|name, ttl, data| yield name, ttl, data}
- each_additional {|name, ttl, data| yield name, ttl, data}
- end
-
- def encode
- return MessageEncoder.new {|msg|
- msg.put_pack('nnnnnn',
- @id,
- (@qr & 1) << 15 |
- (@opcode & 15) << 11 |
- (@aa & 1) << 10 |
- (@tc & 1) << 9 |
- (@rd & 1) << 8 |
- (@ra & 1) << 7 |
- (@rcode & 15),
- @question.length,
- @answer.length,
- @authority.length,
- @additional.length)
- @question.each {|q|
- name, typeclass = q
- msg.put_name(name)
- msg.put_pack('nn', typeclass::TypeValue, typeclass::ClassValue)
- }
- [@answer, @authority, @additional].each {|rr|
- rr.each {|r|
- name, ttl, data = r
- msg.put_name(name)
- msg.put_pack('nnN', data.class::TypeValue, data.class::ClassValue, ttl)
- msg.put_length16 {data.encode_rdata(msg)}
- }
- }
- }.to_s
- end
-
- class MessageEncoder # :nodoc:
- def initialize
- @data = ''
- @names = {}
- yield self
- end
-
- def to_s
- return @data
- end
-
- def put_bytes(d)
- @data << d
- end
-
- def put_pack(template, *d)
- @data << d.pack(template)
- end
-
- def put_length16
- length_index = @data.length
- @data << "\0\0"
- data_start = @data.length
- yield
- data_end = @data.length
- @data[length_index, 2] = [data_end - data_start].pack("n")
- end
-
- def put_string(d)
- self.put_pack("C", d.length)
- @data << d
- end
-
- def put_string_list(ds)
- ds.each {|d|
- self.put_string(d)
- }
- end
-
- def put_name(d)
- put_labels(d.to_a)
- end
-
- def put_labels(d)
- d.each_index {|i|
- domain = d[i..-1]
- if idx = @names[domain]
- self.put_pack("n", 0xc000 | idx)
- return
- else
- @names[domain] = @data.length
- self.put_label(d[i])
- end
- }
- @data << "\0"
- end
-
- def put_label(d)
- self.put_string(d.to_s)
- end
- end
-
- def Message.decode(m)
- o = Message.new(0)
- MessageDecoder.new(m) {|msg|
- id, flag, qdcount, ancount, nscount, arcount =
- msg.get_unpack('nnnnnn')
- o.id = id
- o.qr = (flag >> 15) & 1
- o.opcode = (flag >> 11) & 15
- o.aa = (flag >> 10) & 1
- o.tc = (flag >> 9) & 1
- o.rd = (flag >> 8) & 1
- o.ra = (flag >> 7) & 1
- o.rcode = flag & 15
- (1..qdcount).each {
- name, typeclass = msg.get_question
- o.add_question(name, typeclass)
- }
- (1..ancount).each {
- name, ttl, data = msg.get_rr
- o.add_answer(name, ttl, data)
- }
- (1..nscount).each {
- name, ttl, data = msg.get_rr
- o.add_authority(name, ttl, data)
- }
- (1..arcount).each {
- name, ttl, data = msg.get_rr
- o.add_additional(name, ttl, data)
- }
- }
- return o
- end
-
- class MessageDecoder # :nodoc:
- def initialize(data)
- @data = data
- @index = 0
- @limit = data.length
- yield self
- end
-
- def inspect
- "\#<#{self.class}: #{@data[0, @index].inspect} #{@data[@index..-1].inspect}>"
- end
-
- def get_length16
- len, = self.get_unpack('n')
- save_limit = @limit
- @limit = @index + len
- d = yield(len)
- if @index < @limit
- raise DecodeError.new("junk exists")
- elsif @limit < @index
- raise DecodeError.new("limit exceeded")
- end
- @limit = save_limit
- return d
- end
-
- def get_bytes(len = @limit - @index)
- d = @data[@index, len]
- @index += len
- return d
- end
-
- def get_unpack(template)
- len = 0
- template.each_byte {|byte|
- byte = "%c" % byte
- case byte
- when ?c, ?C
- len += 1
- when ?n
- len += 2
- when ?N
- len += 4
- else
- raise StandardError.new("unsupported template: '#{byte.chr}' in '#{template}'")
- end
- }
- raise DecodeError.new("limit exceeded") if @limit < @index + len
- arr = @data.unpack("@#{@index}#{template}")
- @index += len
- return arr
- end
-
- def get_string
- len = @data[@index].ord
- raise DecodeError.new("limit exceeded") if @limit < @index + 1 + len
- d = @data[@index + 1, len]
- @index += 1 + len
- return d
- end
-
- def get_string_list
- strings = []
- while @index < @limit
- strings << self.get_string
- end
- strings
- end
-
- def get_name
- return Name.new(self.get_labels)
- end
-
- def get_labels(limit=nil)
- limit = @index if !limit || @index < limit
- d = []
- while true
- case @data[@index].ord
- when 0
- @index += 1
- return d
- when 192..255
- idx = self.get_unpack('n')[0] & 0x3fff
- if limit <= idx
- raise DecodeError.new("non-backward name pointer")
- end
- save_index = @index
- @index = idx
- d += self.get_labels(limit)
- @index = save_index
- return d
- else
- d << self.get_label
- end
- end
- return d
- end
-
- def get_label
- return Label::Str.new(self.get_string)
- end
-
- def get_question
- name = self.get_name
- type, klass = self.get_unpack("nn")
- return name, Resource.get_class(type, klass)
- end
-
- def get_rr
- name = self.get_name
- type, klass, ttl = self.get_unpack('nnN')
- typeclass = Resource.get_class(type, klass)
- res = self.get_length16 { typeclass.decode_rdata self }
- res.instance_variable_set :@ttl, ttl
- return name, ttl, res
- end
- end
- end
-
- ##
- # A DNS query abstract class.
-
- class Query
- def encode_rdata(msg) # :nodoc:
- raise EncodeError.new("#{self.class} is query.")
- end
-
- def self.decode_rdata(msg) # :nodoc:
- raise DecodeError.new("#{self.class} is query.")
- end
- end
-
- ##
- # A DNS resource abstract class.
-
- class Resource < Query
-
- ##
- # Remaining Time To Live for this Resource.
-
- attr_reader :ttl
-
- ClassHash = {} # :nodoc:
-
- def encode_rdata(msg) # :nodoc:
- raise NotImplementedError.new
- end
-
- def self.decode_rdata(msg) # :nodoc:
- raise NotImplementedError.new
- end
-
- def ==(other) # :nodoc:
- return false unless self.class == other.class
- s_ivars = self.instance_variables
- s_ivars.sort!
- s_ivars.delete "@ttl"
- o_ivars = other.instance_variables
- o_ivars.sort!
- o_ivars.delete "@ttl"
- return s_ivars == o_ivars &&
- s_ivars.collect {|name| self.instance_variable_get name} ==
- o_ivars.collect {|name| other.instance_variable_get name}
- end
-
- def eql?(other) # :nodoc:
- return self == other
- end
-
- def hash # :nodoc:
- h = 0
- vars = self.instance_variables
- vars.delete "@ttl"
- vars.each {|name|
- h ^= self.instance_variable_get(name).hash
- }
- return h
- end
-
- def self.get_class(type_value, class_value) # :nodoc:
- return ClassHash[[type_value, class_value]] ||
- Generic.create(type_value, class_value)
- end
-
- ##
- # A generic resource abstract class.
-
- class Generic < Resource
-
- ##
- # Creates a new generic resource.
-
- def initialize(data)
- @data = data
- end
-
- ##
- # Data for this generic resource.
-
- attr_reader :data
-
- def encode_rdata(msg) # :nodoc:
- msg.put_bytes(data)
- end
-
- def self.decode_rdata(msg) # :nodoc:
- return self.new(msg.get_bytes)
- end
-
- def self.create(type_value, class_value) # :nodoc:
- c = Class.new(Generic)
- c.const_set(:TypeValue, type_value)
- c.const_set(:ClassValue, class_value)
- Generic.const_set("Type#{type_value}_Class#{class_value}", c)
- ClassHash[[type_value, class_value]] = c
- return c
- end
- end
-
- ##
- # Domain Name resource abstract class.
-
- class DomainName < Resource
-
- ##
- # Creates a new DomainName from +name+.
-
- def initialize(name)
- @name = name
- end
-
- ##
- # The name of this DomainName.
-
- attr_reader :name
-
- def encode_rdata(msg) # :nodoc:
- msg.put_name(@name)
- end
-
- def self.decode_rdata(msg) # :nodoc:
- return self.new(msg.get_name)
- end
- end
-
- # Standard (class generic) RRs
-
- ClassValue = nil # :nodoc:
-
- ##
- # An authoritative name server.
-
- class NS < DomainName
- TypeValue = 2 # :nodoc:
- end
-
- ##
- # The canonical name for an alias.
-
- class CNAME < DomainName
- TypeValue = 5 # :nodoc:
- end
-
- ##
- # Start Of Authority resource.
-
- class SOA < Resource
-
- TypeValue = 6 # :nodoc:
-
- ##
- # Creates a new SOA record. See the attr documentation for the
- # details of each argument.
-
- def initialize(mname, rname, serial, refresh, retry_, expire, minimum)
- @mname = mname
- @rname = rname
- @serial = serial
- @refresh = refresh
- @retry = retry_
- @expire = expire
- @minimum = minimum
- end
-
- ##
- # Name of the host where the master zone file for this zone resides.
-
- attr_reader :mname
-
- ##
- # The person responsible for this domain name.
-
- attr_reader :rname
-
- ##
- # The version number of the zone file.
-
- attr_reader :serial
-
- ##
- # How often, in seconds, a secondary name server is to check for
- # updates from the primary name server.
-
- attr_reader :refresh
-
- ##
- # How often, in seconds, a secondary name server is to retry after a
- # failure to check for a refresh.
-
- attr_reader :retry
-
- ##
- # Time in seconds that a secondary name server is to use the data
- # before refreshing from the primary name server.
-
- attr_reader :expire
-
- ##
- # The minimum number of seconds to be used for TTL values in RRs.
-
- attr_reader :minimum
-
- def encode_rdata(msg) # :nodoc:
- msg.put_name(@mname)
- msg.put_name(@rname)
- msg.put_pack('NNNNN', @serial, @refresh, @retry, @expire, @minimum)
- end
-
- def self.decode_rdata(msg) # :nodoc:
- mname = msg.get_name
- rname = msg.get_name
- serial, refresh, retry_, expire, minimum = msg.get_unpack('NNNNN')
- return self.new(
- mname, rname, serial, refresh, retry_, expire, minimum)
- end
- end
-
- ##
- # A Pointer to another DNS name.
-
- class PTR < DomainName
- TypeValue = 12 # :nodoc:
- end
-
- ##
- # Host Information resource.
-
- class HINFO < Resource
-
- TypeValue = 13 # :nodoc:
-
- ##
- # Creates a new HINFO running +os+ on +cpu+.
-
- def initialize(cpu, os)
- @cpu = cpu
- @os = os
- end
-
- ##
- # CPU architecture for this resource.
-
- attr_reader :cpu
-
- ##
- # Operating system for this resource.
-
- attr_reader :os
-
- def encode_rdata(msg) # :nodoc:
- msg.put_string(@cpu)
- msg.put_string(@os)
- end
-
- def self.decode_rdata(msg) # :nodoc:
- cpu = msg.get_string
- os = msg.get_string
- return self.new(cpu, os)
- end
- end
-
- ##
- # Mailing list or mailbox information.
-
- class MINFO < Resource
-
- TypeValue = 14 # :nodoc:
-
- def initialize(rmailbx, emailbx)
- @rmailbx = rmailbx
- @emailbx = emailbx
- end
-
- ##
- # Domain name responsible for this mail list or mailbox.
-
- attr_reader :rmailbx
-
- ##
- # Mailbox to use for error messages related to the mail list or mailbox.
-
- attr_reader :emailbx
-
- def encode_rdata(msg) # :nodoc:
- msg.put_name(@rmailbx)
- msg.put_name(@emailbx)
- end
-
- def self.decode_rdata(msg) # :nodoc:
- rmailbx = msg.get_string
- emailbx = msg.get_string
- return self.new(rmailbx, emailbx)
- end
- end
-
- ##
- # Mail Exchanger resource.
-
- class MX < Resource
-
- TypeValue= 15 # :nodoc:
-
- ##
- # Creates a new MX record with +preference+, accepting mail at
- # +exchange+.
-
- def initialize(preference, exchange)
- @preference = preference
- @exchange = exchange
- end
-
- ##
- # The preference for this MX.
-
- attr_reader :preference
-
- ##
- # The host of this MX.
-
- attr_reader :exchange
-
- def encode_rdata(msg) # :nodoc:
- msg.put_pack('n', @preference)
- msg.put_name(@exchange)
- end
-
- def self.decode_rdata(msg) # :nodoc:
- preference, = msg.get_unpack('n')
- exchange = msg.get_name
- return self.new(preference, exchange)
- end
- end
-
- ##
- # Unstructured text resource.
-
- class TXT < Resource
-
- TypeValue = 16 # :nodoc:
-
- def initialize(first_string, *rest_strings)
- @strings = [first_string, *rest_strings]
- end
-
- ##
- # Returns an Array of Strings for this TXT record.
-
- attr_reader :strings
-
- ##
- # Returns the first string from +strings+.
-
- def data
- @strings[0]
- end
-
- def encode_rdata(msg) # :nodoc:
- msg.put_string_list(@strings)
- end
-
- def self.decode_rdata(msg) # :nodoc:
- strings = msg.get_string_list
- return self.new(*strings)
- end
- end
-
- ##
- # A Query type requesting any RR.
-
- class ANY < Query
- TypeValue = 255 # :nodoc:
- end
-
- ClassInsensitiveTypes = [ # :nodoc:
- NS, CNAME, SOA, PTR, HINFO, MINFO, MX, TXT, ANY
- ]
-
- ##
- # module IN contains ARPA Internet specific RRs.
-
- module IN
-
- ClassValue = 1 # :nodoc:
-
- ClassInsensitiveTypes.each {|s|
- c = Class.new(s)
- c.const_set(:TypeValue, s::TypeValue)
- c.const_set(:ClassValue, ClassValue)
- ClassHash[[s::TypeValue, ClassValue]] = c
- self.const_set(s.name.sub(/.*::/, ''), c)
- }
-
- ##
- # IPv4 Address resource
-
- class A < Resource
- TypeValue = 1
- ClassValue = IN::ClassValue
- ClassHash[[TypeValue, ClassValue]] = self # :nodoc:
-
- ##
- # Creates a new A for +address+.
-
- def initialize(address)
- @address = IPv4.create(address)
- end
-
- ##
- # The Resolv::IPv4 address for this A.
-
- attr_reader :address
-
- def encode_rdata(msg) # :nodoc:
- msg.put_bytes(@address.address)
- end
-
- def self.decode_rdata(msg) # :nodoc:
- return self.new(IPv4.new(msg.get_bytes(4)))
- end
- end
-
- ##
- # Well Known Service resource.
-
- class WKS < Resource
- TypeValue = 11
- ClassValue = IN::ClassValue
- ClassHash[[TypeValue, ClassValue]] = self # :nodoc:
-
- def initialize(address, protocol, bitmap)
- @address = IPv4.create(address)
- @protocol = protocol
- @bitmap = bitmap
- end
-
- ##
- # The host these services run on.
-
- attr_reader :address
-
- ##
- # IP protocol number for these services.
-
- attr_reader :protocol
-
- ##
- # A bit map of enabled services on this host.
- #
- # If protocol is 6 (TCP) then the 26th bit corresponds to the SMTP
- # service (port 25). If this bit is set, then an SMTP server should
- # be listening on TCP port 25; if zero, SMTP service is not
- # supported.
-
- attr_reader :bitmap
-
- def encode_rdata(msg) # :nodoc:
- msg.put_bytes(@address.address)
- msg.put_pack("n", @protocol)
- msg.put_bytes(@bitmap)
- end
-
- def self.decode_rdata(msg) # :nodoc:
- address = IPv4.new(msg.get_bytes(4))
- protocol, = msg.get_unpack("n")
- bitmap = msg.get_bytes
- return self.new(address, protocol, bitmap)
- end
- end
-
- ##
- # An IPv6 address record.
-
- class AAAA < Resource
- TypeValue = 28
- ClassValue = IN::ClassValue
- ClassHash[[TypeValue, ClassValue]] = self # :nodoc:
-
- ##
- # Creates a new AAAA for +address+.
-
- def initialize(address)
- @address = IPv6.create(address)
- end
-
- ##
- # The Resolv::IPv6 address for this AAAA.
-
- attr_reader :address
-
- def encode_rdata(msg) # :nodoc:
- msg.put_bytes(@address.address)
- end
-
- def self.decode_rdata(msg) # :nodoc:
- return self.new(IPv6.new(msg.get_bytes(16)))
- end
- end
-
- ##
- # SRV resource record defined in RFC 2782
- #
- # These records identify the hostname and port that a service is
- # available at.
-
- class SRV < Resource
- TypeValue = 33
- ClassValue = IN::ClassValue
- ClassHash[[TypeValue, ClassValue]] = self # :nodoc:
-
- # Create a SRV resource record.
- #
- # See the documentation for #priority, #weight, #port and #target
- # for +priority+, +weight+, +port and +target+ respectively.
-
- def initialize(priority, weight, port, target)
- @priority = priority.to_int
- @weight = weight.to_int
- @port = port.to_int
- @target = Name.create(target)
- end
-
- # The priority of this target host.
- #
- # A client MUST attempt to contact the target host with the
- # lowest-numbered priority it can reach; target hosts with the same
- # priority SHOULD be tried in an order defined by the weight field.
- # The range is 0-65535. Note that it is not widely implemented and
- # should be set to zero.
-
- attr_reader :priority
-
- # A server selection mechanism.
- #
- # The weight field specifies a relative weight for entries with the
- # same priority. Larger weights SHOULD be given a proportionately
- # higher probability of being selected. The range of this number is
- # 0-65535. Domain administrators SHOULD use Weight 0 when there
- # isn't any server selection to do, to make the RR easier to read
- # for humans (less noisy). Note that it is not widely implemented
- # and should be set to zero.
-
- attr_reader :weight
-
- # The port on this target host of this service.
- #
- # The range is 0-65535.
-
- attr_reader :port
-
- # The domain name of the target host.
- #
- # A target of "." means that the service is decidedly not available
- # at this domain.
-
- attr_reader :target
-
- def encode_rdata(msg) # :nodoc:
- msg.put_pack("n", @priority)
- msg.put_pack("n", @weight)
- msg.put_pack("n", @port)
- msg.put_name(@target)
- end
-
- def self.decode_rdata(msg) # :nodoc:
- priority, = msg.get_unpack("n")
- weight, = msg.get_unpack("n")
- port, = msg.get_unpack("n")
- target = msg.get_name
- return self.new(priority, weight, port, target)
- end
- end
- end
- end
- end
-
- ##
- # A Resolv::DNS IPv4 address.
-
- class IPv4
-
- ##
- # Regular expression IPv4 addresses must match.
-
- Regex256 = /0
- |1(?:[0-9][0-9]?)?
- |2(?:[0-4][0-9]?|5[0-5]?|[6-9])?
- |[3-9][0-9]?/x
- Regex = /\A(#{Regex256})\.(#{Regex256})\.(#{Regex256})\.(#{Regex256})\z/
-
- def self.create(arg)
- case arg
- when IPv4
- return arg
- when Regex
- if (0..255) === (a = $1.to_i) &&
- (0..255) === (b = $2.to_i) &&
- (0..255) === (c = $3.to_i) &&
- (0..255) === (d = $4.to_i)
- return self.new([a, b, c, d].pack("CCCC"))
- else
- raise ArgumentError.new("IPv4 address with invalid value: " + arg)
- end
- else
- raise ArgumentError.new("cannot interpret as IPv4 address: #{arg.inspect}")
- end
- end
-
- def initialize(address) # :nodoc:
- unless address.kind_of?(String)
- raise ArgumentError, 'IPv4 address must be a string'
- end
- unless address.length == 4
- raise ArgumentError, "IPv4 address expects 4 bytes but #{address.length} bytes"
- end
- @address = address
- end
-
- ##
- # A String representation of this IPv4 address.
-
- ##
- # The raw IPv4 address as a String.
-
- attr_reader :address
-
- def to_s # :nodoc:
- return sprintf("%d.%d.%d.%d", *@address.unpack("CCCC"))
- end
-
- def inspect # :nodoc:
- return "#<#{self.class} #{self.to_s}>"
- end
-
- ##
- # Turns this IPv4 address into a Resolv::DNS::Name.
-
- def to_name
- return DNS::Name.create(
- '%d.%d.%d.%d.in-addr.arpa.' % @address.unpack('CCCC').reverse)
- end
-
- def ==(other) # :nodoc:
- return @address == other.address
- end
-
- def eql?(other) # :nodoc:
- return self == other
- end
-
- def hash # :nodoc:
- return @address.hash
- end
- end
-
- ##
- # A Resolv::DNS IPv6 address.
-
- class IPv6
-
- ##
- # IPv6 address format a:b:c:d:e:f:g:h
- Regex_8Hex = /\A
- (?:[0-9A-Fa-f]{1,4}:){7}
- [0-9A-Fa-f]{1,4}
- \z/x
-
- ##
- # Compressed IPv6 address format a::b
-
- Regex_CompressedHex = /\A
- ((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::
- ((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)
- \z/x
-
- ##
- # IPv4 mapped IPv6 address format a:b:c:d:e:f:w.x.y.z
-
- Regex_6Hex4Dec = /\A
- ((?:[0-9A-Fa-f]{1,4}:){6,6})
- (\d+)\.(\d+)\.(\d+)\.(\d+)
- \z/x
-
- ##
- # Compressed IPv4 mapped IPv6 address format a::b:w.x.y.z
-
- Regex_CompressedHex4Dec = /\A
- ((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::
- ((?:[0-9A-Fa-f]{1,4}:)*)
- (\d+)\.(\d+)\.(\d+)\.(\d+)
- \z/x
-
- ##
- # A composite IPv6 address Regexp.
-
- Regex = /
- (?:#{Regex_8Hex}) |
- (?:#{Regex_CompressedHex}) |
- (?:#{Regex_6Hex4Dec}) |
- (?:#{Regex_CompressedHex4Dec})/x
-
- ##
- # Creates a new IPv6 address from +arg+ which may be:
- #
- # IPv6:: returns +arg+.
- # String:: +arg+ must match one of the IPv6::Regex* constants
-
- def self.create(arg)
- case arg
- when IPv6
- return arg
- when String
- address = ''
- if Regex_8Hex =~ arg
- arg.scan(/[0-9A-Fa-f]+/) {|hex| address << [hex.hex].pack('n')}
- elsif Regex_CompressedHex =~ arg
- prefix = $1
- suffix = $2
- a1 = ''
- a2 = ''
- prefix.scan(/[0-9A-Fa-f]+/) {|hex| a1 << [hex.hex].pack('n')}
- suffix.scan(/[0-9A-Fa-f]+/) {|hex| a2 << [hex.hex].pack('n')}
- omitlen = 16 - a1.length - a2.length
- address << a1 << "\0" * omitlen << a2
- elsif Regex_6Hex4Dec =~ arg
- prefix, a, b, c, d = $1, $2.to_i, $3.to_i, $4.to_i, $5.to_i
- if (0..255) === a && (0..255) === b && (0..255) === c && (0..255) === d
- prefix.scan(/[0-9A-Fa-f]+/) {|hex| address << [hex.hex].pack('n')}
- address << [a, b, c, d].pack('CCCC')
- else
- raise ArgumentError.new("not numeric IPv6 address: " + arg)
- end
- elsif Regex_CompressedHex4Dec =~ arg
- prefix, suffix, a, b, c, d = $1, $2, $3.to_i, $4.to_i, $5.to_i, $6.to_i
- if (0..255) === a && (0..255) === b && (0..255) === c && (0..255) === d
- a1 = ''
- a2 = ''
- prefix.scan(/[0-9A-Fa-f]+/) {|hex| a1 << [hex.hex].pack('n')}
- suffix.scan(/[0-9A-Fa-f]+/) {|hex| a2 << [hex.hex].pack('n')}
- omitlen = 12 - a1.length - a2.length
- address << a1 << "\0" * omitlen << a2 << [a, b, c, d].pack('CCCC')
- else
- raise ArgumentError.new("not numeric IPv6 address: " + arg)
- end
- else
- raise ArgumentError.new("not numeric IPv6 address: " + arg)
- end
- return IPv6.new(address)
- else
- raise ArgumentError.new("cannot interpret as IPv6 address: #{arg.inspect}")
- end
- end
-
- def initialize(address) # :nodoc:
- unless address.kind_of?(String) && address.length == 16
- raise ArgumentError.new('IPv6 address must be 16 bytes')
- end
- @address = address
- end
-
- ##
- # The raw IPv6 address as a String.
-
- attr_reader :address
-
- def to_s # :nodoc:
- address = sprintf("%X:%X:%X:%X:%X:%X:%X:%X", *@address.unpack("nnnnnnnn"))
- unless address.sub!(/(^|:)0(:0)+(:|$)/, '::')
- address.sub!(/(^|:)0(:|$)/, '::')
- end
- return address
- end
-
- def inspect # :nodoc:
- return "#<#{self.class} #{self.to_s}>"
- end
-
- ##
- # Turns this IPv6 address into a Resolv::DNS::Name.
- #--
- # ip6.arpa should be searched too. [RFC3152]
-
- def to_name
- return DNS::Name.new(
- @address.unpack("H32")[0].split(//).reverse + ['ip6', 'arpa'])
- end
-
- def ==(other) # :nodoc:
- return @address == other.address
- end
-
- def eql?(other) # :nodoc:
- return self == other
- end
-
- def hash # :nodoc:
- return @address.hash
- end
- end
-
- ##
- # Default resolver to use for Resolv class methods.
-
- DefaultResolver = self.new
-
- ##
- # Address Regexp to use for matching IP addresses.
-
- AddressRegex = /(?:#{IPv4::Regex})|(?:#{IPv6::Regex})/
-
-end
-
diff --git a/ruby_1_9_3/lib/rexml/attlistdecl.rb b/ruby_1_9_3/lib/rexml/attlistdecl.rb
deleted file mode 100644
index ec4e6c3b8d..0000000000
--- a/ruby_1_9_3/lib/rexml/attlistdecl.rb
+++ /dev/null
@@ -1,62 +0,0 @@
-#vim:ts=2 sw=2 noexpandtab:
-require 'rexml/child'
-require 'rexml/source'
-
-module REXML
- # This class needs:
- # * Documentation
- # * Work! Not all types of attlists are intelligently parsed, so we just
- # spew back out what we get in. This works, but it would be better if
- # we formatted the output ourselves.
- #
- # AttlistDecls provide *just* enough support to allow namespace
- # declarations. If you need some sort of generalized support, or have an
- # interesting idea about how to map the hideous, terrible design of DTD
- # AttlistDecls onto an intuitive Ruby interface, let me know. I'm desperate
- # for anything to make DTDs more palateable.
- class AttlistDecl < Child
- include Enumerable
-
- # What is this? Got me.
- attr_reader :element_name
-
- # Create an AttlistDecl, pulling the information from a Source. Notice
- # that this isn't very convenient; to create an AttlistDecl, you basically
- # have to format it yourself, and then have the initializer parse it.
- # Sorry, but for the forseeable future, DTD support in REXML is pretty
- # weak on convenience. Have I mentioned how much I hate DTDs?
- def initialize(source)
- super()
- if (source.kind_of? Array)
- @element_name, @pairs, @contents = *source
- end
- end
-
- # Access the attlist attribute/value pairs.
- # value = attlist_decl[ attribute_name ]
- def [](key)
- @pairs[key]
- end
-
- # Whether an attlist declaration includes the given attribute definition
- # if attlist_decl.include? "xmlns:foobar"
- def include?(key)
- @pairs.keys.include? key
- end
-
- # Iterate over the key/value pairs:
- # attlist_decl.each { |attribute_name, attribute_value| ... }
- def each(&block)
- @pairs.each(&block)
- end
-
- # Write out exactly what we got in.
- def write out, indent=-1
- out << @contents
- end
-
- def node_type
- :attlistdecl
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/attribute.rb b/ruby_1_9_3/lib/rexml/attribute.rb
deleted file mode 100644
index e99927943f..0000000000
--- a/ruby_1_9_3/lib/rexml/attribute.rb
+++ /dev/null
@@ -1,188 +0,0 @@
-require "rexml/namespace"
-require 'rexml/text'
-
-module REXML
- # Defines an Element Attribute; IE, a attribute=value pair, as in:
- # <element attribute="value"/>. Attributes can be in their own
- # namespaces. General users of REXML will not interact with the
- # Attribute class much.
- class Attribute
- include Node
- include Namespace
-
- # The element to which this attribute belongs
- attr_reader :element
- # The normalized value of this attribute. That is, the attribute with
- # entities intact.
- attr_writer :normalized
- PATTERN = /\s*(#{NAME_STR})\s*=\s*(["'])(.*?)\2/um
-
- NEEDS_A_SECOND_CHECK = /(<|&((#{Entity::NAME});|(#0*((?:\d+)|(?:x[a-fA-F0-9]+)));)?)/um
-
- # Constructor.
- # FIXME: The parser doesn't catch illegal characters in attributes
- #
- # first::
- # Either: an Attribute, which this new attribute will become a
- # clone of; or a String, which is the name of this attribute
- # second::
- # If +first+ is an Attribute, then this may be an Element, or nil.
- # If nil, then the Element parent of this attribute is the parent
- # of the +first+ Attribute. If the first argument is a String,
- # then this must also be a String, and is the content of the attribute.
- # If this is the content, it must be fully normalized (contain no
- # illegal characters).
- # parent::
- # Ignored unless +first+ is a String; otherwise, may be the Element
- # parent of this attribute, or nil.
- #
- #
- # Attribute.new( attribute_to_clone )
- # Attribute.new( attribute_to_clone, parent_element )
- # Attribute.new( "attr", "attr_value" )
- # Attribute.new( "attr", "attr_value", parent_element )
- def initialize( first, second=nil, parent=nil )
- @normalized = @unnormalized = @element = nil
- if first.kind_of? Attribute
- self.name = first.expanded_name
- @unnormalized = first.value
- if second.kind_of? Element
- @element = second
- else
- @element = first.element
- end
- elsif first.kind_of? String
- @element = parent
- self.name = first
- @normalized = second.to_s
- else
- raise "illegal argument #{first.class.name} to Attribute constructor"
- end
- end
-
- # Returns the namespace of the attribute.
- #
- # e = Element.new( "elns:myelement" )
- # e.add_attribute( "nsa:a", "aval" )
- # e.add_attribute( "b", "bval" )
- # e.attributes.get_attribute( "a" ).prefix # -> "nsa"
- # e.attributes.get_attribute( "b" ).prefix # -> "elns"
- # a = Attribute.new( "x", "y" )
- # a.prefix # -> ""
- def prefix
- pf = super
- if pf == ""
- pf = @element.prefix if @element
- end
- pf
- end
-
- # Returns the namespace URL, if defined, or nil otherwise
- #
- # e = Element.new("el")
- # e.add_attributes({"xmlns:ns", "http://url"})
- # e.namespace( "ns" ) # -> "http://url"
- def namespace arg=nil
- arg = prefix if arg.nil?
- @element.namespace arg
- end
-
- # Returns true if other is an Attribute and has the same name and value,
- # false otherwise.
- def ==( other )
- other.kind_of?(Attribute) and other.name==name and other.value==value
- end
-
- # Creates (and returns) a hash from both the name and value
- def hash
- name.hash + value.hash
- end
-
- # Returns this attribute out as XML source, expanding the name
- #
- # a = Attribute.new( "x", "y" )
- # a.to_string # -> "x='y'"
- # b = Attribute.new( "ns:x", "y" )
- # b.to_string # -> "ns:x='y'"
- def to_string
- if @element and @element.context and @element.context[:attribute_quote] == :quote
- %Q^#@expanded_name="#{to_s().gsub(/"/, '&quote;')}"^
- else
- "#@expanded_name='#{to_s().gsub(/'/, '&apos;')}'"
- end
- end
-
- def doctype
- if @element
- doc = @element.document
- doc.doctype if doc
- end
- end
-
- # Returns the attribute value, with entities replaced
- def to_s
- return @normalized if @normalized
-
- @normalized = Text::normalize( @unnormalized, doctype )
- @unnormalized = nil
- @normalized
- end
-
- # Returns the UNNORMALIZED value of this attribute. That is, entities
- # have been expanded to their values
- def value
- return @unnormalized if @unnormalized
- @unnormalized = Text::unnormalize( @normalized, doctype )
- @normalized = nil
- @unnormalized
- end
-
- # Returns a copy of this attribute
- def clone
- Attribute.new self
- end
-
- # Sets the element of which this object is an attribute. Normally, this
- # is not directly called.
- #
- # Returns this attribute
- def element=( element )
- @element = element
-
- if @normalized
- Text.check( @normalized, NEEDS_A_SECOND_CHECK, doctype )
- end
-
- self
- end
-
- # Removes this Attribute from the tree, and returns true if successfull
- #
- # This method is usually not called directly.
- def remove
- @element.attributes.delete self.name unless @element.nil?
- end
-
- # Writes this attribute (EG, puts 'key="value"' to the output)
- def write( output, indent=-1 )
- output << to_string
- end
-
- def node_type
- :attribute
- end
-
- def inspect
- rv = ""
- write( rv )
- rv
- end
-
- def xpath
- path = @element.xpath
- path += "/@#{self.expanded_name}"
- return path
- end
- end
-end
-#vim:ts=2 sw=2 noexpandtab:
diff --git a/ruby_1_9_3/lib/rexml/cdata.rb b/ruby_1_9_3/lib/rexml/cdata.rb
deleted file mode 100644
index 73358edc28..0000000000
--- a/ruby_1_9_3/lib/rexml/cdata.rb
+++ /dev/null
@@ -1,67 +0,0 @@
-require "rexml/text"
-
-module REXML
- class CData < Text
- START = '<![CDATA['
- STOP = ']]>'
- ILLEGAL = /(\]\]>)/
-
- # Constructor. CData is data between <![CDATA[ ... ]]>
- #
- # _Examples_
- # CData.new( source )
- # CData.new( "Here is some CDATA" )
- # CData.new( "Some unprocessed data", respect_whitespace_TF, parent_element )
- def initialize( first, whitespace=true, parent=nil )
- super( first, whitespace, parent, false, true, ILLEGAL )
- end
-
- # Make a copy of this object
- #
- # _Examples_
- # c = CData.new( "Some text" )
- # d = c.clone
- # d.to_s # -> "Some text"
- def clone
- CData.new self
- end
-
- # Returns the content of this CData object
- #
- # _Examples_
- # c = CData.new( "Some text" )
- # c.to_s # -> "Some text"
- def to_s
- @string
- end
-
- def value
- @string
- end
-
- # == DEPRECATED
- # See the rexml/formatters package
- #
- # Generates XML output of this object
- #
- # output::
- # Where to write the string. Defaults to $stdout
- # indent::
- # The amount to indent this node by
- # transitive::
- # Ignored
- # ie_hack::
- # Ignored
- #
- # _Examples_
- # c = CData.new( " Some text " )
- # c.write( $stdout ) #-> <![CDATA[ Some text ]]>
- def write( output=$stdout, indent=-1, transitive=false, ie_hack=false )
- Kernel.warn( "#{self.class.name}.write is deprecated" )
- indent( output, indent )
- output << START
- output << @string
- output << STOP
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/child.rb b/ruby_1_9_3/lib/rexml/child.rb
deleted file mode 100644
index bf97d5f903..0000000000
--- a/ruby_1_9_3/lib/rexml/child.rb
+++ /dev/null
@@ -1,96 +0,0 @@
-require "rexml/node"
-
-module REXML
- ##
- # A Child object is something contained by a parent, and this class
- # contains methods to support that. Most user code will not use this
- # class directly.
- class Child
- include Node
- attr_reader :parent # The Parent of this object
-
- # Constructor. Any inheritors of this class should call super to make
- # sure this method is called.
- # parent::
- # if supplied, the parent of this child will be set to the
- # supplied value, and self will be added to the parent
- def initialize( parent = nil )
- @parent = nil
- # Declare @parent, but don't define it. The next line sets the
- # parent.
- parent.add( self ) if parent
- end
-
- # Replaces this object with another object. Basically, calls
- # Parent.replace_child
- #
- # Returns:: self
- def replace_with( child )
- @parent.replace_child( self, child )
- self
- end
-
- # Removes this child from the parent.
- #
- # Returns:: self
- def remove
- unless @parent.nil?
- @parent.delete self
- end
- self
- end
-
- # Sets the parent of this child to the supplied argument.
- #
- # other::
- # Must be a Parent object. If this object is the same object as the
- # existing parent of this child, no action is taken. Otherwise, this
- # child is removed from the current parent (if one exists), and is added
- # to the new parent.
- # Returns:: The parent added
- def parent=( other )
- return @parent if @parent == other
- @parent.delete self if defined? @parent and @parent
- @parent = other
- end
-
- alias :next_sibling :next_sibling_node
- alias :previous_sibling :previous_sibling_node
-
- # Sets the next sibling of this child. This can be used to insert a child
- # after some other child.
- # a = Element.new("a")
- # b = a.add_element("b")
- # c = Element.new("c")
- # b.next_sibling = c
- # # => <a><b/><c/></a>
- def next_sibling=( other )
- parent.insert_after self, other
- end
-
- # Sets the previous sibling of this child. This can be used to insert a
- # child before some other child.
- # a = Element.new("a")
- # b = a.add_element("b")
- # c = Element.new("c")
- # b.previous_sibling = c
- # # => <a><b/><c/></a>
- def previous_sibling=(other)
- parent.insert_before self, other
- end
-
- # Returns:: the document this child belongs to, or nil if this child
- # belongs to no document
- def document
- return parent.document unless parent.nil?
- nil
- end
-
- # This doesn't yet handle encodings
- def bytes
- document.encoding
-
- to_s
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/comment.rb b/ruby_1_9_3/lib/rexml/comment.rb
deleted file mode 100644
index 42a040c456..0000000000
--- a/ruby_1_9_3/lib/rexml/comment.rb
+++ /dev/null
@@ -1,80 +0,0 @@
-require "rexml/child"
-
-module REXML
- ##
- # Represents an XML comment; that is, text between \<!-- ... -->
- class Comment < Child
- include Comparable
- START = "<!--"
- STOP = "-->"
-
- # The content text
-
- attr_accessor :string
-
- ##
- # Constructor. The first argument can be one of three types:
- # @param first If String, the contents of this comment are set to the
- # argument. If Comment, the argument is duplicated. If
- # Source, the argument is scanned for a comment.
- # @param second If the first argument is a Source, this argument
- # should be nil, not supplied, or a Parent to be set as the parent
- # of this object
- def initialize( first, second = nil )
- #puts "IN COMMENT CONSTRUCTOR; SECOND IS #{second.type}"
- super(second)
- if first.kind_of? String
- @string = first
- elsif first.kind_of? Comment
- @string = first.string
- end
- end
-
- def clone
- Comment.new self
- end
-
- # == DEPRECATED
- # See REXML::Formatters
- #
- # output::
- # Where to write the string
- # indent::
- # An integer. If -1, no indenting will be used; otherwise, the
- # indentation will be this number of spaces, and children will be
- # indented an additional amount.
- # transitive::
- # Ignored by this class. The contents of comments are never modified.
- # ie_hack::
- # Needed for conformity to the child API, but not used by this class.
- def write( output, indent=-1, transitive=false, ie_hack=false )
- Kernel.warn("Comment.write is deprecated. See REXML::Formatters")
- indent( output, indent )
- output << START
- output << @string
- output << STOP
- end
-
- alias :to_s :string
-
- ##
- # Compares this Comment to another; the contents of the comment are used
- # in the comparison.
- def <=>(other)
- other.to_s <=> @string
- end
-
- ##
- # Compares this Comment to another; the contents of the comment are used
- # in the comparison.
- def ==( other )
- other.kind_of? Comment and
- (other <=> self) == 0
- end
-
- def node_type
- :comment
- end
- end
-end
-#vim:ts=2 sw=2 noexpandtab:
diff --git a/ruby_1_9_3/lib/rexml/doctype.rb b/ruby_1_9_3/lib/rexml/doctype.rb
deleted file mode 100644
index 0b3c533bb4..0000000000
--- a/ruby_1_9_3/lib/rexml/doctype.rb
+++ /dev/null
@@ -1,269 +0,0 @@
-require "rexml/parent"
-require "rexml/parseexception"
-require "rexml/namespace"
-require 'rexml/entity'
-require 'rexml/attlistdecl'
-require 'rexml/xmltokens'
-
-module REXML
- # Represents an XML DOCTYPE declaration; that is, the contents of <!DOCTYPE
- # ... >. DOCTYPES can be used to declare the DTD of a document, as well as
- # being used to declare entities used in the document.
- class DocType < Parent
- include XMLTokens
- START = "<!DOCTYPE"
- STOP = ">"
- SYSTEM = "SYSTEM"
- PUBLIC = "PUBLIC"
- DEFAULT_ENTITIES = {
- 'gt'=>EntityConst::GT,
- 'lt'=>EntityConst::LT,
- 'quot'=>EntityConst::QUOT,
- "apos"=>EntityConst::APOS
- }
-
- # name is the name of the doctype
- # external_id is the referenced DTD, if given
- attr_reader :name, :external_id, :entities, :namespaces
-
- # Constructor
- #
- # dt = DocType.new( 'foo', '-//I/Hate/External/IDs' )
- # # <!DOCTYPE foo '-//I/Hate/External/IDs'>
- # dt = DocType.new( doctype_to_clone )
- # # Incomplete. Shallow clone of doctype
- #
- # +Note+ that the constructor:
- #
- # Doctype.new( Source.new( "<!DOCTYPE foo 'bar'>" ) )
- #
- # is _deprecated_. Do not use it. It will probably disappear.
- def initialize( first, parent=nil )
- @entities = DEFAULT_ENTITIES
- @long_name = @uri = nil
- if first.kind_of? String
- super()
- @name = first
- @external_id = parent
- elsif first.kind_of? DocType
- super( parent )
- @name = first.name
- @external_id = first.external_id
- elsif first.kind_of? Array
- super( parent )
- @name = first[0]
- @external_id = first[1]
- @long_name = first[2]
- @uri = first[3]
- elsif first.kind_of? Source
- super( parent )
- parser = Parsers::BaseParser.new( first )
- event = parser.pull
- if event[0] == :start_doctype
- @name, @external_id, @long_name, @uri, = event[1..-1]
- end
- else
- super()
- end
- end
-
- def node_type
- :doctype
- end
-
- def attributes_of element
- rv = []
- each do |child|
- child.each do |key,val|
- rv << Attribute.new(key,val)
- end if child.kind_of? AttlistDecl and child.element_name == element
- end
- rv
- end
-
- def attribute_of element, attribute
- att_decl = find do |child|
- child.kind_of? AttlistDecl and
- child.element_name == element and
- child.include? attribute
- end
- return nil unless att_decl
- att_decl[attribute]
- end
-
- def clone
- DocType.new self
- end
-
- # output::
- # Where to write the string
- # indent::
- # An integer. If -1, no indentation will be used; otherwise, the
- # indentation will be this number of spaces, and children will be
- # indented an additional amount.
- # transitive::
- # Ignored
- # ie_hack::
- # Ignored
- def write( output, indent=0, transitive=false, ie_hack=false )
- f = REXML::Formatters::Default.new
- indent( output, indent )
- output << START
- output << ' '
- output << @name
- output << " #@external_id" if @external_id
- output << " #{@long_name.inspect}" if @long_name
- output << " #{@uri.inspect}" if @uri
- unless @children.empty?
- output << ' ['
- @children.each { |child|
- output << "\n"
- f.write( child, output )
- }
- output << "\n]"
- end
- output << STOP
- end
-
- def context
- @parent.context
- end
-
- def entity( name )
- @entities[name].unnormalized if @entities[name]
- end
-
- def add child
- super(child)
- @entities = DEFAULT_ENTITIES.clone if @entities == DEFAULT_ENTITIES
- @entities[ child.name ] = child if child.kind_of? Entity
- end
-
- # This method retrieves the public identifier identifying the document's
- # DTD.
- #
- # Method contributed by Henrik Martensson
- def public
- case @external_id
- when "SYSTEM"
- nil
- when "PUBLIC"
- strip_quotes(@long_name)
- end
- end
-
- # This method retrieves the system identifier identifying the document's DTD
- #
- # Method contributed by Henrik Martensson
- def system
- case @external_id
- when "SYSTEM"
- strip_quotes(@long_name)
- when "PUBLIC"
- @uri.kind_of?(String) ? strip_quotes(@uri) : nil
- end
- end
-
- # This method returns a list of notations that have been declared in the
- # _internal_ DTD subset. Notations in the external DTD subset are not
- # listed.
- #
- # Method contributed by Henrik Martensson
- def notations
- children().select {|node| node.kind_of?(REXML::NotationDecl)}
- end
-
- # Retrieves a named notation. Only notations declared in the internal
- # DTD subset can be retrieved.
- #
- # Method contributed by Henrik Martensson
- def notation(name)
- notations.find { |notation_decl|
- notation_decl.name == name
- }
- end
-
- private
-
- # Method contributed by Henrik Martensson
- def strip_quotes(quoted_string)
- quoted_string =~ /^[\'\"].*[\'\"]$/ ?
- quoted_string[1, quoted_string.length-2] :
- quoted_string
- end
- end
-
- # We don't really handle any of these since we're not a validating
- # parser, so we can be pretty dumb about them. All we need to be able
- # to do is spew them back out on a write()
-
- # This is an abstract class. You never use this directly; it serves as a
- # parent class for the specific declarations.
- class Declaration < Child
- def initialize src
- super()
- @string = src
- end
-
- def to_s
- @string+'>'
- end
-
- # == DEPRECATED
- # See REXML::Formatters
- #
- def write( output, indent )
- output << to_s
- end
- end
-
- public
- class ElementDecl < Declaration
- def initialize( src )
- super
- end
- end
-
- class ExternalEntity < Child
- def initialize( src )
- super()
- @entity = src
- end
- def to_s
- @entity
- end
- def write( output, indent )
- output << @entity
- end
- end
-
- class NotationDecl < Child
- attr_accessor :public, :system
- def initialize name, middle, pub, sys
- super(nil)
- @name = name
- @middle = middle
- @public = pub
- @system = sys
- end
-
- def to_s
- notation = "<!NOTATION #{@name} #{@middle}"
- notation << " #{@public.inspect}" if @public
- notation << " #{@system.inspect}" if @system
- notation << ">"
- notation
- end
-
- def write( output, indent=-1 )
- output << to_s
- end
-
- # This method retrieves the name of the notation.
- #
- # Method contributed by Henrik Martensson
- def name
- @name
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/document.rb b/ruby_1_9_3/lib/rexml/document.rb
deleted file mode 100644
index b945a5b76c..0000000000
--- a/ruby_1_9_3/lib/rexml/document.rb
+++ /dev/null
@@ -1,248 +0,0 @@
-require "rexml/element"
-require "rexml/xmldecl"
-require "rexml/source"
-require "rexml/comment"
-require "rexml/doctype"
-require "rexml/instruction"
-require "rexml/rexml"
-require "rexml/parseexception"
-require "rexml/output"
-require "rexml/parsers/baseparser"
-require "rexml/parsers/streamparser"
-require "rexml/parsers/treeparser"
-
-module REXML
- # Represents a full XML document, including PIs, a doctype, etc. A
- # Document has a single child that can be accessed by root().
- # Note that if you want to have an XML declaration written for a document
- # you create, you must add one; REXML documents do not write a default
- # declaration for you. See |DECLARATION| and |write|.
- class Document < Element
- # A convenient default XML declaration. If you want an XML declaration,
- # the easiest way to add one is mydoc << Document::DECLARATION
- # +DEPRECATED+
- # Use: mydoc << XMLDecl.default
- DECLARATION = XMLDecl.default
-
- # Constructor
- # @param source if supplied, must be a Document, String, or IO.
- # Documents have their context and Element attributes cloned.
- # Strings are expected to be valid XML documents. IOs are expected
- # to be sources of valid XML documents.
- # @param context if supplied, contains the context of the document;
- # this should be a Hash.
- def initialize( source = nil, context = {} )
- @entity_expansion_count = 0
- super()
- @context = context
- return if source.nil?
- if source.kind_of? Document
- @context = source.context
- super source
- else
- build( source )
- end
- end
-
- def node_type
- :document
- end
-
- # Should be obvious
- def clone
- Document.new self
- end
-
- # According to the XML spec, a root node has no expanded name
- def expanded_name
- ''
- #d = doc_type
- #d ? d.name : "UNDEFINED"
- end
-
- alias :name :expanded_name
-
- # We override this, because XMLDecls and DocTypes must go at the start
- # of the document
- def add( child )
- if child.kind_of? XMLDecl
- if @children[0].kind_of? XMLDecl
- @children[0] = child
- else
- @children.unshift child
- end
- child.parent = self
- elsif child.kind_of? DocType
- # Find first Element or DocType node and insert the decl right
- # before it. If there is no such node, just insert the child at the
- # end. If there is a child and it is an DocType, then replace it.
- insert_before_index = @children.find_index { |x|
- x.kind_of?(Element) || x.kind_of?(DocType)
- }
- if insert_before_index # Not null = not end of list
- if @children[ insert_before_index ].kind_of? DocType
- @children[ insert_before_index ] = child
- else
- @children[ insert_before_index-1, 0 ] = child
- end
- else # Insert at end of list
- @children << child
- end
- child.parent = self
- else
- rv = super
- raise "attempted adding second root element to document" if @elements.size > 1
- rv
- end
- end
- alias :<< :add
-
- def add_element(arg=nil, arg2=nil)
- rv = super
- raise "attempted adding second root element to document" if @elements.size > 1
- rv
- end
-
- # @return the root Element of the document, or nil if this document
- # has no children.
- def root
- elements[1]
- #self
- #@children.find { |item| item.kind_of? Element }
- end
-
- # @return the DocType child of the document, if one exists,
- # and nil otherwise.
- def doctype
- @children.find { |item| item.kind_of? DocType }
- end
-
- # @return the XMLDecl of this document; if no XMLDecl has been
- # set, the default declaration is returned.
- def xml_decl
- rv = @children[0]
- return rv if rv.kind_of? XMLDecl
- rv = @children.unshift(XMLDecl.default)[0]
- end
-
- # @return the XMLDecl version of this document as a String.
- # If no XMLDecl has been set, returns the default version.
- def version
- xml_decl().version
- end
-
- # @return the XMLDecl encoding of this document as an
- # Encoding object.
- # If no XMLDecl has been set, returns the default encoding.
- def encoding
- xml_decl().encoding
- end
-
- # @return the XMLDecl standalone value of this document as a String.
- # If no XMLDecl has been set, returns the default setting.
- def stand_alone?
- xml_decl().stand_alone?
- end
-
- # Write the XML tree out, optionally with indent. This writes out the
- # entire XML document, including XML declarations, doctype declarations,
- # and processing instructions (if any are given).
- #
- # A controversial point is whether Document should always write the XML
- # declaration (<?xml version='1.0'?>) whether or not one is given by the
- # user (or source document). REXML does not write one if one was not
- # specified, because it adds unnecessary bandwidth to applications such
- # as XML-RPC.
- #
- # See also the classes in the rexml/formatters package for the proper way
- # to change the default formatting of XML output
- #
- # _Examples_
- # Document.new("<a><b/></a>").serialize
- #
- # output_string = ""
- # tr = Transitive.new( output_string )
- # Document.new("<a><b/></a>").serialize( tr )
- #
- # output::
- # output an object which supports '<< string'; this is where the
- # document will be written.
- # indent::
- # An integer. If -1, no indenting will be used; otherwise, the
- # indentation will be twice this number of spaces, and children will be
- # indented an additional amount. For a value of 3, every item will be
- # indented 3 more levels, or 6 more spaces (2 * 3). Defaults to -1
- # transitive::
- # If transitive is true and indent is >= 0, then the output will be
- # pretty-printed in such a way that the added whitespace does not affect
- # the absolute *value* of the document -- that is, it leaves the value
- # and number of Text nodes in the document unchanged.
- # ie_hack::
- # Internet Explorer is the worst piece of crap to have ever been
- # written, with the possible exception of Windows itself. Since IE is
- # unable to parse proper XML, we have to provide a hack to generate XML
- # that IE's limited abilities can handle. This hack inserts a space
- # before the /> on empty tags. Defaults to false
- def write( output=$stdout, indent=-1, transitive=false, ie_hack=false )
- if xml_decl.encoding != 'UTF-8' && !output.kind_of?(Output)
- output = Output.new( output, xml_decl.encoding )
- end
- formatter = if indent > -1
- if transitive
- require "rexml/formatters/transitive"
- REXML::Formatters::Transitive.new( indent, ie_hack )
- else
- REXML::Formatters::Pretty.new( indent, ie_hack )
- end
- else
- REXML::Formatters::Default.new( ie_hack )
- end
- formatter.write( self, output )
- end
-
-
- def Document::parse_stream( source, listener )
- Parsers::StreamParser.new( source, listener ).parse
- end
-
- @@entity_expansion_limit = 10_000
-
- # Set the entity expansion limit. By default the limit is set to 10000.
- def Document::entity_expansion_limit=( val )
- @@entity_expansion_limit = val
- end
-
- # Get the entity expansion limit. By default the limit is set to 10000.
- def Document::entity_expansion_limit
- return @@entity_expansion_limit
- end
-
- # Set the entity expansion limit. By default the limit is set to 10240.
- #
- # Deprecated. Use REXML.entity_expansion_text_limit= instead.
- def Document::entity_expansion_text_limit=( val )
- REXML.entity_expansion_text_limit = val
- end
-
- # Get the entity expansion limit. By default the limit is set to 10000.
- #
- # Deprecated. Use REXML.entity_expansion_text_limit instead.
- def Document::entity_expansion_text_limit
- return REXML.entity_expansion_text_limit
- end
-
- attr_reader :entity_expansion_count
-
- def record_entity_expansion
- @entity_expansion_count += 1
- if @entity_expansion_count > @@entity_expansion_limit
- raise "number of entity expansions exceeded, processing aborted."
- end
- end
-
- private
- def build( source )
- Parsers::TreeParser.new( source, self ).parse
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/dtd/attlistdecl.rb b/ruby_1_9_3/lib/rexml/dtd/attlistdecl.rb
deleted file mode 100644
index 25955ee274..0000000000
--- a/ruby_1_9_3/lib/rexml/dtd/attlistdecl.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-require "rexml/child"
-module REXML
- module DTD
- class AttlistDecl < Child
- START = "<!ATTLIST"
- START_RE = /^\s*#{START}/um
- PATTERN_RE = /\s*(#{START}.*?>)/um
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/dtd/dtd.rb b/ruby_1_9_3/lib/rexml/dtd/dtd.rb
deleted file mode 100644
index 966e39ea57..0000000000
--- a/ruby_1_9_3/lib/rexml/dtd/dtd.rb
+++ /dev/null
@@ -1,51 +0,0 @@
-require "rexml/dtd/elementdecl"
-require "rexml/dtd/entitydecl"
-require "rexml/comment"
-require "rexml/dtd/notationdecl"
-require "rexml/dtd/attlistdecl"
-require "rexml/parent"
-
-module REXML
- module DTD
- class Parser
- def Parser.parse( input )
- case input
- when String
- parse_helper input
- when File
- parse_helper input.read
- end
- end
-
- # Takes a String and parses it out
- def Parser.parse_helper( input )
- contents = Parent.new
- while input.size > 0
- case input
- when ElementDecl.PATTERN_RE
- match = $&
- source = $'
- contents << ElementDecl.new( match )
- when AttlistDecl.PATTERN_RE
- matchdata = $~
- source = $'
- contents << AttlistDecl.new( matchdata )
- when EntityDecl.PATTERN_RE
- matchdata = $~
- source = $'
- contents << EntityDecl.new( matchdata )
- when Comment.PATTERN_RE
- matchdata = $~
- source = $'
- contents << Comment.new( matchdata )
- when NotationDecl.PATTERN_RE
- matchdata = $~
- source = $'
- contents << NotationDecl.new( matchdata )
- end
- end
- contents
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/dtd/elementdecl.rb b/ruby_1_9_3/lib/rexml/dtd/elementdecl.rb
deleted file mode 100644
index a0bf641300..0000000000
--- a/ruby_1_9_3/lib/rexml/dtd/elementdecl.rb
+++ /dev/null
@@ -1,17 +0,0 @@
-require "rexml/child"
-module REXML
- module DTD
- class ElementDecl < Child
- START = "<!ELEMENT"
- START_RE = /^\s*#{START}/um
- PATTERN_RE = /^\s*(#{START}.*?)>/um
- PATTERN_RE = /^\s*#{START}\s+((?:[:\w_][-\.\w_]*:)?[-!\*\.\w_]*)(.*?)>/
- #\s*((((["']).*?\5)|[^\/'">]*)*?)(\/)?>/um, true)
-
- def initialize match
- @name = match[1]
- @rest = match[2]
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/dtd/entitydecl.rb b/ruby_1_9_3/lib/rexml/dtd/entitydecl.rb
deleted file mode 100644
index a9286b2b90..0000000000
--- a/ruby_1_9_3/lib/rexml/dtd/entitydecl.rb
+++ /dev/null
@@ -1,56 +0,0 @@
-require "rexml/child"
-module REXML
- module DTD
- class EntityDecl < Child
- START = "<!ENTITY"
- START_RE = /^\s*#{START}/um
- PUBLIC = /^\s*#{START}\s+(?:%\s+)?(\w+)\s+PUBLIC\s+((["']).*?\3)\s+((["']).*?\5)\s*>/um
- SYSTEM = /^\s*#{START}\s+(?:%\s+)?(\w+)\s+SYSTEM\s+((["']).*?\3)(?:\s+NDATA\s+\w+)?\s*>/um
- PLAIN = /^\s*#{START}\s+(\w+)\s+((["']).*?\3)\s*>/um
- PERCENT = /^\s*#{START}\s+%\s+(\w+)\s+((["']).*?\3)\s*>/um
- # <!ENTITY name SYSTEM "...">
- # <!ENTITY name "...">
- def initialize src
- super()
- md = nil
- if src.match( PUBLIC )
- md = src.match( PUBLIC, true )
- @middle = "PUBLIC"
- @content = "#{md[2]} #{md[4]}"
- elsif src.match( SYSTEM )
- md = src.match( SYSTEM, true )
- @middle = "SYSTEM"
- @content = md[2]
- elsif src.match( PLAIN )
- md = src.match( PLAIN, true )
- @middle = ""
- @content = md[2]
- elsif src.match( PERCENT )
- md = src.match( PERCENT, true )
- @middle = ""
- @content = md[2]
- end
- raise ParseException.new("failed Entity match", src) if md.nil?
- @name = md[1]
- end
-
- def to_s
- rv = "<!ENTITY #@name "
- rv << "#@middle " if @middle.size > 0
- rv << @content
- rv
- end
-
- def write( output, indent )
- indent( output, indent )
- output << to_s
- end
-
- def EntityDecl.parse_source source, listener
- md = source.match( PATTERN_RE, true )
- thing = md[0].squeeze(" \t\n\r")
- listener.send inspect.downcase, thing
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/dtd/notationdecl.rb b/ruby_1_9_3/lib/rexml/dtd/notationdecl.rb
deleted file mode 100644
index 17d1b9ef29..0000000000
--- a/ruby_1_9_3/lib/rexml/dtd/notationdecl.rb
+++ /dev/null
@@ -1,39 +0,0 @@
-require "rexml/child"
-module REXML
- module DTD
- class NotationDecl < Child
- START = "<!NOTATION"
- START_RE = /^\s*#{START}/um
- PUBLIC = /^\s*#{START}\s+(\w[\w-]*)\s+(PUBLIC)\s+((["']).*?\4)\s*>/um
- SYSTEM = /^\s*#{START}\s+(\w[\w-]*)\s+(SYSTEM)\s+((["']).*?\4)\s*>/um
- def initialize src
- super()
- if src.match( PUBLIC )
- md = src.match( PUBLIC, true )
- elsif src.match( SYSTEM )
- md = src.match( SYSTEM, true )
- else
- raise ParseException.new( "error parsing notation: no matching pattern", src )
- end
- @name = md[1]
- @middle = md[2]
- @rest = md[3]
- end
-
- def to_s
- "<!NOTATION #@name #@middle #@rest>"
- end
-
- def write( output, indent )
- indent( output, indent )
- output << to_s
- end
-
- def NotationDecl.parse_source source, listener
- md = source.match( PATTERN_RE, true )
- thing = md[0].squeeze(" \t\n\r")
- listener.send inspect.downcase, thing
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/element.rb b/ruby_1_9_3/lib/rexml/element.rb
deleted file mode 100644
index 5991859a78..0000000000
--- a/ruby_1_9_3/lib/rexml/element.rb
+++ /dev/null
@@ -1,1245 +0,0 @@
-require "rexml/parent"
-require "rexml/namespace"
-require "rexml/attribute"
-require "rexml/cdata"
-require "rexml/xpath"
-require "rexml/parseexception"
-
-module REXML
- # An implementation note about namespaces:
- # As we parse, when we find namespaces we put them in a hash and assign
- # them a unique ID. We then convert the namespace prefix for the node
- # to the unique ID. This makes namespace lookup much faster for the
- # cost of extra memory use. We save the namespace prefix for the
- # context node and convert it back when we write it.
- @@namespaces = {}
-
- # Represents a tagged XML element. Elements are characterized by
- # having children, attributes, and names, and can themselves be
- # children.
- class Element < Parent
- include Namespace
-
- UNDEFINED = "UNDEFINED"; # The default name
-
- # Mechanisms for accessing attributes and child elements of this
- # element.
- attr_reader :attributes, :elements
- # The context holds information about the processing environment, such as
- # whitespace handling.
- attr_accessor :context
-
- # Constructor
- # arg::
- # if not supplied, will be set to the default value.
- # If a String, the name of this object will be set to the argument.
- # If an Element, the object will be shallowly cloned; name,
- # attributes, and namespaces will be copied. Children will +not+ be
- # copied.
- # parent::
- # if supplied, must be a Parent, and will be used as
- # the parent of this object.
- # context::
- # If supplied, must be a hash containing context items. Context items
- # include:
- # * <tt>:respect_whitespace</tt> the value of this is :+all+ or an array of
- # strings being the names of the elements to respect
- # whitespace for. Defaults to :+all+.
- # * <tt>:compress_whitespace</tt> the value can be :+all+ or an array of
- # strings being the names of the elements to ignore whitespace on.
- # Overrides :+respect_whitespace+.
- # * <tt>:ignore_whitespace_nodes</tt> the value can be :+all+ or an array
- # of strings being the names of the elements in which to ignore
- # whitespace-only nodes. If this is set, Text nodes which contain only
- # whitespace will not be added to the document tree.
- # * <tt>:raw</tt> can be :+all+, or an array of strings being the names of
- # the elements to process in raw mode. In raw mode, special
- # characters in text is not converted to or from entities.
- def initialize( arg = UNDEFINED, parent=nil, context=nil )
- super(parent)
-
- @elements = Elements.new(self)
- @attributes = Attributes.new(self)
- @context = context
-
- if arg.kind_of? String
- self.name = arg
- elsif arg.kind_of? Element
- self.name = arg.expanded_name
- arg.attributes.each_attribute{ |attribute|
- @attributes << Attribute.new( attribute )
- }
- @context = arg.context
- end
- end
-
- def inspect
- rv = "<#@expanded_name"
-
- @attributes.each_attribute do |attr|
- rv << " "
- attr.write( rv, 0 )
- end
-
- if children.size > 0
- rv << "> ... </>"
- else
- rv << "/>"
- end
- end
-
-
- # Creates a shallow copy of self.
- # d = Document.new "<a><b/><b/><c><d/></c></a>"
- # new_a = d.root.clone
- # puts new_a # => "<a/>"
- def clone
- self.class.new self
- end
-
- # Evaluates to the root node of the document that this element
- # belongs to. If this element doesn't belong to a document, but does
- # belong to another Element, the parent's root will be returned, until the
- # earliest ancestor is found.
- #
- # Note that this is not the same as the document element.
- # In the following example, <a> is the document element, and the root
- # node is the parent node of the document element. You may ask yourself
- # why the root node is useful: consider the doctype and XML declaration,
- # and any processing instructions before the document element... they
- # are children of the root node, or siblings of the document element.
- # The only time this isn't true is when an Element is created that is
- # not part of any Document. In this case, the ancestor that has no
- # parent acts as the root node.
- # d = Document.new '<a><b><c/></b></a>'
- # a = d[1] ; c = a[1][1]
- # d.root_node == d # TRUE
- # a.root_node # namely, d
- # c.root_node # again, d
- def root_node
- parent.nil? ? self : parent.root_node
- end
-
- def root
- return elements[1] if self.kind_of? Document
- return self if parent.kind_of? Document or parent.nil?
- return parent.root
- end
-
- # Evaluates to the document to which this element belongs, or nil if this
- # element doesn't belong to a document.
- def document
- rt = root
- rt.parent if rt
- end
-
- # Evaluates to +true+ if whitespace is respected for this element. This
- # is the case if:
- # 1. Neither :+respect_whitespace+ nor :+compress_whitespace+ has any value
- # 2. The context has :+respect_whitespace+ set to :+all+ or
- # an array containing the name of this element, and
- # :+compress_whitespace+ isn't set to :+all+ or an array containing the
- # name of this element.
- # The evaluation is tested against +expanded_name+, and so is namespace
- # sensitive.
- def whitespace
- @whitespace = nil
- if @context
- if @context[:respect_whitespace]
- @whitespace = (@context[:respect_whitespace] == :all or
- @context[:respect_whitespace].include? expanded_name)
- end
- @whitespace = false if (@context[:compress_whitespace] and
- (@context[:compress_whitespace] == :all or
- @context[:compress_whitespace].include? expanded_name)
- )
- end
- @whitespace = true unless @whitespace == false
- @whitespace
- end
-
- def ignore_whitespace_nodes
- @ignore_whitespace_nodes = false
- if @context
- if @context[:ignore_whitespace_nodes]
- @ignore_whitespace_nodes =
- (@context[:ignore_whitespace_nodes] == :all or
- @context[:ignore_whitespace_nodes].include? expanded_name)
- end
- end
- end
-
- # Evaluates to +true+ if raw mode is set for this element. This
- # is the case if the context has :+raw+ set to :+all+ or
- # an array containing the name of this element.
- #
- # The evaluation is tested against +expanded_name+, and so is namespace
- # sensitive.
- def raw
- @raw = (@context and @context[:raw] and
- (@context[:raw] == :all or
- @context[:raw].include? expanded_name))
- @raw
- end
-
- #once :whitespace, :raw, :ignore_whitespace_nodes
-
- #################################################
- # Namespaces #
- #################################################
-
- # Evaluates to an +Array+ containing the prefixes (names) of all defined
- # namespaces at this context node.
- # doc = Document.new("<a xmlns:x='1' xmlns:y='2'><b/><c xmlns:z='3'/></a>")
- # doc.elements['//b'].prefixes # -> ['x', 'y']
- def prefixes
- prefixes = []
- prefixes = parent.prefixes if parent
- prefixes |= attributes.prefixes
- return prefixes
- end
-
- def namespaces
- namespaces = {}
- namespaces = parent.namespaces if parent
- namespaces = namespaces.merge( attributes.namespaces )
- return namespaces
- end
-
- # Evalutas to the URI for a prefix, or the empty string if no such
- # namespace is declared for this element. Evaluates recursively for
- # ancestors. Returns the default namespace, if there is one.
- # prefix::
- # the prefix to search for. If not supplied, returns the default
- # namespace if one exists
- # Returns::
- # the namespace URI as a String, or nil if no such namespace
- # exists. If the namespace is undefined, returns an empty string
- # doc = Document.new("<a xmlns='1' xmlns:y='2'><b/><c xmlns:z='3'/></a>")
- # b = doc.elements['//b']
- # b.namespace # -> '1'
- # b.namespace("y") # -> '2'
- def namespace(prefix=nil)
- if prefix.nil?
- prefix = prefix()
- end
- if prefix == ''
- prefix = "xmlns"
- else
- prefix = "xmlns:#{prefix}" unless prefix[0,5] == 'xmlns'
- end
- ns = attributes[ prefix ]
- ns = parent.namespace(prefix) if ns.nil? and parent
- ns = '' if ns.nil? and prefix == 'xmlns'
- return ns
- end
-
- # Adds a namespace to this element.
- # prefix::
- # the prefix string, or the namespace URI if +uri+ is not
- # supplied
- # uri::
- # the namespace URI. May be nil, in which +prefix+ is used as
- # the URI
- # Evaluates to: this Element
- # a = Element.new("a")
- # a.add_namespace("xmlns:foo", "bar" )
- # a.add_namespace("foo", "bar") # shorthand for previous line
- # a.add_namespace("twiddle")
- # puts a #-> <a xmlns:foo='bar' xmlns='twiddle'/>
- def add_namespace( prefix, uri=nil )
- unless uri
- @attributes["xmlns"] = prefix
- else
- prefix = "xmlns:#{prefix}" unless prefix =~ /^xmlns:/
- @attributes[ prefix ] = uri
- end
- self
- end
-
- # Removes a namespace from this node. This only works if the namespace is
- # actually declared in this node. If no argument is passed, deletes the
- # default namespace.
- #
- # Evaluates to: this element
- # doc = Document.new "<a xmlns:foo='bar' xmlns='twiddle'/>"
- # doc.root.delete_namespace
- # puts doc # -> <a xmlns:foo='bar'/>
- # doc.root.delete_namespace 'foo'
- # puts doc # -> <a/>
- def delete_namespace namespace="xmlns"
- namespace = "xmlns:#{namespace}" unless namespace == 'xmlns'
- attribute = attributes.get_attribute(namespace)
- attribute.remove unless attribute.nil?
- self
- end
-
- #################################################
- # Elements #
- #################################################
-
- # Adds a child to this element, optionally setting attributes in
- # the element.
- # element::
- # optional. If Element, the element is added.
- # Otherwise, a new Element is constructed with the argument (see
- # Element.initialize).
- # attrs::
- # If supplied, must be a Hash containing String name,value
- # pairs, which will be used to set the attributes of the new Element.
- # Returns:: the Element that was added
- # el = doc.add_element 'my-tag'
- # el = doc.add_element 'my-tag', {'attr1'=>'val1', 'attr2'=>'val2'}
- # el = Element.new 'my-tag'
- # doc.add_element el
- def add_element element, attrs=nil
- raise "First argument must be either an element name, or an Element object" if element.nil?
- el = @elements.add(element)
- attrs.each do |key, value|
- el.attributes[key]=value
- end if attrs.kind_of? Hash
- el
- end
-
- # Deletes a child element.
- # element::
- # Must be an +Element+, +String+, or +Integer+. If Element,
- # the element is removed. If String, the element is found (via XPath)
- # and removed. <em>This means that any parent can remove any
- # descendant.<em> If Integer, the Element indexed by that number will be
- # removed.
- # Returns:: the element that was removed.
- # doc.delete_element "/a/b/c[@id='4']"
- # doc.delete_element doc.elements["//k"]
- # doc.delete_element 1
- def delete_element element
- @elements.delete element
- end
-
- # Evaluates to +true+ if this element has at least one child Element
- # doc = Document.new "<a><b/><c>Text</c></a>"
- # doc.root.has_elements # -> true
- # doc.elements["/a/b"].has_elements # -> false
- # doc.elements["/a/c"].has_elements # -> false
- def has_elements?
- !@elements.empty?
- end
-
- # Iterates through the child elements, yielding for each Element that
- # has a particular attribute set.
- # key::
- # the name of the attribute to search for
- # value::
- # the value of the attribute
- # max::
- # (optional) causes this method to return after yielding
- # for this number of matching children
- # name::
- # (optional) if supplied, this is an XPath that filters
- # the children to check.
- #
- # doc = Document.new "<a><b @id='1'/><c @id='2'/><d @id='1'/><e/></a>"
- # # Yields b, c, d
- # doc.root.each_element_with_attribute( 'id' ) {|e| p e}
- # # Yields b, d
- # doc.root.each_element_with_attribute( 'id', '1' ) {|e| p e}
- # # Yields b
- # doc.root.each_element_with_attribute( 'id', '1', 1 ) {|e| p e}
- # # Yields d
- # doc.root.each_element_with_attribute( 'id', '1', 0, 'd' ) {|e| p e}
- def each_element_with_attribute( key, value=nil, max=0, name=nil, &block ) # :yields: Element
- each_with_something( proc {|child|
- if value.nil?
- child.attributes[key] != nil
- else
- child.attributes[key]==value
- end
- }, max, name, &block )
- end
-
- # Iterates through the children, yielding for each Element that
- # has a particular text set.
- # text::
- # the text to search for. If nil, or not supplied, will iterate
- # over all +Element+ children that contain at least one +Text+ node.
- # max::
- # (optional) causes this method to return after yielding
- # for this number of matching children
- # name::
- # (optional) if supplied, this is an XPath that filters
- # the children to check.
- #
- # doc = Document.new '<a><b>b</b><c>b</c><d>d</d><e/></a>'
- # # Yields b, c, d
- # doc.each_element_with_text {|e|p e}
- # # Yields b, c
- # doc.each_element_with_text('b'){|e|p e}
- # # Yields b
- # doc.each_element_with_text('b', 1){|e|p e}
- # # Yields d
- # doc.each_element_with_text(nil, 0, 'd'){|e|p e}
- def each_element_with_text( text=nil, max=0, name=nil, &block ) # :yields: Element
- each_with_something( proc {|child|
- if text.nil?
- child.has_text?
- else
- child.text == text
- end
- }, max, name, &block )
- end
-
- # Synonym for Element.elements.each
- def each_element( xpath=nil, &block ) # :yields: Element
- @elements.each( xpath, &block )
- end
-
- # Synonym for Element.to_a
- # This is a little slower than calling elements.each directly.
- # xpath:: any XPath by which to search for elements in the tree
- # Returns:: an array of Elements that match the supplied path
- def get_elements( xpath )
- @elements.to_a( xpath )
- end
-
- # Returns the next sibling that is an element, or nil if there is
- # no Element sibling after this one
- # doc = Document.new '<a><b/>text<c/></a>'
- # doc.root.elements['b'].next_element #-> <c/>
- # doc.root.elements['c'].next_element #-> nil
- def next_element
- element = next_sibling
- element = element.next_sibling until element.nil? or element.kind_of? Element
- return element
- end
-
- # Returns the previous sibling that is an element, or nil if there is
- # no Element sibling prior to this one
- # doc = Document.new '<a><b/>text<c/></a>'
- # doc.root.elements['c'].previous_element #-> <b/>
- # doc.root.elements['b'].previous_element #-> nil
- def previous_element
- element = previous_sibling
- element = element.previous_sibling until element.nil? or element.kind_of? Element
- return element
- end
-
-
- #################################################
- # Text #
- #################################################
-
- # Evaluates to +true+ if this element has at least one Text child
- def has_text?
- not text().nil?
- end
-
- # A convenience method which returns the String value of the _first_
- # child text element, if one exists, and +nil+ otherwise.
- #
- # <em>Note that an element may have multiple Text elements, perhaps
- # separated by other children</em>. Be aware that this method only returns
- # the first Text node.
- #
- # This method returns the +value+ of the first text child node, which
- # ignores the +raw+ setting, so always returns normalized text. See
- # the Text::value documentation.
- #
- # doc = Document.new "<p>some text <b>this is bold!</b> more text</p>"
- # # The element 'p' has two text elements, "some text " and " more text".
- # doc.root.text #-> "some text "
- def text( path = nil )
- rv = get_text(path)
- return rv.value unless rv.nil?
- nil
- end
-
- # Returns the first child Text node, if any, or +nil+ otherwise.
- # This method returns the actual +Text+ node, rather than the String content.
- # doc = Document.new "<p>some text <b>this is bold!</b> more text</p>"
- # # The element 'p' has two text elements, "some text " and " more text".
- # doc.root.get_text.value #-> "some text "
- def get_text path = nil
- rv = nil
- if path
- element = @elements[ path ]
- rv = element.get_text unless element.nil?
- else
- rv = @children.find { |node| node.kind_of? Text }
- end
- return rv
- end
-
- # Sets the first Text child of this object. See text() for a
- # discussion about Text children.
- #
- # If a Text child already exists, the child is replaced by this
- # content. This means that Text content can be deleted by calling
- # this method with a nil argument. In this case, the next Text
- # child becomes the first Text child. In no case is the order of
- # any siblings disturbed.
- # text::
- # If a String, a new Text child is created and added to
- # this Element as the first Text child. If Text, the text is set
- # as the first Child element. If nil, then any existing first Text
- # child is removed.
- # Returns:: this Element.
- # doc = Document.new '<a><b/></a>'
- # doc.root.text = 'Sean' #-> '<a><b/>Sean</a>'
- # doc.root.text = 'Elliott' #-> '<a><b/>Elliott</a>'
- # doc.root.add_element 'c' #-> '<a><b/>Elliott<c/></a>'
- # doc.root.text = 'Russell' #-> '<a><b/>Russell<c/></a>'
- # doc.root.text = nil #-> '<a><b/><c/></a>'
- def text=( text )
- if text.kind_of? String
- text = Text.new( text, whitespace(), nil, raw() )
- elsif !text.nil? and !text.kind_of? Text
- text = Text.new( text.to_s, whitespace(), nil, raw() )
- end
- old_text = get_text
- if text.nil?
- old_text.remove unless old_text.nil?
- else
- if old_text.nil?
- self << text
- else
- old_text.replace_with( text )
- end
- end
- return self
- end
-
- # A helper method to add a Text child. Actual Text instances can
- # be added with regular Parent methods, such as add() and <<()
- # text::
- # if a String, a new Text instance is created and added
- # to the parent. If Text, the object is added directly.
- # Returns:: this Element
- # e = Element.new('a') #-> <e/>
- # e.add_text 'foo' #-> <e>foo</e>
- # e.add_text Text.new(' bar') #-> <e>foo bar</e>
- # Note that at the end of this example, the branch has <b>3</b> nodes; the 'e'
- # element and <b>2</b> Text node children.
- def add_text( text )
- if text.kind_of? String
- if @children[-1].kind_of? Text
- @children[-1] << text
- return
- end
- text = Text.new( text, whitespace(), nil, raw() )
- end
- self << text unless text.nil?
- return self
- end
-
- def node_type
- :element
- end
-
- def xpath
- path_elements = []
- cur = self
- path_elements << __to_xpath_helper( self )
- while cur.parent
- cur = cur.parent
- path_elements << __to_xpath_helper( cur )
- end
- return path_elements.reverse.join( "/" )
- end
-
- #################################################
- # Attributes #
- #################################################
-
- def attribute( name, namespace=nil )
- prefix = nil
- if namespaces.respond_to? :key
- prefix = namespaces.key(namespace) if namespace
- else
- prefix = namespaces.index(namespace) if namespace
- end
- prefix = nil if prefix == 'xmlns'
-
- ret_val =
- attributes.get_attribute( "#{prefix ? prefix + ':' : ''}#{name}" )
-
- return ret_val unless ret_val.nil?
- return nil if prefix.nil?
-
- # now check that prefix'es namespace is not the same as the
- # default namespace
- return nil unless ( namespaces[ prefix ] == namespaces[ 'xmlns' ] )
-
- attributes.get_attribute( name )
-
- end
-
- # Evaluates to +true+ if this element has any attributes set, false
- # otherwise.
- def has_attributes?
- return !@attributes.empty?
- end
-
- # Adds an attribute to this element, overwriting any existing attribute
- # by the same name.
- # key::
- # can be either an Attribute or a String. If an Attribute,
- # the attribute is added to the list of Element attributes. If String,
- # the argument is used as the name of the new attribute, and the value
- # parameter must be supplied.
- # value::
- # Required if +key+ is a String, and ignored if the first argument is
- # an Attribute. This is a String, and is used as the value
- # of the new Attribute. This should be the unnormalized value of the
- # attribute (without entities).
- # Returns:: the Attribute added
- # e = Element.new 'e'
- # e.add_attribute( 'a', 'b' ) #-> <e a='b'/>
- # e.add_attribute( 'x:a', 'c' ) #-> <e a='b' x:a='c'/>
- # e.add_attribute Attribute.new('b', 'd') #-> <e a='b' x:a='c' b='d'/>
- def add_attribute( key, value=nil )
- if key.kind_of? Attribute
- @attributes << key
- else
- @attributes[key] = value
- end
- end
-
- # Add multiple attributes to this element.
- # hash:: is either a hash, or array of arrays
- # el.add_attributes( {"name1"=>"value1", "name2"=>"value2"} )
- # el.add_attributes( [ ["name1","value1"], ["name2"=>"value2"] ] )
- def add_attributes hash
- if hash.kind_of? Hash
- hash.each_pair {|key, value| @attributes[key] = value }
- elsif hash.kind_of? Array
- hash.each { |value| @attributes[ value[0] ] = value[1] }
- end
- end
-
- # Removes an attribute
- # key::
- # either an Attribute or a String. In either case, the
- # attribute is found by matching the attribute name to the argument,
- # and then removed. If no attribute is found, no action is taken.
- # Returns::
- # the attribute removed, or nil if this Element did not contain
- # a matching attribute
- # e = Element.new('E')
- # e.add_attribute( 'name', 'Sean' ) #-> <E name='Sean'/>
- # r = e.add_attribute( 'sur:name', 'Russell' ) #-> <E name='Sean' sur:name='Russell'/>
- # e.delete_attribute( 'name' ) #-> <E sur:name='Russell'/>
- # e.delete_attribute( r ) #-> <E/>
- def delete_attribute(key)
- attr = @attributes.get_attribute(key)
- attr.remove unless attr.nil?
- end
-
- #################################################
- # Other Utilities #
- #################################################
-
- # Get an array of all CData children.
- # IMMUTABLE
- def cdatas
- find_all { |child| child.kind_of? CData }.freeze
- end
-
- # Get an array of all Comment children.
- # IMMUTABLE
- def comments
- find_all { |child| child.kind_of? Comment }.freeze
- end
-
- # Get an array of all Instruction children.
- # IMMUTABLE
- def instructions
- find_all { |child| child.kind_of? Instruction }.freeze
- end
-
- # Get an array of all Text children.
- # IMMUTABLE
- def texts
- find_all { |child| child.kind_of? Text }.freeze
- end
-
- # == DEPRECATED
- # See REXML::Formatters
- #
- # Writes out this element, and recursively, all children.
- # output::
- # output an object which supports '<< string'; this is where the
- # document will be written.
- # indent::
- # An integer. If -1, no indenting will be used; otherwise, the
- # indentation will be this number of spaces, and children will be
- # indented an additional amount. Defaults to -1
- # transitive::
- # If transitive is true and indent is >= 0, then the output will be
- # pretty-printed in such a way that the added whitespace does not affect
- # the parse tree of the document
- # ie_hack::
- # Internet Explorer is the worst piece of crap to have ever been
- # written, with the possible exception of Windows itself. Since IE is
- # unable to parse proper XML, we have to provide a hack to generate XML
- # that IE's limited abilities can handle. This hack inserts a space
- # before the /> on empty tags. Defaults to false
- #
- # out = ''
- # doc.write( out ) #-> doc is written to the string 'out'
- # doc.write( $stdout ) #-> doc written to the console
- def write(output=$stdout, indent=-1, transitive=false, ie_hack=false)
- Kernel.warn("#{self.class.name}.write is deprecated. See REXML::Formatters")
- formatter = if indent > -1
- if transitive
- require "rexml/formatters/transitive"
- REXML::Formatters::Transitive.new( indent, ie_hack )
- else
- REXML::Formatters::Pretty.new( indent, ie_hack )
- end
- else
- REXML::Formatters::Default.new( ie_hack )
- end
- formatter.write( self, output )
- end
-
-
- private
- def __to_xpath_helper node
- rv = node.expanded_name.clone
- if node.parent
- results = node.parent.find_all {|n|
- n.kind_of?(REXML::Element) and n.expanded_name == node.expanded_name
- }
- if results.length > 1
- idx = results.index( node )
- rv << "[#{idx+1}]"
- end
- end
- rv
- end
-
- # A private helper method
- def each_with_something( test, max=0, name=nil )
- num = 0
- @elements.each( name ){ |child|
- yield child if test.call(child) and num += 1
- return if max>0 and num == max
- }
- end
- end
-
- ########################################################################
- # ELEMENTS #
- ########################################################################
-
- # A class which provides filtering of children for Elements, and
- # XPath search support. You are expected to only encounter this class as
- # the <tt>element.elements</tt> object. Therefore, you are
- # _not_ expected to instantiate this yourself.
- class Elements
- include Enumerable
- # Constructor
- # parent:: the parent Element
- def initialize parent
- @element = parent
- end
-
- # Fetches a child element. Filters only Element children, regardless of
- # the XPath match.
- # index::
- # the search parameter. This is either an Integer, which
- # will be used to find the index'th child Element, or an XPath,
- # which will be used to search for the Element. <em>Because
- # of the nature of XPath searches, any element in the connected XML
- # document can be fetched through any other element.</em> <b>The
- # Integer index is 1-based, not 0-based.</b> This means that the first
- # child element is at index 1, not 0, and the +n+th element is at index
- # +n+, not <tt>n-1</tt>. This is because XPath indexes element children
- # starting from 1, not 0, and the indexes should be the same.
- # name::
- # optional, and only used in the first argument is an
- # Integer. In that case, the index'th child Element that has the
- # supplied name will be returned. Note again that the indexes start at 1.
- # Returns:: the first matching Element, or nil if no child matched
- # doc = Document.new '<a><b/><c id="1"/><c id="2"/><d/></a>'
- # doc.root.elements[1] #-> <b/>
- # doc.root.elements['c'] #-> <c id="1"/>
- # doc.root.elements[2,'c'] #-> <c id="2"/>
- def []( index, name=nil)
- if index.kind_of? Integer
- raise "index (#{index}) must be >= 1" if index < 1
- name = literalize(name) if name
- num = 0
- @element.find { |child|
- child.kind_of? Element and
- (name.nil? ? true : child.has_name?( name )) and
- (num += 1) == index
- }
- else
- return XPath::first( @element, index )
- #{ |element|
- # return element if element.kind_of? Element
- #}
- #return nil
- end
- end
-
- # Sets an element, replacing any previous matching element. If no
- # existing element is found ,the element is added.
- # index:: Used to find a matching element to replace. See []().
- # element::
- # The element to replace the existing element with
- # the previous element
- # Returns:: nil if no previous element was found.
- #
- # doc = Document.new '<a/>'
- # doc.root.elements[10] = Element.new('b') #-> <a><b/></a>
- # doc.root.elements[1] #-> <b/>
- # doc.root.elements[1] = Element.new('c') #-> <a><c/></a>
- # doc.root.elements['c'] = Element.new('d') #-> <a><d/></a>
- def []=( index, element )
- previous = self[index]
- if previous.nil?
- @element.add element
- else
- previous.replace_with element
- end
- return previous
- end
-
- # Returns +true+ if there are no +Element+ children, +false+ otherwise
- def empty?
- @element.find{ |child| child.kind_of? Element}.nil?
- end
-
- # Returns the index of the supplied child (starting at 1), or -1 if
- # the element is not a child
- # element:: an +Element+ child
- def index element
- rv = 0
- found = @element.find do |child|
- child.kind_of? Element and
- (rv += 1) and
- child == element
- end
- return rv if found == element
- return -1
- end
-
- # Deletes a child Element
- # element::
- # Either an Element, which is removed directly; an
- # xpath, where the first matching child is removed; or an Integer,
- # where the n'th Element is removed.
- # Returns:: the removed child
- # doc = Document.new '<a><b/><c/><c id="1"/></a>'
- # b = doc.root.elements[1]
- # doc.root.elements.delete b #-> <a><c/><c id="1"/></a>
- # doc.elements.delete("a/c[@id='1']") #-> <a><c/></a>
- # doc.root.elements.delete 1 #-> <a/>
- def delete element
- if element.kind_of? Element
- @element.delete element
- else
- el = self[element]
- el.remove if el
- end
- end
-
- # Removes multiple elements. Filters for Element children, regardless of
- # XPath matching.
- # xpath:: all elements matching this String path are removed.
- # Returns:: an Array of Elements that have been removed
- # doc = Document.new '<a><c/><c/><c/><c/></a>'
- # deleted = doc.elements.delete_all 'a/c' #-> [<c/>, <c/>, <c/>, <c/>]
- def delete_all( xpath )
- rv = []
- XPath::each( @element, xpath) {|element|
- rv << element if element.kind_of? Element
- }
- rv.each do |element|
- @element.delete element
- element.remove
- end
- return rv
- end
-
- # Adds an element
- # element::
- # if supplied, is either an Element, String, or
- # Source (see Element.initialize). If not supplied or nil, a
- # new, default Element will be constructed
- # Returns:: the added Element
- # a = Element.new('a')
- # a.elements.add(Element.new('b')) #-> <a><b/></a>
- # a.elements.add('c') #-> <a><b/><c/></a>
- def add element=nil
- if element.nil?
- Element.new("", self, @element.context)
- elsif not element.kind_of?(Element)
- Element.new(element, self, @element.context)
- else
- @element << element
- element.context = @element.context
- element
- end
- end
-
- alias :<< :add
-
- # Iterates through all of the child Elements, optionally filtering
- # them by a given XPath
- # xpath::
- # optional. If supplied, this is a String XPath, and is used to
- # filter the children, so that only matching children are yielded. Note
- # that XPaths are automatically filtered for Elements, so that
- # non-Element children will not be yielded
- # doc = Document.new '<a><b/><c/><d/>sean<b/><c/><d/></a>'
- # doc.root.each {|e|p e} #-> Yields b, c, d, b, c, d elements
- # doc.root.each('b') {|e|p e} #-> Yields b, b elements
- # doc.root.each('child::node()') {|e|p e}
- # #-> Yields <b/>, <c/>, <d/>, <b/>, <c/>, <d/>
- # XPath.each(doc.root, 'child::node()', &block)
- # #-> Yields <b/>, <c/>, <d/>, sean, <b/>, <c/>, <d/>
- def each( xpath=nil, &block)
- XPath::each( @element, xpath ) {|e| yield e if e.kind_of? Element }
- end
-
- def collect( xpath=nil, &block )
- collection = []
- XPath::each( @element, xpath ) {|e|
- collection << yield(e) if e.kind_of?(Element)
- }
- collection
- end
-
- def inject( xpath=nil, initial=nil, &block )
- first = true
- XPath::each( @element, xpath ) {|e|
- if (e.kind_of? Element)
- if (first and initial == nil)
- initial = e
- first = false
- else
- initial = yield( initial, e ) if e.kind_of? Element
- end
- end
- }
- initial
- end
-
- # Returns the number of +Element+ children of the parent object.
- # doc = Document.new '<a>sean<b/>elliott<b/>russell<b/></a>'
- # doc.root.size #-> 6, 3 element and 3 text nodes
- # doc.root.elements.size #-> 3
- def size
- count = 0
- @element.each {|child| count+=1 if child.kind_of? Element }
- count
- end
-
- # Returns an Array of Element children. An XPath may be supplied to
- # filter the children. Only Element children are returned, even if the
- # supplied XPath matches non-Element children.
- # doc = Document.new '<a>sean<b/>elliott<c/></a>'
- # doc.root.elements.to_a #-> [ <b/>, <c/> ]
- # doc.root.elements.to_a("child::node()") #-> [ <b/>, <c/> ]
- # XPath.match(doc.root, "child::node()") #-> [ sean, <b/>, elliott, <c/> ]
- def to_a( xpath=nil )
- rv = XPath.match( @element, xpath )
- return rv.find_all{|e| e.kind_of? Element} if xpath
- rv
- end
-
- private
- # Private helper class. Removes quotes from quoted strings
- def literalize name
- name = name[1..-2] if name[0] == ?' or name[0] == ?" #'
- name
- end
- end
-
- ########################################################################
- # ATTRIBUTES #
- ########################################################################
-
- # A class that defines the set of Attributes of an Element and provides
- # operations for accessing elements in that set.
- class Attributes < Hash
- # Constructor
- # element:: the Element of which this is an Attribute
- def initialize element
- @element = element
- end
-
- # Fetches an attribute value. If you want to get the Attribute itself,
- # use get_attribute()
- # name:: an XPath attribute name. Namespaces are relevant here.
- # Returns::
- # the String value of the matching attribute, or +nil+ if no
- # matching attribute was found. This is the unnormalized value
- # (with entities expanded).
- #
- # doc = Document.new "<a foo:att='1' bar:att='2' att='&lt;'/>"
- # doc.root.attributes['att'] #-> '<'
- # doc.root.attributes['bar:att'] #-> '2'
- def [](name)
- attr = get_attribute(name)
- return attr.value unless attr.nil?
- return nil
- end
-
- def to_a
- values.flatten
- end
-
- # Returns the number of attributes the owning Element contains.
- # doc = Document "<a x='1' y='2' foo:x='3'/>"
- # doc.root.attributes.length #-> 3
- def length
- c = 0
- each_attribute { c+=1 }
- c
- end
- alias :size :length
-
- # Iterates over the attributes of an Element. Yields actual Attribute
- # nodes, not String values.
- #
- # doc = Document.new '<a x="1" y="2"/>'
- # doc.root.attributes.each_attribute {|attr|
- # p attr.expanded_name+" => "+attr.value
- # }
- def each_attribute # :yields: attribute
- each_value do |val|
- if val.kind_of? Attribute
- yield val
- else
- val.each_value { |atr| yield atr }
- end
- end
- end
-
- # Iterates over each attribute of an Element, yielding the expanded name
- # and value as a pair of Strings.
- #
- # doc = Document.new '<a x="1" y="2"/>'
- # doc.root.attributes.each {|name, value| p name+" => "+value }
- def each
- each_attribute do |attr|
- yield [attr.expanded_name, attr.value]
- end
- end
-
- # Fetches an attribute
- # name::
- # the name by which to search for the attribute. Can be a
- # <tt>prefix:name</tt> namespace name.
- # Returns:: The first matching attribute, or nil if there was none. This
- # value is an Attribute node, not the String value of the attribute.
- # doc = Document.new '<a x:foo="1" foo="2" bar="3"/>'
- # doc.root.attributes.get_attribute("foo").value #-> "2"
- # doc.root.attributes.get_attribute("x:foo").value #-> "1"
- def get_attribute( name )
- attr = fetch( name, nil )
- if attr.nil?
- return nil if name.nil?
- # Look for prefix
- name =~ Namespace::NAMESPLIT
- prefix, n = $1, $2
- if prefix
- attr = fetch( n, nil )
- # check prefix
- if attr == nil
- elsif attr.kind_of? Attribute
- return attr if prefix == attr.prefix
- else
- attr = attr[ prefix ]
- return attr
- end
- end
- element_document = @element.document
- if element_document and element_document.doctype
- expn = @element.expanded_name
- expn = element_document.doctype.name if expn.size == 0
- attr_val = element_document.doctype.attribute_of(expn, name)
- return Attribute.new( name, attr_val ) if attr_val
- end
- return nil
- end
- if attr.kind_of? Hash
- attr = attr[ @element.prefix ]
- end
- return attr
- end
-
- # Sets an attribute, overwriting any existing attribute value by the
- # same name. Namespace is significant.
- # name:: the name of the attribute
- # value::
- # (optional) If supplied, the value of the attribute. If
- # nil, any existing matching attribute is deleted.
- # Returns::
- # Owning element
- # doc = Document.new "<a x:foo='1' foo='3'/>"
- # doc.root.attributes['y:foo'] = '2'
- # doc.root.attributes['foo'] = '4'
- # doc.root.attributes['x:foo'] = nil
- def []=( name, value )
- if value.nil? # Delete the named attribute
- attr = get_attribute(name)
- delete attr
- return
- end
-
- unless value.kind_of? Attribute
- if @element.document and @element.document.doctype
- value = Text::normalize( value, @element.document.doctype )
- else
- value = Text::normalize( value, nil )
- end
- value = Attribute.new(name, value)
- end
- value.element = @element
- old_attr = fetch(value.name, nil)
- if old_attr.nil?
- store(value.name, value)
- elsif old_attr.kind_of? Hash
- old_attr[value.prefix] = value
- elsif old_attr.prefix != value.prefix
- # Check for conflicting namespaces
- raise ParseException.new(
- "Namespace conflict in adding attribute \"#{value.name}\": "+
- "Prefix \"#{old_attr.prefix}\" = "+
- "\"#{@element.namespace(old_attr.prefix)}\" and prefix "+
- "\"#{value.prefix}\" = \"#{@element.namespace(value.prefix)}\"") if
- value.prefix != "xmlns" and old_attr.prefix != "xmlns" and
- @element.namespace( old_attr.prefix ) ==
- @element.namespace( value.prefix )
- store value.name, { old_attr.prefix => old_attr,
- value.prefix => value }
- else
- store value.name, value
- end
- return @element
- end
-
- # Returns an array of Strings containing all of the prefixes declared
- # by this set of # attributes. The array does not include the default
- # namespace declaration, if one exists.
- # doc = Document.new("<a xmlns='foo' xmlns:x='bar' xmlns:y='twee' "+
- # "z='glorp' p:k='gru'/>")
- # prefixes = doc.root.attributes.prefixes #-> ['x', 'y']
- def prefixes
- ns = []
- each_attribute do |attribute|
- ns << attribute.name if attribute.prefix == 'xmlns'
- end
- if @element.document and @element.document.doctype
- expn = @element.expanded_name
- expn = @element.document.doctype.name if expn.size == 0
- @element.document.doctype.attributes_of(expn).each {
- |attribute|
- ns << attribute.name if attribute.prefix == 'xmlns'
- }
- end
- ns
- end
-
- def namespaces
- namespaces = {}
- each_attribute do |attribute|
- namespaces[attribute.name] = attribute.value if attribute.prefix == 'xmlns' or attribute.name == 'xmlns'
- end
- if @element.document and @element.document.doctype
- expn = @element.expanded_name
- expn = @element.document.doctype.name if expn.size == 0
- @element.document.doctype.attributes_of(expn).each {
- |attribute|
- namespaces[attribute.name] = attribute.value if attribute.prefix == 'xmlns' or attribute.name == 'xmlns'
- }
- end
- namespaces
- end
-
- # Removes an attribute
- # attribute::
- # either a String, which is the name of the attribute to remove --
- # namespaces are significant here -- or the attribute to remove.
- # Returns:: the owning element
- # doc = Document.new "<a y:foo='0' x:foo='1' foo='3' z:foo='4'/>"
- # doc.root.attributes.delete 'foo' #-> <a y:foo='0' x:foo='1' z:foo='4'/>"
- # doc.root.attributes.delete 'x:foo' #-> <a y:foo='0' z:foo='4'/>"
- # attr = doc.root.attributes.get_attribute('y:foo')
- # doc.root.attributes.delete attr #-> <a z:foo='4'/>"
- def delete( attribute )
- name = nil
- prefix = nil
- if attribute.kind_of? Attribute
- name = attribute.name
- prefix = attribute.prefix
- else
- attribute =~ Namespace::NAMESPLIT
- prefix, name = $1, $2
- prefix = '' unless prefix
- end
- old = fetch(name, nil)
- attr = nil
- if old.kind_of? Hash # the supplied attribute is one of many
- attr = old.delete(prefix)
- if old.size == 1
- repl = nil
- old.each_value{|v| repl = v}
- store name, repl
- end
- elsif old.nil?
- return @element
- else # the supplied attribute is a top-level one
- attr = old
- super(name)
- end
- @element
- end
-
- # Adds an attribute, overriding any existing attribute by the
- # same name. Namespaces are significant.
- # attribute:: An Attribute
- def add( attribute )
- self[attribute.name] = attribute
- end
-
- alias :<< :add
-
- # Deletes all attributes matching a name. Namespaces are significant.
- # name::
- # A String; all attributes that match this path will be removed
- # Returns:: an Array of the Attributes that were removed
- def delete_all( name )
- rv = []
- each_attribute { |attribute|
- rv << attribute if attribute.expanded_name == name
- }
- rv.each{ |attr| attr.remove }
- return rv
- end
-
- # The +get_attribute_ns+ method retrieves a method by its namespace
- # and name. Thus it is possible to reliably identify an attribute
- # even if an XML processor has changed the prefix.
- #
- # Method contributed by Henrik Martensson
- def get_attribute_ns(namespace, name)
- result = nil
- each_attribute() { |attribute|
- if name == attribute.name &&
- namespace == attribute.namespace() &&
- ( !namespace.empty? || !attribute.fully_expanded_name.index(':') )
- # foo will match xmlns:foo, but only if foo isn't also an attribute
- result = attribute if !result or !namespace.empty? or
- !attribute.fully_expanded_name.index(':')
- end
- }
- result
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/encoding.rb b/ruby_1_9_3/lib/rexml/encoding.rb
deleted file mode 100644
index d1d5172841..0000000000
--- a/ruby_1_9_3/lib/rexml/encoding.rb
+++ /dev/null
@@ -1,62 +0,0 @@
-module REXML
- module Encoding
- # ID ---> Encoding name
- attr_reader :encoding
- def encoding=(encoding)
- encoding = encoding.name if encoding.is_a?(Encoding)
- if encoding.is_a?(String)
- original_encoding = encoding
- encoding = find_encoding(encoding)
- unless encoding
- raise ArgumentError, "Bad encoding name #{original_encoding}"
- end
- end
- return false if defined?(@encoding) and encoding == @encoding
- if encoding
- @encoding = encoding.upcase
- else
- @encoding = 'UTF-8'
- end
- true
- end
-
- def check_encoding(xml)
- # We have to recognize UTF-16BE, UTF-16LE, and UTF-8
- if xml[0, 2] == "\xfe\xff"
- xml[0, 2] = ""
- return 'UTF-16BE'
- elsif xml[0, 2] == "\xff\xfe"
- xml[0, 2] = ""
- return 'UTF-16LE'
- end
- xml =~ /^\s*<\?xml\s+version\s*=\s*(['"]).*?\1\s+encoding\s*=\s*(["'])(.*?)\2/m
- return $3 ? $3.upcase : 'UTF-8'
- end
-
- def encode(string)
- string.encode(@encoding)
- end
-
- def decode(string)
- string.encode(::Encoding::UTF_8, @encoding)
- end
-
- private
- def find_encoding(name)
- case name
- when /\Ashift-jis\z/i
- return "SHIFT_JIS"
- when /\ACP-(\d+)\z/
- name = "CP#{$1}"
- when /\AUTF-8\z/i
- return name
- end
- begin
- ::Encoding::Converter.search_convpath(name, 'UTF-8')
- rescue ::Encoding::ConverterNotFoundError
- return nil
- end
- name
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/entity.rb b/ruby_1_9_3/lib/rexml/entity.rb
deleted file mode 100644
index 3d81fbc738..0000000000
--- a/ruby_1_9_3/lib/rexml/entity.rb
+++ /dev/null
@@ -1,166 +0,0 @@
-require 'rexml/child'
-require 'rexml/source'
-require 'rexml/xmltokens'
-
-module REXML
- # God, I hate DTDs. I really do. Why this idiot standard still
- # plagues us is beyond me.
- class Entity < Child
- include XMLTokens
- PUBIDCHAR = "\x20\x0D\x0Aa-zA-Z0-9\\-()+,./:=?;!*@$_%#"
- SYSTEMLITERAL = %Q{((?:"[^"]*")|(?:'[^']*'))}
- PUBIDLITERAL = %Q{("[#{PUBIDCHAR}']*"|'[#{PUBIDCHAR}]*')}
- EXTERNALID = "(?:(?:(SYSTEM)\\s+#{SYSTEMLITERAL})|(?:(PUBLIC)\\s+#{PUBIDLITERAL}\\s+#{SYSTEMLITERAL}))"
- NDATADECL = "\\s+NDATA\\s+#{NAME}"
- PEREFERENCE = "%#{NAME};"
- ENTITYVALUE = %Q{((?:"(?:[^%&"]|#{PEREFERENCE}|#{REFERENCE})*")|(?:'([^%&']|#{PEREFERENCE}|#{REFERENCE})*'))}
- PEDEF = "(?:#{ENTITYVALUE}|#{EXTERNALID})"
- ENTITYDEF = "(?:#{ENTITYVALUE}|(?:#{EXTERNALID}(#{NDATADECL})?))"
- PEDECL = "<!ENTITY\\s+(%)\\s+#{NAME}\\s+#{PEDEF}\\s*>"
- GEDECL = "<!ENTITY\\s+#{NAME}\\s+#{ENTITYDEF}\\s*>"
- ENTITYDECL = /\s*(?:#{GEDECL})|(?:#{PEDECL})/um
-
- attr_reader :name, :external, :ref, :ndata, :pubid
-
- # Create a new entity. Simple entities can be constructed by passing a
- # name, value to the constructor; this creates a generic, plain entity
- # reference. For anything more complicated, you have to pass a Source to
- # the constructor with the entity definition, or use the accessor methods.
- # +WARNING+: There is no validation of entity state except when the entity
- # is read from a stream. If you start poking around with the accessors,
- # you can easily create a non-conformant Entity. The best thing to do is
- # dump the stupid DTDs and use XMLSchema instead.
- #
- # e = Entity.new( 'amp', '&' )
- def initialize stream, value=nil, parent=nil, reference=false
- super(parent)
- @ndata = @pubid = @value = @external = nil
- if stream.kind_of? Array
- @name = stream[1]
- if stream[-1] == '%'
- @reference = true
- stream.pop
- else
- @reference = false
- end
- if stream[2] =~ /SYSTEM|PUBLIC/
- @external = stream[2]
- if @external == 'SYSTEM'
- @ref = stream[3]
- @ndata = stream[4] if stream.size == 5
- else
- @pubid = stream[3]
- @ref = stream[4]
- end
- else
- @value = stream[2]
- end
- else
- @reference = reference
- @external = nil
- @name = stream
- @value = value
- end
- end
-
- # Evaluates whether the given string matchs an entity definition,
- # returning true if so, and false otherwise.
- def Entity::matches? string
- (ENTITYDECL =~ string) == 0
- end
-
- # Evaluates to the unnormalized value of this entity; that is, replacing
- # all entities -- both %ent; and &ent; entities. This differs from
- # +value()+ in that +value+ only replaces %ent; entities.
- def unnormalized
- document.record_entity_expansion unless document.nil?
- v = value()
- return nil if v.nil?
- @unnormalized = Text::unnormalize(v, parent)
- @unnormalized
- end
-
- #once :unnormalized
-
- # Returns the value of this entity unprocessed -- raw. This is the
- # normalized value; that is, with all %ent; and &ent; entities intact
- def normalized
- @value
- end
-
- # Write out a fully formed, correct entity definition (assuming the Entity
- # object itself is valid.)
- #
- # out::
- # An object implementing <TT>&lt;&lt;<TT> to which the entity will be
- # output
- # indent::
- # *DEPRECATED* and ignored
- def write out, indent=-1
- out << '<!ENTITY '
- out << '% ' if @reference
- out << @name
- out << ' '
- if @external
- out << @external << ' '
- if @pubid
- q = @pubid.include?('"')?"'":'"'
- out << q << @pubid << q << ' '
- end
- q = @ref.include?('"')?"'":'"'
- out << q << @ref << q
- out << ' NDATA ' << @ndata if @ndata
- else
- q = @value.include?('"')?"'":'"'
- out << q << @value << q
- end
- out << '>'
- end
-
- # Returns this entity as a string. See write().
- def to_s
- rv = ''
- write rv
- rv
- end
-
- PEREFERENCE_RE = /#{PEREFERENCE}/um
- # Returns the value of this entity. At the moment, only internal entities
- # are processed. If the value contains internal references (IE,
- # %blah;), those are replaced with their values. IE, if the doctype
- # contains:
- # <!ENTITY % foo "bar">
- # <!ENTITY yada "nanoo %foo; nanoo>
- # then:
- # doctype.entity('yada').value #-> "nanoo bar nanoo"
- def value
- if @value
- matches = @value.scan(PEREFERENCE_RE)
- rv = @value.clone
- if @parent
- matches.each do |entity_reference|
- entity_value = @parent.entity( entity_reference[0] )
- rv.gsub!( /%#{entity_reference.join};/um, entity_value )
- end
- end
- return rv
- end
- nil
- end
- end
-
- # This is a set of entity constants -- the ones defined in the XML
- # specification. These are +gt+, +lt+, +amp+, +quot+ and +apos+.
- module EntityConst
- # +>+
- GT = Entity.new( 'gt', '>' )
- # +<+
- LT = Entity.new( 'lt', '<' )
- # +&+
- AMP = Entity.new( 'amp', '&' )
- # +"+
- QUOT = Entity.new( 'quot', '"' )
- # +'+
- APOS = Entity.new( 'apos', "'" )
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/formatters/default.rb b/ruby_1_9_3/lib/rexml/formatters/default.rb
deleted file mode 100644
index 574c821f96..0000000000
--- a/ruby_1_9_3/lib/rexml/formatters/default.rb
+++ /dev/null
@@ -1,111 +0,0 @@
-module REXML
- module Formatters
- class Default
- # Prints out the XML document with no formatting -- except if id_hack is
- # set.
- #
- # ie_hack::
- # If set to true, then inserts whitespace before the close of an empty
- # tag, so that IE's bad XML parser doesn't choke.
- def initialize( ie_hack=false )
- @ie_hack = ie_hack
- end
-
- # Writes the node to some output.
- #
- # node::
- # The node to write
- # output::
- # A class implementing <TT>&lt;&lt;</TT>. Pass in an Output object to
- # change the output encoding.
- def write( node, output )
- case node
-
- when Document
- if node.xml_decl.encoding != 'UTF-8' && !output.kind_of?(Output)
- output = Output.new( output, node.xml_decl.encoding )
- end
- write_document( node, output )
-
- when Element
- write_element( node, output )
-
- when Declaration, ElementDecl, NotationDecl, ExternalEntity, Entity,
- Attribute, AttlistDecl
- node.write( output,-1 )
-
- when Instruction
- write_instruction( node, output )
-
- when DocType, XMLDecl
- node.write( output )
-
- when Comment
- write_comment( node, output )
-
- when CData
- write_cdata( node, output )
-
- when Text
- write_text( node, output )
-
- else
- raise Exception.new("XML FORMATTING ERROR")
-
- end
- end
-
- protected
- def write_document( node, output )
- node.children.each { |child| write( child, output ) }
- end
-
- def write_element( node, output )
- output << "<#{node.expanded_name}"
-
- node.attributes.to_a.map { |a|
- Hash === a ? a.values : a
- }.flatten.sort_by {|attr| attr.name}.each do |attr|
- output << " "
- attr.write( output )
- end unless node.attributes.empty?
-
- if node.children.empty?
- output << " " if @ie_hack
- output << "/"
- else
- output << ">"
- node.children.each { |child|
- write( child, output )
- }
- output << "</#{node.expanded_name}"
- end
- output << ">"
- end
-
- def write_text( node, output )
- output << node.to_s()
- end
-
- def write_comment( node, output )
- output << Comment::START
- output << node.to_s
- output << Comment::STOP
- end
-
- def write_cdata( node, output )
- output << CData::START
- output << node.to_s
- output << CData::STOP
- end
-
- def write_instruction( node, output )
- output << Instruction::START.sub(/\\/u, '')
- output << node.target
- output << ' '
- output << node.content
- output << Instruction::STOP.sub(/\\/u, '')
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/formatters/pretty.rb b/ruby_1_9_3/lib/rexml/formatters/pretty.rb
deleted file mode 100644
index 63f726e8c3..0000000000
--- a/ruby_1_9_3/lib/rexml/formatters/pretty.rb
+++ /dev/null
@@ -1,141 +0,0 @@
-require 'rexml/formatters/default'
-
-module REXML
- module Formatters
- # Pretty-prints an XML document. This destroys whitespace in text nodes
- # and will insert carriage returns and indentations.
- #
- # TODO: Add an option to print attributes on new lines
- class Pretty < Default
-
- # If compact is set to true, then the formatter will attempt to use as
- # little space as possible
- attr_accessor :compact
- # The width of a page. Used for formatting text
- attr_accessor :width
-
- # Create a new pretty printer.
- #
- # output::
- # An object implementing '<<(String)', to which the output will be written.
- # indentation::
- # An integer greater than 0. The indentation of each level will be
- # this number of spaces. If this is < 1, the behavior of this object
- # is undefined. Defaults to 2.
- # ie_hack::
- # If true, the printer will insert whitespace before closing empty
- # tags, thereby allowing Internet Explorer's feeble XML parser to
- # function. Defaults to false.
- def initialize( indentation=2, ie_hack=false )
- @indentation = indentation
- @level = 0
- @ie_hack = ie_hack
- @width = 80
- @compact = false
- end
-
- protected
- def write_element(node, output)
- output << ' '*@level
- output << "<#{node.expanded_name}"
-
- node.attributes.each_attribute do |attr|
- output << " "
- attr.write( output )
- end unless node.attributes.empty?
-
- if node.children.empty?
- if @ie_hack
- output << " "
- end
- output << "/"
- else
- output << ">"
- # If compact and all children are text, and if the formatted output
- # is less than the specified width, then try to print everything on
- # one line
- skip = false
- if compact
- if node.children.inject(true) {|s,c| s & c.kind_of?(Text)}
- string = ""
- old_level = @level
- @level = 0
- node.children.each { |child| write( child, string ) }
- @level = old_level
- if string.length < @width
- output << string
- skip = true
- end
- end
- end
- unless skip
- output << "\n"
- @level += @indentation
- node.children.each { |child|
- next if child.kind_of?(Text) and child.to_s.strip.length == 0
- write( child, output )
- output << "\n"
- }
- @level -= @indentation
- output << ' '*@level
- end
- output << "</#{node.expanded_name}"
- end
- output << ">"
- end
-
- def write_text( node, output )
- s = node.to_s()
- s.gsub!(/\s/,' ')
- s.squeeze!(" ")
- s = wrap(s, @width - @level)
- s = indent_text(s, @level, " ", true)
- output << (' '*@level + s)
- end
-
- def write_comment( node, output)
- output << ' ' * @level
- super
- end
-
- def write_cdata( node, output)
- output << ' ' * @level
- super
- end
-
- def write_document( node, output )
- # Ok, this is a bit odd. All XML documents have an XML declaration,
- # but it may not write itself if the user didn't specifically add it,
- # either through the API or in the input document. If it doesn't write
- # itself, then we don't need a carriage return... which makes this
- # logic more complex.
- node.children.each { |child|
- next if child == node.children[-1] and child.instance_of?(Text)
- unless child == node.children[0] or child.instance_of?(Text) or
- (child == node.children[1] and !node.children[0].writethis)
- output << "\n"
- end
- write( child, output )
- }
- end
-
- private
- def indent_text(string, level=1, style="\t", indentfirstline=true)
- return string if level < 0
- string.gsub(/\n/, "\n#{style*level}")
- end
-
- def wrap(string, width)
- parts = []
- while string.length > width and place = string.rindex(' ', width)
- parts << string[0...place]
- string = string[place+1..-1]
- end
- parts << string
- parts.join("\n")
- end
-
- end
- end
-end
-
diff --git a/ruby_1_9_3/lib/rexml/formatters/transitive.rb b/ruby_1_9_3/lib/rexml/formatters/transitive.rb
deleted file mode 100644
index 6cc690d922..0000000000
--- a/ruby_1_9_3/lib/rexml/formatters/transitive.rb
+++ /dev/null
@@ -1,57 +0,0 @@
-require 'rexml/formatters/pretty'
-
-module REXML
- module Formatters
- # The Transitive formatter writes an XML document that parses to an
- # identical document as the source document. This means that no extra
- # whitespace nodes are inserted, and whitespace within text nodes is
- # preserved. Within these constraints, the document is pretty-printed,
- # with whitespace inserted into the metadata to introduce formatting.
- #
- # Note that this is only useful if the original XML is not already
- # formatted. Since this formatter does not alter whitespace nodes, the
- # results of formatting already formatted XML will be odd.
- class Transitive < Default
- def initialize( indentation=2, ie_hack=false )
- @indentation = indentation
- @level = 0
- @ie_hack = ie_hack
- end
-
- protected
- def write_element( node, output )
- output << "<#{node.expanded_name}"
-
- node.attributes.each_attribute do |attr|
- output << " "
- attr.write( output )
- end unless node.attributes.empty?
-
- output << "\n"
- output << ' '*@level
- if node.children.empty?
- output << " " if @ie_hack
- output << "/"
- else
- output << ">"
- # If compact and all children are text, and if the formatted output
- # is less than the specified width, then try to print everything on
- # one line
- @level += @indentation
- node.children.each { |child|
- write( child, output )
- }
- @level -= @indentation
- output << "</#{node.expanded_name}"
- output << "\n"
- output << ' '*@level
- end
- output << ">"
- end
-
- def write_text( node, output )
- output << node.to_s()
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/functions.rb b/ruby_1_9_3/lib/rexml/functions.rb
deleted file mode 100644
index 20c8961aee..0000000000
--- a/ruby_1_9_3/lib/rexml/functions.rb
+++ /dev/null
@@ -1,394 +0,0 @@
-module REXML
- # If you add a method, keep in mind two things:
- # (1) the first argument will always be a list of nodes from which to
- # filter. In the case of context methods (such as position), the function
- # should return an array with a value for each child in the array.
- # (2) all method calls from XML will have "-" replaced with "_".
- # Therefore, in XML, "local-name()" is identical (and actually becomes)
- # "local_name()"
- module Functions
- @@context = nil
- @@namespace_context = {}
- @@variables = {}
-
- def Functions::namespace_context=(x) ; @@namespace_context=x ; end
- def Functions::variables=(x) ; @@variables=x ; end
- def Functions::namespace_context ; @@namespace_context ; end
- def Functions::variables ; @@variables ; end
-
- def Functions::context=(value); @@context = value; end
-
- def Functions::text( )
- if @@context[:node].node_type == :element
- return @@context[:node].find_all{|n| n.node_type == :text}.collect{|n| n.value}
- elsif @@context[:node].node_type == :text
- return @@context[:node].value
- else
- return false
- end
- end
-
- # Returns the last node of the given list of nodes.
- def Functions::last( )
- @@context[:size]
- end
-
- def Functions::position( )
- @@context[:index]
- end
-
- # Returns the size of the given list of nodes.
- def Functions::count( node_set )
- node_set.size
- end
-
- # Since REXML is non-validating, this method is not implemented as it
- # requires a DTD
- def Functions::id( object )
- end
-
- # UNTESTED
- def Functions::local_name( node_set=nil )
- get_namespace( node_set ) do |node|
- return node.local_name
- end
- end
-
- def Functions::namespace_uri( node_set=nil )
- get_namespace( node_set ) {|node| node.namespace}
- end
-
- def Functions::name( node_set=nil )
- get_namespace( node_set ) do |node|
- node.expanded_name
- end
- end
-
- # Helper method.
- def Functions::get_namespace( node_set = nil )
- if node_set == nil
- yield @@context[:node] if defined? @@context[:node].namespace
- else
- if node_set.respond_to? :each
- node_set.each { |node| yield node if defined? node.namespace }
- elsif node_set.respond_to? :namespace
- yield node_set
- end
- end
- end
-
- # A node-set is converted to a string by returning the string-value of the
- # node in the node-set that is first in document order. If the node-set is
- # empty, an empty string is returned.
- #
- # A number is converted to a string as follows
- #
- # NaN is converted to the string NaN
- #
- # positive zero is converted to the string 0
- #
- # negative zero is converted to the string 0
- #
- # positive infinity is converted to the string Infinity
- #
- # negative infinity is converted to the string -Infinity
- #
- # if the number is an integer, the number is represented in decimal form
- # as a Number with no decimal point and no leading zeros, preceded by a
- # minus sign (-) if the number is negative
- #
- # otherwise, the number is represented in decimal form as a Number
- # including a decimal point with at least one digit before the decimal
- # point and at least one digit after the decimal point, preceded by a
- # minus sign (-) if the number is negative; there must be no leading zeros
- # before the decimal point apart possibly from the one required digit
- # immediately before the decimal point; beyond the one required digit
- # after the decimal point there must be as many, but only as many, more
- # digits as are needed to uniquely distinguish the number from all other
- # IEEE 754 numeric values.
- #
- # The boolean false value is converted to the string false. The boolean
- # true value is converted to the string true.
- #
- # An object of a type other than the four basic types is converted to a
- # string in a way that is dependent on that type.
- def Functions::string( object=nil )
- #object = @context unless object
- if object.instance_of? Array
- string( object[0] )
- elsif defined? object.node_type
- if object.node_type == :attribute
- object.value
- elsif object.node_type == :element || object.node_type == :document
- string_value(object)
- else
- object.to_s
- end
- elsif object.nil?
- return ""
- else
- object.to_s
- end
- end
-
- # A node-set is converted to a string by
- # returning the concatenation of the string-value
- # of each of the children of the node in the
- # node-set that is first in document order.
- # If the node-set is empty, an empty string is returned.
- def Functions::string_value( o )
- rv = ""
- o.children.each { |e|
- if e.node_type == :text
- rv << e.to_s
- elsif e.node_type == :element
- rv << string_value( e )
- end
- }
- rv
- end
-
- # UNTESTED
- def Functions::concat( *objects )
- objects.join
- end
-
- # Fixed by Mike Stok
- def Functions::starts_with( string, test )
- string(string).index(string(test)) == 0
- end
-
- # Fixed by Mike Stok
- def Functions::contains( string, test )
- string(string).include?(string(test))
- end
-
- # Kouhei fixed this
- def Functions::substring_before( string, test )
- ruby_string = string(string)
- ruby_index = ruby_string.index(string(test))
- if ruby_index.nil?
- ""
- else
- ruby_string[ 0...ruby_index ]
- end
- end
-
- # Kouhei fixed this too
- def Functions::substring_after( string, test )
- ruby_string = string(string)
- return $1 if ruby_string =~ /#{test}(.*)/
- ""
- end
-
- # Take equal portions of Mike Stok and Sean Russell; mix
- # vigorously, and pour into a tall, chilled glass. Serves 10,000.
- def Functions::substring( string, start, length=nil )
- ruby_string = string(string)
- ruby_length = if length.nil?
- ruby_string.length.to_f
- else
- number(length)
- end
- ruby_start = number(start)
-
- # Handle the special cases
- return '' if (
- ruby_length.nan? or
- ruby_start.nan? or
- ruby_start.infinite?
- )
-
- infinite_length = ruby_length.infinite? == 1
- ruby_length = ruby_string.length if infinite_length
-
- # Now, get the bounds. The XPath bounds are 1..length; the ruby bounds
- # are 0..length. Therefore, we have to offset the bounds by one.
- ruby_start = ruby_start.round - 1
- ruby_length = ruby_length.round
-
- if ruby_start < 0
- ruby_length += ruby_start unless infinite_length
- ruby_start = 0
- end
- return '' if ruby_length <= 0
- ruby_string[ruby_start,ruby_length]
- end
-
- # UNTESTED
- def Functions::string_length( string )
- string(string).length
- end
-
- # UNTESTED
- def Functions::normalize_space( string=nil )
- string = string(@@context[:node]) if string.nil?
- if string.kind_of? Array
- string.collect{|x| string.to_s.strip.gsub(/\s+/um, ' ') if string}
- else
- string.to_s.strip.gsub(/\s+/um, ' ')
- end
- end
-
- # This is entirely Mike Stok's beast
- def Functions::translate( string, tr1, tr2 )
- from = string(tr1)
- to = string(tr2)
-
- # the map is our translation table.
- #
- # if a character occurs more than once in the
- # from string then we ignore the second &
- # subsequent mappings
- #
- # if a character maps to nil then we delete it
- # in the output. This happens if the from
- # string is longer than the to string
- #
- # there's nothing about - or ^ being special in
- # http://www.w3.org/TR/xpath#function-translate
- # so we don't build ranges or negated classes
-
- map = Hash.new
- 0.upto(from.length - 1) { |pos|
- from_char = from[pos]
- unless map.has_key? from_char
- map[from_char] =
- if pos < to.length
- to[pos]
- else
- nil
- end
- end
- }
-
- if ''.respond_to? :chars
- string(string).chars.collect { |c|
- if map.has_key? c then map[c] else c end
- }.compact.join
- else
- string(string).unpack('U*').collect { |c|
- if map.has_key? c then map[c] else c end
- }.compact.pack('U*')
- end
- end
-
- # UNTESTED
- def Functions::boolean( object=nil )
- if object.kind_of? String
- if object =~ /\d+/u
- return object.to_f != 0
- else
- return object.size > 0
- end
- elsif object.kind_of? Array
- object = object.find{|x| x and true}
- end
- return object ? true : false
- end
-
- # UNTESTED
- def Functions::not( object )
- not boolean( object )
- end
-
- # UNTESTED
- def Functions::true( )
- true
- end
-
- # UNTESTED
- def Functions::false( )
- false
- end
-
- # UNTESTED
- def Functions::lang( language )
- lang = false
- node = @@context[:node]
- attr = nil
- until node.nil?
- if node.node_type == :element
- attr = node.attributes["xml:lang"]
- unless attr.nil?
- lang = compare_language(string(language), attr)
- break
- else
- end
- end
- node = node.parent
- end
- lang
- end
-
- def Functions::compare_language lang1, lang2
- lang2.downcase.index(lang1.downcase) == 0
- end
-
- # a string that consists of optional whitespace followed by an optional
- # minus sign followed by a Number followed by whitespace is converted to
- # the IEEE 754 number that is nearest (according to the IEEE 754
- # round-to-nearest rule) to the mathematical value represented by the
- # string; any other string is converted to NaN
- #
- # boolean true is converted to 1; boolean false is converted to 0
- #
- # a node-set is first converted to a string as if by a call to the string
- # function and then converted in the same way as a string argument
- #
- # an object of a type other than the four basic types is converted to a
- # number in a way that is dependent on that type
- def Functions::number( object=nil )
- object = @@context[:node] unless object
- case object
- when true
- Float(1)
- when false
- Float(0)
- when Array
- number(string( object ))
- when Numeric
- object.to_f
- else
- str = string( object )
- # If XPath ever gets scientific notation...
- #if str =~ /^\s*-?(\d*\.?\d+|\d+\.)([Ee]\d*)?\s*$/
- if str =~ /^\s*-?(\d*\.?\d+|\d+\.)\s*$/
- str.to_f
- else
- (0.0 / 0.0)
- end
- end
- end
-
- def Functions::sum( nodes )
- nodes = [nodes] unless nodes.kind_of? Array
- nodes.inject(0) { |r,n| r += number(string(n)) }
- end
-
- def Functions::floor( number )
- number(number).floor
- end
-
- def Functions::ceiling( number )
- number(number).ceil
- end
-
- def Functions::round( number )
- begin
- number(number).round
- rescue FloatDomainError
- number(number)
- end
- end
-
- def Functions::processing_instruction( node )
- node.node_type == :processing_instruction
- end
-
- def Functions::method_missing( id )
- puts "METHOD MISSING #{id.id2name}"
- XPath.match( @@context[:node], id.id2name )
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/instruction.rb b/ruby_1_9_3/lib/rexml/instruction.rb
deleted file mode 100644
index f8b734a5b5..0000000000
--- a/ruby_1_9_3/lib/rexml/instruction.rb
+++ /dev/null
@@ -1,70 +0,0 @@
-require "rexml/child"
-require "rexml/source"
-
-module REXML
- # Represents an XML Instruction; IE, <? ... ?>
- # TODO: Add parent arg (3rd arg) to constructor
- class Instruction < Child
- START = '<\?'
- STOP = '\?>'
-
- # target is the "name" of the Instruction; IE, the "tag" in <?tag ...?>
- # content is everything else.
- attr_accessor :target, :content
-
- # Constructs a new Instruction
- # @param target can be one of a number of things. If String, then
- # the target of this instruction is set to this. If an Instruction,
- # then the Instruction is shallowly cloned (target and content are
- # copied). If a Source, then the source is scanned and parsed for
- # an Instruction declaration.
- # @param content Must be either a String, or a Parent. Can only
- # be a Parent if the target argument is a Source. Otherwise, this
- # String is set as the content of this instruction.
- def initialize(target, content=nil)
- if target.kind_of? String
- super()
- @target = target
- @content = content
- elsif target.kind_of? Instruction
- super(content)
- @target = target.target
- @content = target.content
- end
- @content.strip! if @content
- end
-
- def clone
- Instruction.new self
- end
-
- # == DEPRECATED
- # See the rexml/formatters package
- #
- def write writer, indent=-1, transitive=false, ie_hack=false
- Kernel.warn( "#{self.class.name}.write is deprecated" )
- indent(writer, indent)
- writer << START.sub(/\\/u, '')
- writer << @target
- writer << ' '
- writer << @content
- writer << STOP.sub(/\\/u, '')
- end
-
- # @return true if other is an Instruction, and the content and target
- # of the other matches the target and content of this object.
- def ==( other )
- other.kind_of? Instruction and
- other.target == @target and
- other.content == @content
- end
-
- def node_type
- :processing_instruction
- end
-
- def inspect
- "<?p-i #{target} ...?>"
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/light/node.rb b/ruby_1_9_3/lib/rexml/light/node.rb
deleted file mode 100644
index 0a896c83dc..0000000000
--- a/ruby_1_9_3/lib/rexml/light/node.rb
+++ /dev/null
@@ -1,195 +0,0 @@
-require 'rexml/xmltokens'
-
-# [ :element, parent, name, attributes, children* ]
- # a = Node.new
- # a << "B" # => <a>B</a>
- # a.b # => <a>B<b/></a>
- # a.b[1] # => <a>B<b/><b/><a>
- # a.b[1]["x"] = "y" # => <a>B<b/><b x="y"/></a>
- # a.b[0].c # => <a>B<b><c/></b><b x="y"/></a>
- # a.b.c << "D" # => <a>B<b><c>D</c></b><b x="y"/></a>
-module REXML
- module Light
- # Represents a tagged XML element. Elements are characterized by
- # having children, attributes, and names, and can themselves be
- # children.
- class Node
- NAMESPLIT = /^(?:(#{XMLTokens::NCNAME_STR}):)?(#{XMLTokens::NCNAME_STR})/u
- PARENTS = [ :element, :document, :doctype ]
- # Create a new element.
- def initialize node=nil
- @node = node
- if node.kind_of? String
- node = [ :text, node ]
- elsif node.nil?
- node = [ :document, nil, nil ]
- elsif node[0] == :start_element
- node[0] = :element
- elsif node[0] == :start_doctype
- node[0] = :doctype
- elsif node[0] == :start_document
- node[0] = :document
- end
- end
-
- def size
- if PARENTS.include? @node[0]
- @node[-1].size
- else
- 0
- end
- end
-
- def each( &block )
- size.times { |x| yield( at(x+4) ) }
- end
-
- def name
- at(2)
- end
-
- def name=( name_str, ns=nil )
- pfx = ''
- pfx = "#{prefix(ns)}:" if ns
- _old_put(2, "#{pfx}#{name_str}")
- end
-
- def parent=( node )
- _old_put(1,node)
- end
-
- def local_name
- namesplit
- @name
- end
-
- def local_name=( name_str )
- _old_put( 1, "#@prefix:#{name_str}" )
- end
-
- def prefix( namespace=nil )
- prefix_of( self, namespace )
- end
-
- def namespace( prefix=prefix() )
- namespace_of( self, prefix )
- end
-
- def namespace=( namespace )
- @prefix = prefix( namespace )
- pfx = ''
- pfx = "#@prefix:" if @prefix.size > 0
- _old_put(1, "#{pfx}#@name")
- end
-
- def []( reference, ns=nil )
- if reference.kind_of? String
- pfx = ''
- pfx = "#{prefix(ns)}:" if ns
- at(3)["#{pfx}#{reference}"]
- elsif reference.kind_of? Range
- _old_get( Range.new(4+reference.begin, reference.end, reference.exclude_end?) )
- else
- _old_get( 4+reference )
- end
- end
-
- def =~( path )
- XPath.match( self, path )
- end
-
- # Doesn't handle namespaces yet
- def []=( reference, ns, value=nil )
- if reference.kind_of? String
- value = ns unless value
- at( 3 )[reference] = value
- elsif reference.kind_of? Range
- _old_put( Range.new(3+reference.begin, reference.end, reference.exclude_end?), ns )
- else
- if value
- _old_put( 4+reference, ns, value )
- else
- _old_put( 4+reference, ns )
- end
- end
- end
-
- # Append a child to this element, optionally under a provided namespace.
- # The namespace argument is ignored if the element argument is an Element
- # object. Otherwise, the element argument is a string, the namespace (if
- # provided) is the namespace the element is created in.
- def << element
- if node_type() == :text
- at(-1) << element
- else
- newnode = Node.new( element )
- newnode.parent = self
- self.push( newnode )
- end
- at(-1)
- end
-
- def node_type
- _old_get(0)
- end
-
- def text=( foo )
- replace = at(4).kind_of?(String)? 1 : 0
- self._old_put(4,replace, normalizefoo)
- end
-
- def root
- context = self
- context = context.at(1) while context.at(1)
- end
-
- def has_name?( name, namespace = '' )
- at(3) == name and namespace() == namespace
- end
-
- def children
- self
- end
-
- def parent
- at(1)
- end
-
- def to_s
-
- end
-
- private
-
- def namesplit
- return if @name.defined?
- at(2) =~ NAMESPLIT
- @prefix = '' || $1
- @name = $2
- end
-
- def namespace_of( node, prefix=nil )
- if not prefix
- name = at(2)
- name =~ NAMESPLIT
- prefix = $1
- end
- to_find = 'xmlns'
- to_find = "xmlns:#{prefix}" if not prefix.nil?
- ns = at(3)[ to_find ]
- ns ? ns : namespace_of( @node[0], prefix )
- end
-
- def prefix_of( node, namespace=nil )
- if not namespace
- name = node.name
- name =~ NAMESPLIT
- $1
- else
- ns = at(3).find { |k,v| v == namespace }
- ns ? ns : prefix_of( node.parent, namespace )
- end
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/namespace.rb b/ruby_1_9_3/lib/rexml/namespace.rb
deleted file mode 100644
index aeb339ee83..0000000000
--- a/ruby_1_9_3/lib/rexml/namespace.rb
+++ /dev/null
@@ -1,47 +0,0 @@
-require 'rexml/xmltokens'
-
-module REXML
- # Adds named attributes to an object.
- module Namespace
- # The name of the object, valid if set
- attr_reader :name, :expanded_name
- # The expanded name of the object, valid if name is set
- attr_accessor :prefix
- include XMLTokens
- NAMESPLIT = /^(?:(#{NCNAME_STR}):)?(#{NCNAME_STR})/u
-
- # Sets the name and the expanded name
- def name=( name )
- @expanded_name = name
- name =~ NAMESPLIT
- if $1
- @prefix = $1
- else
- @prefix = ""
- @namespace = ""
- end
- @name = $2
- end
-
- # Compares names optionally WITH namespaces
- def has_name?( other, ns=nil )
- if ns
- return (namespace() == ns and name() == other)
- elsif other.include? ":"
- return fully_expanded_name == other
- else
- return name == other
- end
- end
-
- alias :local_name :name
-
- # Fully expand the name, even if the prefix wasn't specified in the
- # source file.
- def fully_expanded_name
- ns = prefix
- return "#{ns}:#@name" if ns.size > 0
- return @name
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/node.rb b/ruby_1_9_3/lib/rexml/node.rb
deleted file mode 100644
index cab6e9fddb..0000000000
--- a/ruby_1_9_3/lib/rexml/node.rb
+++ /dev/null
@@ -1,75 +0,0 @@
-require "rexml/parseexception"
-require "rexml/formatters/pretty"
-require "rexml/formatters/default"
-
-module REXML
- # Represents a node in the tree. Nodes are never encountered except as
- # superclasses of other objects. Nodes have siblings.
- module Node
- # @return the next sibling (nil if unset)
- def next_sibling_node
- return nil if @parent.nil?
- @parent[ @parent.index(self) + 1 ]
- end
-
- # @return the previous sibling (nil if unset)
- def previous_sibling_node
- return nil if @parent.nil?
- ind = @parent.index(self)
- return nil if ind == 0
- @parent[ ind - 1 ]
- end
-
- # indent::
- # *DEPRECATED* This parameter is now ignored. See the formatters in the
- # REXML::Formatters package for changing the output style.
- def to_s indent=nil
- unless indent.nil?
- Kernel.warn( "#{self.class.name}.to_s(indent) parameter is deprecated" )
- f = REXML::Formatters::Pretty.new( indent )
- f.write( self, rv = "" )
- else
- f = REXML::Formatters::Default.new
- f.write( self, rv = "" )
- end
- return rv
- end
-
- def indent to, ind
- if @parent and @parent.context and not @parent.context[:indentstyle].nil? then
- indentstyle = @parent.context[:indentstyle]
- else
- indentstyle = ' '
- end
- to << indentstyle*ind unless ind<1
- end
-
- def parent?
- false;
- end
-
-
- # Visit all subnodes of +self+ recursively
- def each_recursive(&block) # :yields: node
- self.elements.each {|node|
- block.call(node)
- node.each_recursive(&block)
- }
- end
-
- # Find (and return) first subnode (recursively) for which the block
- # evaluates to true. Returns +nil+ if none was found.
- def find_first_recursive(&block) # :yields: node
- each_recursive {|node|
- return node if block.call(node)
- }
- return nil
- end
-
- # Returns the position that +self+ holds in its parent's array, indexed
- # from 1.
- def index_in_parent
- parent.index(self)+1
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/output.rb b/ruby_1_9_3/lib/rexml/output.rb
deleted file mode 100644
index 50333ba177..0000000000
--- a/ruby_1_9_3/lib/rexml/output.rb
+++ /dev/null
@@ -1,24 +0,0 @@
-require 'rexml/encoding'
-
-module REXML
- class Output
- include Encoding
-
- attr_reader :encoding
-
- def initialize real_IO, encd="iso-8859-1"
- @output = real_IO
- self.encoding = encd
-
- @to_utf = encd != 'UTF-8'
- end
-
- def <<( content )
- @output << (@to_utf ? self.encode(content) : content)
- end
-
- def to_s
- "Output[#{encoding}]"
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/parent.rb b/ruby_1_9_3/lib/rexml/parent.rb
deleted file mode 100644
index 0a9f805109..0000000000
--- a/ruby_1_9_3/lib/rexml/parent.rb
+++ /dev/null
@@ -1,167 +0,0 @@
-require "rexml/child"
-
-module REXML
- # A parent has children, and has methods for accessing them. The Parent
- # class is never encountered except as the superclass for some other
- # object.
- class Parent < Child
- include Enumerable
-
- # Constructor
- # @param parent if supplied, will be set as the parent of this object
- def initialize parent=nil
- super(parent)
- @children = []
- end
-
- def add( object )
- #puts "PARENT GOTS #{size} CHILDREN"
- object.parent = self
- @children << object
- #puts "PARENT NOW GOTS #{size} CHILDREN"
- object
- end
-
- alias :push :add
- alias :<< :push
-
- def unshift( object )
- object.parent = self
- @children.unshift object
- end
-
- def delete( object )
- found = false
- @children.delete_if {|c| c.equal?(object) and found = true }
- object.parent = nil if found
- found ? object : nil
- end
-
- def each(&block)
- @children.each(&block)
- end
-
- def delete_if( &block )
- @children.delete_if(&block)
- end
-
- def delete_at( index )
- @children.delete_at index
- end
-
- def each_index( &block )
- @children.each_index(&block)
- end
-
- # Fetches a child at a given index
- # @param index the Integer index of the child to fetch
- def []( index )
- @children[index]
- end
-
- alias :each_child :each
-
-
-
- # Set an index entry. See Array.[]=
- # @param index the index of the element to set
- # @param opt either the object to set, or an Integer length
- # @param child if opt is an Integer, this is the child to set
- # @return the parent (self)
- def []=( *args )
- args[-1].parent = self
- @children[*args[0..-2]] = args[-1]
- end
-
- # Inserts an child before another child
- # @param child1 this is either an xpath or an Element. If an Element,
- # child2 will be inserted before child1 in the child list of the parent.
- # If an xpath, child2 will be inserted before the first child to match
- # the xpath.
- # @param child2 the child to insert
- # @return the parent (self)
- def insert_before( child1, child2 )
- if child1.kind_of? String
- child1 = XPath.first( self, child1 )
- child1.parent.insert_before child1, child2
- else
- ind = index(child1)
- child2.parent.delete(child2) if child2.parent
- @children[ind,0] = child2
- child2.parent = self
- end
- self
- end
-
- # Inserts an child after another child
- # @param child1 this is either an xpath or an Element. If an Element,
- # child2 will be inserted after child1 in the child list of the parent.
- # If an xpath, child2 will be inserted after the first child to match
- # the xpath.
- # @param child2 the child to insert
- # @return the parent (self)
- def insert_after( child1, child2 )
- if child1.kind_of? String
- child1 = XPath.first( self, child1 )
- child1.parent.insert_after child1, child2
- else
- ind = index(child1)+1
- child2.parent.delete(child2) if child2.parent
- @children[ind,0] = child2
- child2.parent = self
- end
- self
- end
-
- def to_a
- @children.dup
- end
-
- # Fetches the index of a given child
- # @param child the child to get the index of
- # @return the index of the child, or nil if the object is not a child
- # of this parent.
- def index( child )
- count = -1
- @children.find { |i| count += 1 ; i.hash == child.hash }
- count
- end
-
- # @return the number of children of this parent
- def size
- @children.size
- end
-
- alias :length :size
-
- # Replaces one child with another, making sure the nodelist is correct
- # @param to_replace the child to replace (must be a Child)
- # @param replacement the child to insert into the nodelist (must be a
- # Child)
- def replace_child( to_replace, replacement )
- @children.map! {|c| c.equal?( to_replace ) ? replacement : c }
- to_replace.parent = nil
- replacement.parent = self
- end
-
- # Deeply clones this object. This creates a complete duplicate of this
- # Parent, including all descendants.
- def deep_clone
- cl = clone()
- each do |child|
- if child.kind_of? Parent
- cl << child.deep_clone
- else
- cl << child.clone
- end
- end
- cl
- end
-
- alias :children :to_a
-
- def parent?
- true
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/parseexception.rb b/ruby_1_9_3/lib/rexml/parseexception.rb
deleted file mode 100644
index 0c4d55abda..0000000000
--- a/ruby_1_9_3/lib/rexml/parseexception.rb
+++ /dev/null
@@ -1,51 +0,0 @@
-module REXML
- class ParseException < RuntimeError
- attr_accessor :source, :parser, :continued_exception
-
- def initialize( message, source=nil, parser=nil, exception=nil )
- super(message)
- @source = source
- @parser = parser
- @continued_exception = exception
- end
-
- def to_s
- # Quote the original exception, if there was one
- if @continued_exception
- err = @continued_exception.inspect
- err << "\n"
- err << @continued_exception.backtrace.join("\n")
- err << "\n...\n"
- else
- err = ""
- end
-
- # Get the stack trace and error message
- err << super
-
- # Add contextual information
- if @source
- err << "\nLine: #{line}\n"
- err << "Position: #{position}\n"
- err << "Last 80 unconsumed characters:\n"
- err << @source.buffer[0..80].force_encoding("ASCII-8BIT").gsub(/\n/, ' ')
- end
-
- err
- end
-
- def position
- @source.current_line[0] if @source and defined? @source.current_line and
- @source.current_line
- end
-
- def line
- @source.current_line[2] if @source and defined? @source.current_line and
- @source.current_line
- end
-
- def context
- @source.current_line
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/parsers/baseparser.rb b/ruby_1_9_3/lib/rexml/parsers/baseparser.rb
deleted file mode 100644
index 2df26b82f9..0000000000
--- a/ruby_1_9_3/lib/rexml/parsers/baseparser.rb
+++ /dev/null
@@ -1,518 +0,0 @@
-require 'rexml/parseexception'
-require 'rexml/undefinednamespaceexception'
-require 'rexml/source'
-require 'set'
-
-module REXML
- module Parsers
- # = Using the Pull Parser
- # <em>This API is experimental, and subject to change.</em>
- # parser = PullParser.new( "<a>text<b att='val'/>txet</a>" )
- # while parser.has_next?
- # res = parser.next
- # puts res[1]['att'] if res.start_tag? and res[0] == 'b'
- # end
- # See the PullEvent class for information on the content of the results.
- # The data is identical to the arguments passed for the various events to
- # the StreamListener API.
- #
- # Notice that:
- # parser = PullParser.new( "<a>BAD DOCUMENT" )
- # while parser.has_next?
- # res = parser.next
- # raise res[1] if res.error?
- # end
- #
- # Nat Price gave me some good ideas for the API.
- class BaseParser
- LETTER = '[:alpha:]'
- DIGIT = '[:digit:]'
-
- COMBININGCHAR = '' # TODO
- EXTENDER = '' # TODO
-
- NCNAME_STR= "[#{LETTER}_:][-[:alnum:]._:#{COMBININGCHAR}#{EXTENDER}]*"
- NAME_STR= "(?:(#{NCNAME_STR}):)?(#{NCNAME_STR})"
- UNAME_STR= "(?:#{NCNAME_STR}:)?#{NCNAME_STR}"
-
- NAMECHAR = '[\-\w\.:]'
- NAME = "([\\w:]#{NAMECHAR}*)"
- NMTOKEN = "(?:#{NAMECHAR})+"
- NMTOKENS = "#{NMTOKEN}(\\s+#{NMTOKEN})*"
- REFERENCE = "&(?:#{NAME};|#\\d+;|#x[0-9a-fA-F]+;)"
- REFERENCE_RE = /#{REFERENCE}/
-
- DOCTYPE_START = /\A\s*<!DOCTYPE\s/um
- DOCTYPE_PATTERN = /\s*<!DOCTYPE\s+(.*?)(\[|>)/um
- ATTRIBUTE_PATTERN = /\s*(#{NAME_STR})\s*=\s*(["'])(.*?)\4/um
- COMMENT_START = /\A<!--/u
- COMMENT_PATTERN = /<!--(.*?)-->/um
- CDATA_START = /\A<!\[CDATA\[/u
- CDATA_END = /^\s*\]\s*>/um
- CDATA_PATTERN = /<!\[CDATA\[(.*?)\]\]>/um
- XMLDECL_START = /\A<\?xml\s/u;
- XMLDECL_PATTERN = /<\?xml\s+(.*?)\?>/um
- INSTRUCTION_START = /\A<\?/u
- INSTRUCTION_PATTERN = /<\?(.*?)(\s+.*?)?\?>/um
- TAG_MATCH = /^<((?>#{NAME_STR}))\s*((?>\s+#{UNAME_STR}\s*=\s*(["']).*?\5)*)\s*(\/)?>/um
- CLOSE_MATCH = /^\s*<\/(#{NAME_STR})\s*>/um
-
- VERSION = /\bversion\s*=\s*["'](.*?)['"]/um
- ENCODING = /\bencoding\s*=\s*["'](.*?)['"]/um
- STANDALONE = /\bstandalone\s*=\s*["'](.*?)['"]/um
-
- ENTITY_START = /^\s*<!ENTITY/
- IDENTITY = /^([!\*\w\-]+)(\s+#{NCNAME_STR})?(\s+["'](.*?)['"])?(\s+['"](.*?)["'])?/u
- ELEMENTDECL_START = /^\s*<!ELEMENT/um
- ELEMENTDECL_PATTERN = /^\s*(<!ELEMENT.*?)>/um
- SYSTEMENTITY = /^\s*(%.*?;)\s*$/um
- ENUMERATION = "\\(\\s*#{NMTOKEN}(?:\\s*\\|\\s*#{NMTOKEN})*\\s*\\)"
- NOTATIONTYPE = "NOTATION\\s+\\(\\s*#{NAME}(?:\\s*\\|\\s*#{NAME})*\\s*\\)"
- ENUMERATEDTYPE = "(?:(?:#{NOTATIONTYPE})|(?:#{ENUMERATION}))"
- ATTTYPE = "(CDATA|ID|IDREF|IDREFS|ENTITY|ENTITIES|NMTOKEN|NMTOKENS|#{ENUMERATEDTYPE})"
- ATTVALUE = "(?:\"((?:[^<&\"]|#{REFERENCE})*)\")|(?:'((?:[^<&']|#{REFERENCE})*)')"
- DEFAULTDECL = "(#REQUIRED|#IMPLIED|(?:(#FIXED\\s+)?#{ATTVALUE}))"
- ATTDEF = "\\s+#{NAME}\\s+#{ATTTYPE}\\s+#{DEFAULTDECL}"
- ATTDEF_RE = /#{ATTDEF}/
- ATTLISTDECL_START = /^\s*<!ATTLIST/um
- ATTLISTDECL_PATTERN = /^\s*<!ATTLIST\s+#{NAME}(?:#{ATTDEF})*\s*>/um
- NOTATIONDECL_START = /^\s*<!NOTATION/um
- PUBLIC = /^\s*<!NOTATION\s+(\w[\-\w]*)\s+(PUBLIC)\s+(["'])(.*?)\3(?:\s+(["'])(.*?)\5)?\s*>/um
- SYSTEM = /^\s*<!NOTATION\s+(\w[\-\w]*)\s+(SYSTEM)\s+(["'])(.*?)\3\s*>/um
-
- TEXT_PATTERN = /\A([^<]*)/um
-
- # Entity constants
- PUBIDCHAR = "\x20\x0D\x0Aa-zA-Z0-9\\-()+,./:=?;!*@$_%#"
- SYSTEMLITERAL = %Q{((?:"[^"]*")|(?:'[^']*'))}
- PUBIDLITERAL = %Q{("[#{PUBIDCHAR}']*"|'[#{PUBIDCHAR}]*')}
- EXTERNALID = "(?:(?:(SYSTEM)\\s+#{SYSTEMLITERAL})|(?:(PUBLIC)\\s+#{PUBIDLITERAL}\\s+#{SYSTEMLITERAL}))"
- NDATADECL = "\\s+NDATA\\s+#{NAME}"
- PEREFERENCE = "%#{NAME};"
- ENTITYVALUE = %Q{((?:"(?:[^%&"]|#{PEREFERENCE}|#{REFERENCE})*")|(?:'([^%&']|#{PEREFERENCE}|#{REFERENCE})*'))}
- PEDEF = "(?:#{ENTITYVALUE}|#{EXTERNALID})"
- ENTITYDEF = "(?:#{ENTITYVALUE}|(?:#{EXTERNALID}(#{NDATADECL})?))"
- PEDECL = "<!ENTITY\\s+(%)\\s+#{NAME}\\s+#{PEDEF}\\s*>"
- GEDECL = "<!ENTITY\\s+#{NAME}\\s+#{ENTITYDEF}\\s*>"
- ENTITYDECL = /\s*(?:#{GEDECL})|(?:#{PEDECL})/um
-
- EREFERENCE = /&(?!#{NAME};)/
-
- DEFAULT_ENTITIES = {
- 'gt' => [/&gt;/, '&gt;', '>', />/],
- 'lt' => [/&lt;/, '&lt;', '<', /</],
- 'quot' => [/&quot;/, '&quot;', '"', /"/],
- "apos" => [/&apos;/, "&apos;", "'", /'/]
- }
-
-
- ######################################################################
- # These are patterns to identify common markup errors, to make the
- # error messages more informative.
- ######################################################################
- MISSING_ATTRIBUTE_QUOTES = /^<#{NAME_STR}\s+#{NAME_STR}\s*=\s*[^"']/um
-
- def initialize( source )
- self.stream = source
- @listeners = []
- end
-
- def add_listener( listener )
- @listeners << listener
- end
-
- attr_reader :source
-
- def stream=( source )
- @source = SourceFactory.create_from( source )
- @closed = nil
- @document_status = nil
- @tags = []
- @stack = []
- @entities = []
- @nsstack = []
- end
-
- def position
- if @source.respond_to? :position
- @source.position
- else
- # FIXME
- 0
- end
- end
-
- # Returns true if there are no more events
- def empty?
- return (@source.empty? and @stack.empty?)
- end
-
- # Returns true if there are more events. Synonymous with !empty?
- def has_next?
- return !(@source.empty? and @stack.empty?)
- end
-
- # Push an event back on the head of the stream. This method
- # has (theoretically) infinite depth.
- def unshift token
- @stack.unshift(token)
- end
-
- # Peek at the +depth+ event in the stack. The first element on the stack
- # is at depth 0. If +depth+ is -1, will parse to the end of the input
- # stream and return the last event, which is always :end_document.
- # Be aware that this causes the stream to be parsed up to the +depth+
- # event, so you can effectively pre-parse the entire document (pull the
- # entire thing into memory) using this method.
- def peek depth=0
- raise %Q[Illegal argument "#{depth}"] if depth < -1
- temp = []
- if depth == -1
- temp.push(pull()) until empty?
- else
- while @stack.size+temp.size < depth+1
- temp.push(pull())
- end
- end
- @stack += temp if temp.size > 0
- @stack[depth]
- end
-
- # Returns the next event. This is a +PullEvent+ object.
- def pull
- pull_event.tap do |event|
- @listeners.each do |listener|
- listener.receive event
- end
- end
- end
-
- def pull_event
- if @closed
- x, @closed = @closed, nil
- return [ :end_element, x ]
- end
- return [ :end_document ] if empty?
- return @stack.shift if @stack.size > 0
- #STDERR.puts @source.encoding
- @source.read if @source.buffer.size<2
- #STDERR.puts "BUFFER = #{@source.buffer.inspect}"
- if @document_status == nil
- #@source.consume( /^\s*/um )
- word = @source.match( /^((?:\s+)|(?:<[^>]*>))/um )
- word = word[1] unless word.nil?
- #STDERR.puts "WORD = #{word.inspect}"
- case word
- when COMMENT_START
- return [ :comment, @source.match( COMMENT_PATTERN, true )[1] ]
- when XMLDECL_START
- #STDERR.puts "XMLDECL"
- results = @source.match( XMLDECL_PATTERN, true )[1]
- version = VERSION.match( results )
- version = version[1] unless version.nil?
- encoding = ENCODING.match(results)
- encoding = encoding[1] unless encoding.nil?
- @source.encoding = encoding
- standalone = STANDALONE.match(results)
- standalone = standalone[1] unless standalone.nil?
- return [ :xmldecl, version, encoding, standalone ]
- when INSTRUCTION_START
- return [ :processing_instruction, *@source.match(INSTRUCTION_PATTERN, true)[1,2] ]
- when DOCTYPE_START
- md = @source.match( DOCTYPE_PATTERN, true )
- @nsstack.unshift(curr_ns=Set.new)
- identity = md[1]
- close = md[2]
- identity =~ IDENTITY
- name = $1
- raise REXML::ParseException.new("DOCTYPE is missing a name") if name.nil?
- pub_sys = $2.nil? ? nil : $2.strip
- long_name = $4.nil? ? nil : $4.strip
- uri = $6.nil? ? nil : $6.strip
- args = [ :start_doctype, name, pub_sys, long_name, uri ]
- if close == ">"
- @document_status = :after_doctype
- @source.read if @source.buffer.size<2
- md = @source.match(/^\s*/um, true)
- @stack << [ :end_doctype ]
- else
- @document_status = :in_doctype
- end
- return args
- when /^\s+/
- else
- @document_status = :after_doctype
- @source.read if @source.buffer.size<2
- md = @source.match(/\s*/um, true)
- if @source.encoding == "UTF-8"
- @source.buffer.force_encoding(::Encoding::UTF_8)
- end
- end
- end
- if @document_status == :in_doctype
- md = @source.match(/\s*(.*?>)/um)
- case md[1]
- when SYSTEMENTITY
- match = @source.match( SYSTEMENTITY, true )[1]
- return [ :externalentity, match ]
-
- when ELEMENTDECL_START
- return [ :elementdecl, @source.match( ELEMENTDECL_PATTERN, true )[1] ]
-
- when ENTITY_START
- match = @source.match( ENTITYDECL, true ).to_a.compact
- match[0] = :entitydecl
- ref = false
- if match[1] == '%'
- ref = true
- match.delete_at 1
- end
- # Now we have to sort out what kind of entity reference this is
- if match[2] == 'SYSTEM'
- # External reference
- match[3] = match[3][1..-2] # PUBID
- match.delete_at(4) if match.size > 4 # Chop out NDATA decl
- # match is [ :entity, name, SYSTEM, pubid(, ndata)? ]
- elsif match[2] == 'PUBLIC'
- # External reference
- match[3] = match[3][1..-2] # PUBID
- match[4] = match[4][1..-2] # HREF
- # match is [ :entity, name, PUBLIC, pubid, href ]
- else
- match[2] = match[2][1..-2]
- match.pop if match.size == 4
- # match is [ :entity, name, value ]
- end
- match << '%' if ref
- return match
- when ATTLISTDECL_START
- md = @source.match( ATTLISTDECL_PATTERN, true )
- raise REXML::ParseException.new( "Bad ATTLIST declaration!", @source ) if md.nil?
- element = md[1]
- contents = md[0]
-
- pairs = {}
- values = md[0].scan( ATTDEF_RE )
- values.each do |attdef|
- unless attdef[3] == "#IMPLIED"
- attdef.compact!
- val = attdef[3]
- val = attdef[4] if val == "#FIXED "
- pairs[attdef[0]] = val
- if attdef[0] =~ /^xmlns:(.*)/
- @nsstack[0] << $1
- end
- end
- end
- return [ :attlistdecl, element, pairs, contents ]
- when NOTATIONDECL_START
- md = nil
- if @source.match( PUBLIC )
- md = @source.match( PUBLIC, true )
- vals = [md[1],md[2],md[4],md[6]]
- elsif @source.match( SYSTEM )
- md = @source.match( SYSTEM, true )
- vals = [md[1],md[2],nil,md[4]]
- else
- raise REXML::ParseException.new( "error parsing notation: no matching pattern", @source )
- end
- return [ :notationdecl, *vals ]
- when CDATA_END
- @document_status = :after_doctype
- @source.match( CDATA_END, true )
- return [ :end_doctype ]
- end
- end
- begin
- if @source.buffer[0] == ?<
- if @source.buffer[1] == ?/
- @nsstack.shift
- last_tag = @tags.pop
- #md = @source.match_to_consume( '>', CLOSE_MATCH)
- md = @source.match( CLOSE_MATCH, true )
- raise REXML::ParseException.new( "Missing end tag for "+
- "'#{last_tag}' (got \"#{md[1]}\")",
- @source) unless last_tag == md[1]
- return [ :end_element, last_tag ]
- elsif @source.buffer[1] == ?!
- md = @source.match(/\A(\s*[^>]*>)/um)
- #STDERR.puts "SOURCE BUFFER = #{source.buffer}, #{source.buffer.size}"
- raise REXML::ParseException.new("Malformed node", @source) unless md
- if md[0][2] == ?-
- md = @source.match( COMMENT_PATTERN, true )
-
- case md[1]
- when /--/, /-\z/
- raise REXML::ParseException.new("Malformed comment", @source)
- end
-
- return [ :comment, md[1] ] if md
- else
- md = @source.match( CDATA_PATTERN, true )
- return [ :cdata, md[1] ] if md
- end
- raise REXML::ParseException.new( "Declarations can only occur "+
- "in the doctype declaration.", @source)
- elsif @source.buffer[1] == ??
- md = @source.match( INSTRUCTION_PATTERN, true )
- return [ :processing_instruction, md[1], md[2] ] if md
- raise REXML::ParseException.new( "Bad instruction declaration",
- @source)
- else
- # Get the next tag
- md = @source.match(TAG_MATCH, true)
- unless md
- # Check for missing attribute quotes
- raise REXML::ParseException.new("missing attribute quote", @source) if @source.match(MISSING_ATTRIBUTE_QUOTES )
- raise REXML::ParseException.new("malformed XML: missing tag start", @source)
- end
- attributes = {}
- prefixes = Set.new
- prefixes << md[2] if md[2]
- @nsstack.unshift(curr_ns=Set.new)
- if md[4].size > 0
- attrs = md[4].scan( ATTRIBUTE_PATTERN )
- raise REXML::ParseException.new( "error parsing attributes: [#{attrs.join ', '}], excess = \"#$'\"", @source) if $' and $'.strip.size > 0
- attrs.each { |a,b,c,d,e|
- if b == "xmlns"
- if c == "xml"
- if e != "http://www.w3.org/XML/1998/namespace"
- msg = "The 'xml' prefix must not be bound to any other namespace "+
- "(http://www.w3.org/TR/REC-xml-names/#ns-decl)"
- raise REXML::ParseException.new( msg, @source, self )
- end
- elsif c == "xmlns"
- msg = "The 'xmlns' prefix must not be declared "+
- "(http://www.w3.org/TR/REC-xml-names/#ns-decl)"
- raise REXML::ParseException.new( msg, @source, self)
- end
- curr_ns << c
- elsif b
- prefixes << b unless b == "xml"
- end
-
- if attributes.has_key? a
- msg = "Duplicate attribute #{a.inspect}"
- raise REXML::ParseException.new( msg, @source, self)
- end
-
- attributes[a] = e
- }
- end
-
- # Verify that all of the prefixes have been defined
- for prefix in prefixes
- unless @nsstack.find{|k| k.member?(prefix)}
- raise UndefinedNamespaceException.new(prefix,@source,self)
- end
- end
-
- if md[6]
- @closed = md[1]
- @nsstack.shift
- else
- @tags.push( md[1] )
- end
- return [ :start_element, md[1], attributes ]
- end
- else
- md = @source.match( TEXT_PATTERN, true )
- if md[0].length == 0
- @source.match( /(\s+)/, true )
- end
- #STDERR.puts "GOT #{md[1].inspect}" unless md[0].length == 0
- #return [ :text, "" ] if md[0].length == 0
- # unnormalized = Text::unnormalize( md[1], self )
- # return PullEvent.new( :text, md[1], unnormalized )
- return [ :text, md[1] ]
- end
- rescue REXML::UndefinedNamespaceException
- raise
- rescue REXML::ParseException
- raise
- rescue Exception, NameError => error
- raise REXML::ParseException.new( "Exception parsing",
- @source, self, (error ? error : $!) )
- end
- return [ :dummy ]
- end
- private :pull_event
-
- def entity( reference, entities )
- value = nil
- value = entities[ reference ] if entities
- if not value
- value = DEFAULT_ENTITIES[ reference ]
- value = value[2] if value
- end
- unnormalize( value, entities ) if value
- end
-
- # Escapes all possible entities
- def normalize( input, entities=nil, entity_filter=nil )
- copy = input.clone
- # Doing it like this rather than in a loop improves the speed
- copy.gsub!( EREFERENCE, '&amp;' )
- entities.each do |key, value|
- copy.gsub!( value, "&#{key};" ) unless entity_filter and
- entity_filter.include?(entity)
- end if entities
- copy.gsub!( EREFERENCE, '&amp;' )
- DEFAULT_ENTITIES.each do |key, value|
- copy.gsub!( value[3], value[1] )
- end
- copy
- end
-
- # Unescapes all possible entities
- def unnormalize( string, entities=nil, filter=nil )
- rv = string.clone
- rv.gsub!( /\r\n?/, "\n" )
- matches = rv.scan( REFERENCE_RE )
- return rv if matches.size == 0
- rv.gsub!( /&#0*((?:\d+)|(?:x[a-fA-F0-9]+));/ ) {
- m=$1
- m = "0#{m}" if m[0] == ?x
- [Integer(m)].pack('U*')
- }
- matches.collect!{|x|x[0]}.compact!
- if matches.size > 0
- matches.each do |entity_reference|
- unless filter and filter.include?(entity_reference)
- entity_value = entity( entity_reference, entities )
- if entity_value
- re = /&#{entity_reference};/
- rv.gsub!( re, entity_value )
- else
- er = DEFAULT_ENTITIES[entity_reference]
- rv.gsub!( er[0], er[2] ) if er
- end
- end
- end
- rv.gsub!( /&amp;/, '&' )
- end
- rv
- end
- end
- end
-end
-
-=begin
- case event[0]
- when :start_element
- when :text
- when :end_element
- when :processing_instruction
- when :cdata
- when :comment
- when :xmldecl
- when :start_doctype
- when :end_doctype
- when :externalentity
- when :elementdecl
- when :entity
- when :attlistdecl
- when :notationdecl
- when :end_doctype
- end
-=end
diff --git a/ruby_1_9_3/lib/rexml/parsers/lightparser.rb b/ruby_1_9_3/lib/rexml/parsers/lightparser.rb
deleted file mode 100644
index 81041681c2..0000000000
--- a/ruby_1_9_3/lib/rexml/parsers/lightparser.rb
+++ /dev/null
@@ -1,58 +0,0 @@
-require 'rexml/parsers/streamparser'
-require 'rexml/parsers/baseparser'
-require 'rexml/light/node'
-
-module REXML
- module Parsers
- class LightParser
- def initialize stream
- @stream = stream
- @parser = REXML::Parsers::BaseParser.new( stream )
- end
-
- def add_listener( listener )
- @parser.add_listener( listener )
- end
-
- def rewind
- @stream.rewind
- @parser.stream = @stream
- end
-
- def parse
- root = context = [ :document ]
- while true
- event = @parser.pull
- case event[0]
- when :end_document
- break
- when :start_element, :start_doctype
- new_node = event
- context << new_node
- new_node[1,0] = [context]
- context = new_node
- when :end_element, :end_doctype
- context = context[1]
- else
- new_node = event
- context << new_node
- new_node[1,0] = [context]
- end
- end
- root
- end
- end
-
- # An element is an array. The array contains:
- # 0 The parent element
- # 1 The tag name
- # 2 A hash of attributes
- # 3..-1 The child elements
- # An element is an array of size > 3
- # Text is a String
- # PIs are [ :processing_instruction, target, data ]
- # Comments are [ :comment, data ]
- # DocTypes are DocType structs
- # The root is an array with XMLDecls, Text, DocType, Array, Text
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/parsers/pullparser.rb b/ruby_1_9_3/lib/rexml/parsers/pullparser.rb
deleted file mode 100644
index 68a4ff7eae..0000000000
--- a/ruby_1_9_3/lib/rexml/parsers/pullparser.rb
+++ /dev/null
@@ -1,196 +0,0 @@
-require 'forwardable'
-
-require 'rexml/parseexception'
-require 'rexml/parsers/baseparser'
-require 'rexml/xmltokens'
-
-module REXML
- module Parsers
- # = Using the Pull Parser
- # <em>This API is experimental, and subject to change.</em>
- # parser = PullParser.new( "<a>text<b att='val'/>txet</a>" )
- # while parser.has_next?
- # res = parser.next
- # puts res[1]['att'] if res.start_tag? and res[0] == 'b'
- # end
- # See the PullEvent class for information on the content of the results.
- # The data is identical to the arguments passed for the various events to
- # the StreamListener API.
- #
- # Notice that:
- # parser = PullParser.new( "<a>BAD DOCUMENT" )
- # while parser.has_next?
- # res = parser.next
- # raise res[1] if res.error?
- # end
- #
- # Nat Price gave me some good ideas for the API.
- class PullParser
- include XMLTokens
- extend Forwardable
-
- def_delegators( :@parser, :has_next? )
- def_delegators( :@parser, :entity )
- def_delegators( :@parser, :empty? )
- def_delegators( :@parser, :source )
-
- def initialize stream
- @entities = {}
- @listeners = nil
- @parser = BaseParser.new( stream )
- @my_stack = []
- end
-
- def add_listener( listener )
- @listeners = [] unless @listeners
- @listeners << listener
- end
-
- def each
- while has_next?
- yield self.pull
- end
- end
-
- def peek depth=0
- if @my_stack.length <= depth
- (depth - @my_stack.length + 1).times {
- e = PullEvent.new(@parser.pull)
- @my_stack.push(e)
- }
- end
- @my_stack[depth]
- end
-
- def pull
- return @my_stack.shift if @my_stack.length > 0
-
- event = @parser.pull
- case event[0]
- when :entitydecl
- @entities[ event[1] ] =
- event[2] unless event[2] =~ /PUBLIC|SYSTEM/
- when :text
- unnormalized = @parser.unnormalize( event[1], @entities )
- event << unnormalized
- end
- PullEvent.new( event )
- end
-
- def unshift token
- @my_stack.unshift token
- end
- end
-
- # A parsing event. The contents of the event are accessed as an +Array?,
- # and the type is given either by the ...? methods, or by accessing the
- # +type+ accessor. The contents of this object vary from event to event,
- # but are identical to the arguments passed to +StreamListener+s for each
- # event.
- class PullEvent
- # The type of this event. Will be one of :tag_start, :tag_end, :text,
- # :processing_instruction, :comment, :doctype, :attlistdecl, :entitydecl,
- # :notationdecl, :entity, :cdata, :xmldecl, or :error.
- def initialize(arg)
- @contents = arg
- end
-
- def []( start, endd=nil)
- if start.kind_of? Range
- @contents.slice( start.begin+1 .. start.end )
- elsif start.kind_of? Numeric
- if endd.nil?
- @contents.slice( start+1 )
- else
- @contents.slice( start+1, endd )
- end
- else
- raise "Illegal argument #{start.inspect} (#{start.class})"
- end
- end
-
- def event_type
- @contents[0]
- end
-
- # Content: [ String tag_name, Hash attributes ]
- def start_element?
- @contents[0] == :start_element
- end
-
- # Content: [ String tag_name ]
- def end_element?
- @contents[0] == :end_element
- end
-
- # Content: [ String raw_text, String unnormalized_text ]
- def text?
- @contents[0] == :text
- end
-
- # Content: [ String text ]
- def instruction?
- @contents[0] == :processing_instruction
- end
-
- # Content: [ String text ]
- def comment?
- @contents[0] == :comment
- end
-
- # Content: [ String name, String pub_sys, String long_name, String uri ]
- def doctype?
- @contents[0] == :start_doctype
- end
-
- # Content: [ String text ]
- def attlistdecl?
- @contents[0] == :attlistdecl
- end
-
- # Content: [ String text ]
- def elementdecl?
- @contents[0] == :elementdecl
- end
-
- # Due to the wonders of DTDs, an entity declaration can be just about
- # anything. There's no way to normalize it; you'll have to interpret the
- # content yourself. However, the following is true:
- #
- # * If the entity declaration is an internal entity:
- # [ String name, String value ]
- # Content: [ String text ]
- def entitydecl?
- @contents[0] == :entitydecl
- end
-
- # Content: [ String text ]
- def notationdecl?
- @contents[0] == :notationdecl
- end
-
- # Content: [ String text ]
- def entity?
- @contents[0] == :entity
- end
-
- # Content: [ String text ]
- def cdata?
- @contents[0] == :cdata
- end
-
- # Content: [ String version, String encoding, String standalone ]
- def xmldecl?
- @contents[0] == :xmldecl
- end
-
- def error?
- @contents[0] == :error
- end
-
- def inspect
- @contents[0].to_s + ": " + @contents[1..-1].inspect
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/parsers/sax2parser.rb b/ruby_1_9_3/lib/rexml/parsers/sax2parser.rb
deleted file mode 100644
index 0661af37aa..0000000000
--- a/ruby_1_9_3/lib/rexml/parsers/sax2parser.rb
+++ /dev/null
@@ -1,247 +0,0 @@
-require 'rexml/parsers/baseparser'
-require 'rexml/parseexception'
-require 'rexml/namespace'
-require 'rexml/text'
-
-module REXML
- module Parsers
- # SAX2Parser
- class SAX2Parser
- def initialize source
- @parser = BaseParser.new(source)
- @listeners = []
- @procs = []
- @namespace_stack = []
- @has_listeners = false
- @tag_stack = []
- @entities = {}
- end
-
- def source
- @parser.source
- end
-
- def add_listener( listener )
- @parser.add_listener( listener )
- end
-
- # Listen arguments:
- #
- # Symbol, Array, Block
- # Listen to Symbol events on Array elements
- # Symbol, Block
- # Listen to Symbol events
- # Array, Listener
- # Listen to all events on Array elements
- # Array, Block
- # Listen to :start_element events on Array elements
- # Listener
- # Listen to All events
- #
- # Symbol can be one of: :start_element, :end_element,
- # :start_prefix_mapping, :end_prefix_mapping, :characters,
- # :processing_instruction, :doctype, :attlistdecl, :elementdecl,
- # :entitydecl, :notationdecl, :cdata, :xmldecl, :comment
- #
- # There is an additional symbol that can be listened for: :progress.
- # This will be called for every event generated, passing in the current
- # stream position.
- #
- # Array contains regular expressions or strings which will be matched
- # against fully qualified element names.
- #
- # Listener must implement the methods in SAX2Listener
- #
- # Block will be passed the same arguments as a SAX2Listener method would
- # be, where the method name is the same as the matched Symbol.
- # See the SAX2Listener for more information.
- def listen( *args, &blok )
- if args[0].kind_of? Symbol
- if args.size == 2
- args[1].each { |match| @procs << [args[0], match, blok] }
- else
- add( [args[0], nil, blok] )
- end
- elsif args[0].kind_of? Array
- if args.size == 2
- args[0].each { |match| add( [nil, match, args[1]] ) }
- else
- args[0].each { |match| add( [ :start_element, match, blok ] ) }
- end
- else
- add([nil, nil, args[0]])
- end
- end
-
- def deafen( listener=nil, &blok )
- if listener
- @listeners.delete_if {|item| item[-1] == listener }
- @has_listeners = false if @listeners.size == 0
- else
- @procs.delete_if {|item| item[-1] == blok }
- end
- end
-
- def parse
- @procs.each { |sym,match,block| block.call if sym == :start_document }
- @listeners.each { |sym,match,block|
- block.start_document if sym == :start_document or sym.nil?
- }
- context = []
- while true
- event = @parser.pull
- case event[0]
- when :end_document
- handle( :end_document )
- break
- when :start_doctype
- handle( :doctype, *event[1..-1])
- when :end_doctype
- context = context[1]
- when :start_element
- @tag_stack.push(event[1])
- # find the observers for namespaces
- procs = get_procs( :start_prefix_mapping, event[1] )
- listeners = get_listeners( :start_prefix_mapping, event[1] )
- if procs or listeners
- # break out the namespace declarations
- # The attributes live in event[2]
- event[2].each {|n, v| event[2][n] = @parser.normalize(v)}
- nsdecl = event[2].find_all { |n, value| n =~ /^xmlns(:|$)/ }
- nsdecl.collect! { |n, value| [ n[6..-1], value ] }
- @namespace_stack.push({})
- nsdecl.each do |n,v|
- @namespace_stack[-1][n] = v
- # notify observers of namespaces
- procs.each { |ob| ob.call( n, v ) } if procs
- listeners.each { |ob| ob.start_prefix_mapping(n, v) } if listeners
- end
- end
- event[1] =~ Namespace::NAMESPLIT
- prefix = $1
- local = $2
- uri = get_namespace(prefix)
- # find the observers for start_element
- procs = get_procs( :start_element, event[1] )
- listeners = get_listeners( :start_element, event[1] )
- # notify observers
- procs.each { |ob| ob.call( uri, local, event[1], event[2] ) } if procs
- listeners.each { |ob|
- ob.start_element( uri, local, event[1], event[2] )
- } if listeners
- when :end_element
- @tag_stack.pop
- event[1] =~ Namespace::NAMESPLIT
- prefix = $1
- local = $2
- uri = get_namespace(prefix)
- # find the observers for start_element
- procs = get_procs( :end_element, event[1] )
- listeners = get_listeners( :end_element, event[1] )
- # notify observers
- procs.each { |ob| ob.call( uri, local, event[1] ) } if procs
- listeners.each { |ob|
- ob.end_element( uri, local, event[1] )
- } if listeners
-
- namespace_mapping = @namespace_stack.pop
- # find the observers for namespaces
- procs = get_procs( :end_prefix_mapping, event[1] )
- listeners = get_listeners( :end_prefix_mapping, event[1] )
- if procs or listeners
- namespace_mapping.each do |ns_prefix, ns_uri|
- # notify observers of namespaces
- procs.each { |ob| ob.call( ns_prefix ) } if procs
- listeners.each { |ob| ob.end_prefix_mapping(ns_prefix) } if listeners
- end
- end
- when :text
- #normalized = @parser.normalize( event[1] )
- #handle( :characters, normalized )
- copy = event[1].clone
-
- esub = proc { |match|
- if @entities.has_key?($1)
- @entities[$1].gsub(Text::REFERENCE, &esub)
- else
- match
- end
- }
-
- copy.gsub!( Text::REFERENCE, &esub )
- copy.gsub!( Text::NUMERICENTITY ) {|m|
- m=$1
- m = "0#{m}" if m[0] == ?x
- [Integer(m)].pack('U*')
- }
- handle( :characters, copy )
- when :entitydecl
- @entities[ event[1] ] = event[2] if event.size == 3
- handle( *event )
- when :processing_instruction, :comment, :attlistdecl,
- :elementdecl, :cdata, :notationdecl, :xmldecl
- handle( *event )
- end
- handle( :progress, @parser.position )
- end
- end
-
- private
- def handle( symbol, *arguments )
- tag = @tag_stack[-1]
- procs = get_procs( symbol, tag )
- listeners = get_listeners( symbol, tag )
- # notify observers
- procs.each { |ob| ob.call( *arguments ) } if procs
- listeners.each { |l|
- l.send( symbol.to_s, *arguments )
- } if listeners
- end
-
- # The following methods are duplicates, but it is faster than using
- # a helper
- def get_procs( symbol, name )
- return nil if @procs.size == 0
- @procs.find_all do |sym, match, block|
- #puts sym.inspect+"=="+symbol.inspect+ "\t"+match.inspect+"=="+name.inspect+ "\t"+( (sym.nil? or symbol == sym) and ((name.nil? and match.nil?) or match.nil? or ( (name == match) or (match.kind_of? Regexp and name =~ match)))).to_s
- (
- (sym.nil? or symbol == sym) and
- ((name.nil? and match.nil?) or match.nil? or (
- (name == match) or
- (match.kind_of? Regexp and name =~ match)
- )
- )
- )
- end.collect{|x| x[-1]}
- end
- def get_listeners( symbol, name )
- return nil if @listeners.size == 0
- @listeners.find_all do |sym, match, block|
- (
- (sym.nil? or symbol == sym) and
- ((name.nil? and match.nil?) or match.nil? or (
- (name == match) or
- (match.kind_of? Regexp and name =~ match)
- )
- )
- )
- end.collect{|x| x[-1]}
- end
-
- def add( pair )
- if pair[-1].respond_to? :call
- @procs << pair unless @procs.include? pair
- else
- @listeners << pair unless @listeners.include? pair
- @has_listeners = true
- end
- end
-
- def get_namespace( prefix )
- uris = (@namespace_stack.find_all { |ns| not ns[prefix].nil? }) ||
- (@namespace_stack.find { |ns| not ns[nil].nil? })
- uris[-1][prefix] unless uris.nil? or 0 == uris.size
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/parsers/streamparser.rb b/ruby_1_9_3/lib/rexml/parsers/streamparser.rb
deleted file mode 100644
index 073fcc2c21..0000000000
--- a/ruby_1_9_3/lib/rexml/parsers/streamparser.rb
+++ /dev/null
@@ -1,46 +0,0 @@
-module REXML
- module Parsers
- class StreamParser
- def initialize source, listener
- @listener = listener
- @parser = BaseParser.new( source )
- end
-
- def add_listener( listener )
- @parser.add_listener( listener )
- end
-
- def parse
- # entity string
- while true
- event = @parser.pull
- case event[0]
- when :end_document
- return
- when :start_element
- attrs = event[2].each do |n, v|
- event[2][n] = @parser.unnormalize( v )
- end
- @listener.tag_start( event[1], attrs )
- when :end_element
- @listener.tag_end( event[1] )
- when :text
- normalized = @parser.unnormalize( event[1] )
- @listener.text( normalized )
- when :processing_instruction
- @listener.instruction( *event[1,2] )
- when :start_doctype
- @listener.doctype( *event[1..-1] )
- when :end_doctype
- # FIXME: remove this condition for milestone:3.2
- @listener.doctype_end if @listener.respond_to? :doctype_end
- when :comment, :attlistdecl, :cdata, :xmldecl, :elementdecl
- @listener.send( event[0].to_s, *event[1..-1] )
- when :entitydecl, :notationdecl
- @listener.send( event[0].to_s, event[1..-1] )
- end
- end
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/parsers/treeparser.rb b/ruby_1_9_3/lib/rexml/parsers/treeparser.rb
deleted file mode 100644
index 7f618cb319..0000000000
--- a/ruby_1_9_3/lib/rexml/parsers/treeparser.rb
+++ /dev/null
@@ -1,100 +0,0 @@
-require 'rexml/validation/validationexception'
-require 'rexml/undefinednamespaceexception'
-
-module REXML
- module Parsers
- class TreeParser
- def initialize( source, build_context = Document.new )
- @build_context = build_context
- @parser = Parsers::BaseParser.new( source )
- end
-
- def add_listener( listener )
- @parser.add_listener( listener )
- end
-
- def parse
- tag_stack = []
- in_doctype = false
- entities = nil
- begin
- while true
- event = @parser.pull
- #STDERR.puts "TREEPARSER GOT #{event.inspect}"
- case event[0]
- when :end_document
- unless tag_stack.empty?
- #raise ParseException.new("No close tag for #{tag_stack.inspect}")
- raise ParseException.new("No close tag for #{@build_context.xpath}")
- end
- return
- when :start_element
- tag_stack.push(event[1])
- el = @build_context = @build_context.add_element( event[1] )
- event[2].each do |key, value|
- el.attributes[key]=Attribute.new(key,value,self)
- end
- when :end_element
- tag_stack.pop
- @build_context = @build_context.parent
- when :text
- if not in_doctype
- if @build_context[-1].instance_of? Text
- @build_context[-1] << event[1]
- else
- @build_context.add(
- Text.new(event[1], @build_context.whitespace, nil, true)
- ) unless (
- @build_context.ignore_whitespace_nodes and
- event[1].strip.size==0
- )
- end
- end
- when :comment
- c = Comment.new( event[1] )
- @build_context.add( c )
- when :cdata
- c = CData.new( event[1] )
- @build_context.add( c )
- when :processing_instruction
- @build_context.add( Instruction.new( event[1], event[2] ) )
- when :end_doctype
- in_doctype = false
- entities.each { |k,v| entities[k] = @build_context.entities[k].value }
- @build_context = @build_context.parent
- when :start_doctype
- doctype = DocType.new( event[1..-1], @build_context )
- @build_context = doctype
- entities = {}
- in_doctype = true
- when :attlistdecl
- n = AttlistDecl.new( event[1..-1] )
- @build_context.add( n )
- when :externalentity
- n = ExternalEntity.new( event[1] )
- @build_context.add( n )
- when :elementdecl
- n = ElementDecl.new( event[1] )
- @build_context.add(n)
- when :entitydecl
- entities[ event[1] ] = event[2] unless event[2] =~ /PUBLIC|SYSTEM/
- @build_context.add(Entity.new(event))
- when :notationdecl
- n = NotationDecl.new( *event[1..-1] )
- @build_context.add( n )
- when :xmldecl
- x = XMLDecl.new( event[1], event[2], event[3] )
- @build_context.add( x )
- end
- end
- rescue REXML::Validation::ValidationException
- raise
- rescue REXML::UndefinedNamespaceException
- raise
- rescue
- raise ParseException.new( $!.message, @parser.source, @parser, $! )
- end
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/parsers/ultralightparser.rb b/ruby_1_9_3/lib/rexml/parsers/ultralightparser.rb
deleted file mode 100644
index 7dd8172802..0000000000
--- a/ruby_1_9_3/lib/rexml/parsers/ultralightparser.rb
+++ /dev/null
@@ -1,56 +0,0 @@
-require 'rexml/parsers/streamparser'
-require 'rexml/parsers/baseparser'
-
-module REXML
- module Parsers
- class UltraLightParser
- def initialize stream
- @stream = stream
- @parser = REXML::Parsers::BaseParser.new( stream )
- end
-
- def add_listener( listener )
- @parser.add_listener( listener )
- end
-
- def rewind
- @stream.rewind
- @parser.stream = @stream
- end
-
- def parse
- root = context = []
- while true
- event = @parser.pull
- case event[0]
- when :end_document
- break
- when :end_doctype
- context = context[1]
- when :start_element, :doctype
- context << event
- event[1,0] = [context]
- context = event
- when :end_element
- context = context[1]
- else
- context << event
- end
- end
- root
- end
- end
-
- # An element is an array. The array contains:
- # 0 The parent element
- # 1 The tag name
- # 2 A hash of attributes
- # 3..-1 The child elements
- # An element is an array of size > 3
- # Text is a String
- # PIs are [ :processing_instruction, target, data ]
- # Comments are [ :comment, data ]
- # DocTypes are DocType structs
- # The root is an array with XMLDecls, Text, DocType, Array, Text
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/parsers/xpathparser.rb b/ruby_1_9_3/lib/rexml/parsers/xpathparser.rb
deleted file mode 100644
index e643d11511..0000000000
--- a/ruby_1_9_3/lib/rexml/parsers/xpathparser.rb
+++ /dev/null
@@ -1,697 +0,0 @@
-require 'rexml/namespace'
-require 'rexml/xmltokens'
-
-module REXML
- module Parsers
- # You don't want to use this class. Really. Use XPath, which is a wrapper
- # for this class. Believe me. You don't want to poke around in here.
- # There is strange, dark magic at work in this code. Beware. Go back! Go
- # back while you still can!
- class XPathParser
- include XMLTokens
- LITERAL = /^'([^']*)'|^"([^"]*)"/u
-
- def namespaces=( namespaces )
- Functions::namespace_context = namespaces
- @namespaces = namespaces
- end
-
- def parse path
- path = path.dup
- path.gsub!(/([\(\[])\s+/, '\1') # Strip ignorable spaces
- path.gsub!( /\s+([\]\)])/, '\1')
- parsed = []
- path = OrExpr(path, parsed)
- parsed
- end
-
- def predicate path
- parsed = []
- Predicate( "[#{path}]", parsed )
- parsed
- end
-
- def abbreviate( path )
- path = path.kind_of?(String) ? parse( path ) : path
- string = ""
- document = false
- while path.size > 0
- op = path.shift
- case op
- when :node
- when :attribute
- string << "/" if string.size > 0
- string << "@"
- when :child
- string << "/" if string.size > 0
- when :descendant_or_self
- string << "/"
- when :self
- string << "."
- when :parent
- string << ".."
- when :any
- string << "*"
- when :text
- string << "text()"
- when :following, :following_sibling,
- :ancestor, :ancestor_or_self, :descendant,
- :namespace, :preceding, :preceding_sibling
- string << "/" unless string.size == 0
- string << op.to_s.tr("_", "-")
- string << "::"
- when :qname
- prefix = path.shift
- name = path.shift
- string << prefix+":" if prefix.size > 0
- string << name
- when :predicate
- string << '['
- string << predicate_to_string( path.shift ) {|x| abbreviate( x ) }
- string << ']'
- when :document
- document = true
- when :function
- string << path.shift
- string << "( "
- string << predicate_to_string( path.shift[0] ) {|x| abbreviate( x )}
- string << " )"
- when :literal
- string << %Q{ "#{path.shift}" }
- else
- string << "/" unless string.size == 0
- string << "UNKNOWN("
- string << op.inspect
- string << ")"
- end
- end
- string = "/"+string if document
- return string
- end
-
- def expand( path )
- path = path.kind_of?(String) ? parse( path ) : path
- string = ""
- document = false
- while path.size > 0
- op = path.shift
- case op
- when :node
- string << "node()"
- when :attribute, :child, :following, :following_sibling,
- :ancestor, :ancestor_or_self, :descendant, :descendant_or_self,
- :namespace, :preceding, :preceding_sibling, :self, :parent
- string << "/" unless string.size == 0
- string << op.to_s.tr("_", "-")
- string << "::"
- when :any
- string << "*"
- when :qname
- prefix = path.shift
- name = path.shift
- string << prefix+":" if prefix.size > 0
- string << name
- when :predicate
- string << '['
- string << predicate_to_string( path.shift ) { |x| expand(x) }
- string << ']'
- when :document
- document = true
- else
- string << "/" unless string.size == 0
- string << "UNKNOWN("
- string << op.inspect
- string << ")"
- end
- end
- string = "/"+string if document
- return string
- end
-
- def predicate_to_string( path, &block )
- string = ""
- case path[0]
- when :and, :or, :mult, :plus, :minus, :neq, :eq, :lt, :gt, :lteq, :gteq, :div, :mod, :union
- op = path.shift
- case op
- when :eq
- op = "="
- when :lt
- op = "<"
- when :gt
- op = ">"
- when :lteq
- op = "<="
- when :gteq
- op = ">="
- when :neq
- op = "!="
- when :union
- op = "|"
- end
- left = predicate_to_string( path.shift, &block )
- right = predicate_to_string( path.shift, &block )
- string << " "
- string << left
- string << " "
- string << op.to_s
- string << " "
- string << right
- string << " "
- when :function
- path.shift
- name = path.shift
- string << name
- string << "( "
- string << predicate_to_string( path.shift, &block )
- string << " )"
- when :literal
- path.shift
- string << " "
- string << path.shift.inspect
- string << " "
- else
- string << " "
- string << yield( path )
- string << " "
- end
- return string.squeeze(" ")
- end
-
- private
- #LocationPath
- # | RelativeLocationPath
- # | '/' RelativeLocationPath?
- # | '//' RelativeLocationPath
- def LocationPath path, parsed
- #puts "LocationPath '#{path}'"
- path = path.strip
- if path[0] == ?/
- parsed << :document
- if path[1] == ?/
- parsed << :descendant_or_self
- parsed << :node
- path = path[2..-1]
- else
- path = path[1..-1]
- end
- end
- #puts parsed.inspect
- return RelativeLocationPath( path, parsed ) if path.size > 0
- end
-
- #RelativeLocationPath
- # | Step
- # | (AXIS_NAME '::' | '@' | '') AxisSpecifier
- # NodeTest
- # Predicate
- # | '.' | '..' AbbreviatedStep
- # | RelativeLocationPath '/' Step
- # | RelativeLocationPath '//' Step
- AXIS = /^(ancestor|ancestor-or-self|attribute|child|descendant|descendant-or-self|following|following-sibling|namespace|parent|preceding|preceding-sibling|self)::/
- def RelativeLocationPath path, parsed
- #puts "RelativeLocationPath #{path}"
- while path.size > 0
- # (axis or @ or <child::>) nodetest predicate >
- # OR > / Step
- # (. or ..) >
- if path[0] == ?.
- if path[1] == ?.
- parsed << :parent
- parsed << :node
- path = path[2..-1]
- else
- parsed << :self
- parsed << :node
- path = path[1..-1]
- end
- else
- if path[0] == ?@
- #puts "ATTRIBUTE"
- parsed << :attribute
- path = path[1..-1]
- # Goto Nodetest
- elsif path =~ AXIS
- parsed << $1.tr('-','_').intern
- path = $'
- # Goto Nodetest
- else
- parsed << :child
- end
-
- #puts "NODETESTING '#{path}'"
- n = []
- path = NodeTest( path, n)
- #puts "NODETEST RETURNED '#{path}'"
-
- if path[0] == ?[
- path = Predicate( path, n )
- end
-
- parsed.concat(n)
- end
-
- if path.size > 0
- if path[0] == ?/
- if path[1] == ?/
- parsed << :descendant_or_self
- parsed << :node
- path = path[2..-1]
- else
- path = path[1..-1]
- end
- else
- return path
- end
- end
- end
- return path
- end
-
- # Returns a 1-1 map of the nodeset
- # The contents of the resulting array are either:
- # true/false, if a positive match
- # String, if a name match
- #NodeTest
- # | ('*' | NCNAME ':' '*' | QNAME) NameTest
- # | NODE_TYPE '(' ')' NodeType
- # | PI '(' LITERAL ')' PI
- # | '[' expr ']' Predicate
- NCNAMETEST= /^(#{NCNAME_STR}):\*/u
- QNAME = Namespace::NAMESPLIT
- NODE_TYPE = /^(comment|text|node)\(\s*\)/m
- PI = /^processing-instruction\(/
- def NodeTest path, parsed
- #puts "NodeTest with #{path}"
- case path
- when /^\*/
- path = $'
- parsed << :any
- when NODE_TYPE
- type = $1
- path = $'
- parsed << type.tr('-', '_').intern
- when PI
- path = $'
- literal = nil
- if path !~ /^\s*\)/
- path =~ LITERAL
- literal = $1
- path = $'
- raise ParseException.new("Missing ')' after processing instruction") if path[0] != ?)
- path = path[1..-1]
- end
- parsed << :processing_instruction
- parsed << (literal || '')
- when NCNAMETEST
- #puts "NCNAMETEST"
- prefix = $1
- path = $'
- parsed << :namespace
- parsed << prefix
- when QNAME
- #puts "QNAME"
- prefix = $1
- name = $2
- path = $'
- prefix = "" unless prefix
- parsed << :qname
- parsed << prefix
- parsed << name
- end
- return path
- end
-
- # Filters the supplied nodeset on the predicate(s)
- def Predicate path, parsed
- #puts "PREDICATE with #{path}"
- return nil unless path[0] == ?[
- predicates = []
- while path[0] == ?[
- path, expr = get_group(path)
- predicates << expr[1..-2] if expr
- end
- #puts "PREDICATES = #{predicates.inspect}"
- predicates.each{ |pred|
- #puts "ORING #{pred}"
- preds = []
- parsed << :predicate
- parsed << preds
- OrExpr(pred, preds)
- }
- #puts "PREDICATES = #{predicates.inspect}"
- path
- end
-
- # The following return arrays of true/false, a 1-1 mapping of the
- # supplied nodeset, except for axe(), which returns a filtered
- # nodeset
-
- #| OrExpr S 'or' S AndExpr
- #| AndExpr
- def OrExpr path, parsed
- #puts "OR >>> #{path}"
- n = []
- rest = AndExpr( path, n )
- #puts "OR <<< #{rest}"
- if rest != path
- while rest =~ /^\s*( or )/
- n = [ :or, n, [] ]
- rest = AndExpr( $', n[-1] )
- end
- end
- if parsed.size == 0 and n.size != 0
- parsed.replace(n)
- elsif n.size > 0
- parsed << n
- end
- rest
- end
-
- #| AndExpr S 'and' S EqualityExpr
- #| EqualityExpr
- def AndExpr path, parsed
- #puts "AND >>> #{path}"
- n = []
- rest = EqualityExpr( path, n )
- #puts "AND <<< #{rest}"
- if rest != path
- while rest =~ /^\s*( and )/
- n = [ :and, n, [] ]
- #puts "AND >>> #{rest}"
- rest = EqualityExpr( $', n[-1] )
- #puts "AND <<< #{rest}"
- end
- end
- if parsed.size == 0 and n.size != 0
- parsed.replace(n)
- elsif n.size > 0
- parsed << n
- end
- rest
- end
-
- #| EqualityExpr ('=' | '!=') RelationalExpr
- #| RelationalExpr
- def EqualityExpr path, parsed
- #puts "EQUALITY >>> #{path}"
- n = []
- rest = RelationalExpr( path, n )
- #puts "EQUALITY <<< #{rest}"
- if rest != path
- while rest =~ /^\s*(!?=)\s*/
- if $1[0] == ?!
- n = [ :neq, n, [] ]
- else
- n = [ :eq, n, [] ]
- end
- rest = RelationalExpr( $', n[-1] )
- end
- end
- if parsed.size == 0 and n.size != 0
- parsed.replace(n)
- elsif n.size > 0
- parsed << n
- end
- rest
- end
-
- #| RelationalExpr ('<' | '>' | '<=' | '>=') AdditiveExpr
- #| AdditiveExpr
- def RelationalExpr path, parsed
- #puts "RELATION >>> #{path}"
- n = []
- rest = AdditiveExpr( path, n )
- #puts "RELATION <<< #{rest}"
- if rest != path
- while rest =~ /^\s*([<>]=?)\s*/
- if $1[0] == ?<
- sym = "lt"
- else
- sym = "gt"
- end
- sym << "eq" if $1[-1] == ?=
- n = [ sym.intern, n, [] ]
- rest = AdditiveExpr( $', n[-1] )
- end
- end
- if parsed.size == 0 and n.size != 0
- parsed.replace(n)
- elsif n.size > 0
- parsed << n
- end
- rest
- end
-
- #| AdditiveExpr ('+' | S '-') MultiplicativeExpr
- #| MultiplicativeExpr
- def AdditiveExpr path, parsed
- #puts "ADDITIVE >>> #{path}"
- n = []
- rest = MultiplicativeExpr( path, n )
- #puts "ADDITIVE <<< #{rest}"
- if rest != path
- while rest =~ /^\s*(\+| -)\s*/
- if $1[0] == ?+
- n = [ :plus, n, [] ]
- else
- n = [ :minus, n, [] ]
- end
- rest = MultiplicativeExpr( $', n[-1] )
- end
- end
- if parsed.size == 0 and n.size != 0
- parsed.replace(n)
- elsif n.size > 0
- parsed << n
- end
- rest
- end
-
- #| MultiplicativeExpr ('*' | S ('div' | 'mod') S) UnaryExpr
- #| UnaryExpr
- def MultiplicativeExpr path, parsed
- #puts "MULT >>> #{path}"
- n = []
- rest = UnaryExpr( path, n )
- #puts "MULT <<< #{rest}"
- if rest != path
- while rest =~ /^\s*(\*| div | mod )\s*/
- if $1[0] == ?*
- n = [ :mult, n, [] ]
- elsif $1.include?( "div" )
- n = [ :div, n, [] ]
- else
- n = [ :mod, n, [] ]
- end
- rest = UnaryExpr( $', n[-1] )
- end
- end
- if parsed.size == 0 and n.size != 0
- parsed.replace(n)
- elsif n.size > 0
- parsed << n
- end
- rest
- end
-
- #| '-' UnaryExpr
- #| UnionExpr
- def UnaryExpr path, parsed
- path =~ /^(\-*)/
- path = $'
- if $1 and (($1.size % 2) != 0)
- mult = -1
- else
- mult = 1
- end
- parsed << :neg if mult < 0
-
- #puts "UNARY >>> #{path}"
- n = []
- path = UnionExpr( path, n )
- #puts "UNARY <<< #{path}"
- parsed.concat( n )
- path
- end
-
- #| UnionExpr '|' PathExpr
- #| PathExpr
- def UnionExpr path, parsed
- #puts "UNION >>> #{path}"
- n = []
- rest = PathExpr( path, n )
- #puts "UNION <<< #{rest}"
- if rest != path
- while rest =~ /^\s*(\|)\s*/
- n = [ :union, n, [] ]
- rest = PathExpr( $', n[-1] )
- end
- end
- if parsed.size == 0 and n.size != 0
- parsed.replace( n )
- elsif n.size > 0
- parsed << n
- end
- rest
- end
-
- #| LocationPath
- #| FilterExpr ('/' | '//') RelativeLocationPath
- def PathExpr path, parsed
- path =~ /^\s*/
- path = $'
- #puts "PATH >>> #{path}"
- n = []
- rest = FilterExpr( path, n )
- #puts "PATH <<< '#{rest}'"
- if rest != path
- if rest and rest[0] == ?/
- return RelativeLocationPath(rest, n)
- end
- end
- #puts "BEFORE WITH '#{rest}'"
- rest = LocationPath(rest, n) if rest =~ /\A[\/\.\@\[\w*]/
- parsed.concat(n)
- return rest
- end
-
- #| FilterExpr Predicate
- #| PrimaryExpr
- def FilterExpr path, parsed
- #puts "FILTER >>> #{path}"
- n = []
- path = PrimaryExpr( path, n )
- #puts "FILTER <<< #{path}"
- path = Predicate(path, n) if path and path[0] == ?[
- #puts "FILTER <<< #{path}"
- parsed.concat(n)
- path
- end
-
- #| VARIABLE_REFERENCE
- #| '(' expr ')'
- #| LITERAL
- #| NUMBER
- #| FunctionCall
- VARIABLE_REFERENCE = /^\$(#{NAME_STR})/u
- NUMBER = /^(\d*\.?\d+)/
- NT = /^comment|text|processing-instruction|node$/
- def PrimaryExpr path, parsed
- case path
- when VARIABLE_REFERENCE
- varname = $1
- path = $'
- parsed << :variable
- parsed << varname
- #arry << @variables[ varname ]
- when /^(\w[-\w]*)(?:\()/
- #puts "PrimaryExpr :: Function >>> #$1 -- '#$''"
- fname = $1
- tmp = $'
- #puts "#{fname} =~ #{NT.inspect}"
- return path if fname =~ NT
- path = tmp
- parsed << :function
- parsed << fname
- path = FunctionCall(path, parsed)
- when NUMBER
- #puts "LITERAL or NUMBER: #$1"
- varname = $1.nil? ? $2 : $1
- path = $'
- parsed << :literal
- parsed << (varname.include?('.') ? varname.to_f : varname.to_i)
- when LITERAL
- #puts "LITERAL or NUMBER: #$1"
- varname = $1.nil? ? $2 : $1
- path = $'
- parsed << :literal
- parsed << varname
- when /^\(/ #/
- path, contents = get_group(path)
- contents = contents[1..-2]
- n = []
- OrExpr( contents, n )
- parsed.concat(n)
- end
- path
- end
-
- #| FUNCTION_NAME '(' ( expr ( ',' expr )* )? ')'
- def FunctionCall rest, parsed
- path, arguments = parse_args(rest)
- argset = []
- for argument in arguments
- args = []
- OrExpr( argument, args )
- argset << args
- end
- parsed << argset
- path
- end
-
- # get_group( '[foo]bar' ) -> ['bar', '[foo]']
- def get_group string
- ind = 0
- depth = 0
- st = string[0,1]
- en = (st == "(" ? ")" : "]")
- begin
- case string[ind,1]
- when st
- depth += 1
- when en
- depth -= 1
- end
- ind += 1
- end while depth > 0 and ind < string.length
- return nil unless depth==0
- [string[ind..-1], string[0..ind-1]]
- end
-
- def parse_args( string )
- arguments = []
- ind = 0
- inquot = false
- inapos = false
- depth = 1
- begin
- case string[ind]
- when ?"
- inquot = !inquot unless inapos
- when ?'
- inapos = !inapos unless inquot
- else
- unless inquot or inapos
- case string[ind]
- when ?(
- depth += 1
- if depth == 1
- string = string[1..-1]
- ind -= 1
- end
- when ?)
- depth -= 1
- if depth == 0
- s = string[0,ind].strip
- arguments << s unless s == ""
- string = string[ind+1..-1]
- end
- when ?,
- if depth == 1
- s = string[0,ind].strip
- arguments << s unless s == ""
- string = string[ind+1..-1]
- ind = -1
- end
- end
- end
- end
- ind += 1
- end while depth > 0 and ind < string.length
- return nil unless depth==0
- [string,arguments]
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/quickpath.rb b/ruby_1_9_3/lib/rexml/quickpath.rb
deleted file mode 100644
index 9bec2158dd..0000000000
--- a/ruby_1_9_3/lib/rexml/quickpath.rb
+++ /dev/null
@@ -1,265 +0,0 @@
-require 'rexml/functions'
-require 'rexml/xmltokens'
-
-module REXML
- class QuickPath
- include Functions
- include XMLTokens
-
- # A base Hash object to be used when initializing a
- # default empty namespaces set.
- EMPTY_HASH = {}
-
- def QuickPath::first element, path, namespaces=EMPTY_HASH
- match(element, path, namespaces)[0]
- end
-
- def QuickPath::each element, path, namespaces=EMPTY_HASH, &block
- path = "*" unless path
- match(element, path, namespaces).each( &block )
- end
-
- def QuickPath::match element, path, namespaces=EMPTY_HASH
- raise "nil is not a valid xpath" unless path
- results = nil
- Functions::namespace_context = namespaces
- case path
- when /^\/([^\/]|$)/u
- # match on root
- path = path[1..-1]
- return [element.root.parent] if path == ''
- results = filter([element.root], path)
- when /^[-\w]*::/u
- results = filter([element], path)
- when /^\*/u
- results = filter(element.to_a, path)
- when /^[\[!\w:]/u
- # match on child
- children = element.to_a
- results = filter(children, path)
- else
- results = filter([element], path)
- end
- return results
- end
-
- # Given an array of nodes it filters the array based on the path. The
- # result is that when this method returns, the array will contain elements
- # which match the path
- def QuickPath::filter elements, path
- return elements if path.nil? or path == '' or elements.size == 0
- case path
- when /^\/\//u # Descendant
- return axe( elements, "descendant-or-self", $' )
- when /^\/?\b(\w[-\w]*)\b::/u # Axe
- return axe( elements, $1, $' )
- when /^\/(?=\b([:!\w][-\.\w]*:)?[-!\*\.\w]*\b([^:(]|$)|\*)/u # Child
- rest = $'
- results = []
- elements.each do |element|
- results |= filter( element.to_a, rest )
- end
- return results
- when /^\/?(\w[-\w]*)\(/u # / Function
- return function( elements, $1, $' )
- when Namespace::NAMESPLIT # Element name
- name = $2
- ns = $1
- rest = $'
- elements.delete_if do |element|
- !(element.kind_of? Element and
- (element.expanded_name == name or
- (element.name == name and
- element.namespace == Functions.namespace_context[ns])))
- end
- return filter( elements, rest )
- when /^\/\[/u
- matches = []
- elements.each do |element|
- matches |= predicate( element.to_a, path[1..-1] ) if element.kind_of? Element
- end
- return matches
- when /^\[/u # Predicate
- return predicate( elements, path )
- when /^\/?\.\.\./u # Ancestor
- return axe( elements, "ancestor", $' )
- when /^\/?\.\./u # Parent
- return filter( elements.collect{|e|e.parent}, $' )
- when /^\/?\./u # Self
- return filter( elements, $' )
- when /^\*/u # Any
- results = []
- elements.each do |element|
- results |= filter( [element], $' ) if element.kind_of? Element
- #if element.kind_of? Element
- # children = element.to_a
- # children.delete_if { |child| !child.kind_of?(Element) }
- # results |= filter( children, $' )
- #end
- end
- return results
- end
- return []
- end
-
- def QuickPath::axe( elements, axe_name, rest )
- matches = []
- matches = filter( elements.dup, rest ) if axe_name =~ /-or-self$/u
- case axe_name
- when /^descendant/u
- elements.each do |element|
- matches |= filter( element.to_a, "descendant-or-self::#{rest}" ) if element.kind_of? Element
- end
- when /^ancestor/u
- elements.each do |element|
- while element.parent
- matches << element.parent
- element = element.parent
- end
- end
- matches = filter( matches, rest )
- when "self"
- matches = filter( elements, rest )
- when "child"
- elements.each do |element|
- matches |= filter( element.to_a, rest ) if element.kind_of? Element
- end
- when "attribute"
- elements.each do |element|
- matches << element.attributes[ rest ] if element.kind_of? Element
- end
- when "parent"
- matches = filter(elements.collect{|element| element.parent}.uniq, rest)
- when "following-sibling"
- matches = filter(elements.collect{|element| element.next_sibling}.uniq,
- rest)
- when "previous-sibling"
- matches = filter(elements.collect{|element|
- element.previous_sibling}.uniq, rest )
- end
- return matches.uniq
- end
-
- OPERAND_ = '((?=(?:(?!and|or).)*[^\s<>=])[^\s<>=]+)'
- # A predicate filters a node-set with respect to an axis to produce a
- # new node-set. For each node in the node-set to be filtered, the
- # PredicateExpr is evaluated with that node as the context node, with
- # the number of nodes in the node-set as the context size, and with the
- # proximity position of the node in the node-set with respect to the
- # axis as the context position; if PredicateExpr evaluates to true for
- # that node, the node is included in the new node-set; otherwise, it is
- # not included.
- #
- # A PredicateExpr is evaluated by evaluating the Expr and converting
- # the result to a boolean. If the result is a number, the result will
- # be converted to true if the number is equal to the context position
- # and will be converted to false otherwise; if the result is not a
- # number, then the result will be converted as if by a call to the
- # boolean function. Thus a location path para[3] is equivalent to
- # para[position()=3].
- def QuickPath::predicate( elements, path )
- ind = 1
- bcount = 1
- while bcount > 0
- bcount += 1 if path[ind] == ?[
- bcount -= 1 if path[ind] == ?]
- ind += 1
- end
- ind -= 1
- predicate = path[1..ind-1]
- rest = path[ind+1..-1]
-
- # have to change 'a [=<>] b [=<>] c' into 'a [=<>] b and b [=<>] c'
- #
- predicate.gsub!(
- /#{OPERAND_}\s*([<>=])\s*#{OPERAND_}\s*([<>=])\s*#{OPERAND_}/u,
- '\1 \2 \3 and \3 \4 \5' )
- # Let's do some Ruby trickery to avoid some work:
- predicate.gsub!( /&/u, "&&" )
- predicate.gsub!( /=/u, "==" )
- predicate.gsub!( /@(\w[-\w.]*)/u, 'attribute("\1")' )
- predicate.gsub!( /\bmod\b/u, "%" )
- predicate.gsub!( /\b(\w[-\w.]*\()/u ) {
- fname = $1
- fname.gsub( /-/u, "_" )
- }
-
- Functions.pair = [ 0, elements.size ]
- results = []
- elements.each do |element|
- Functions.pair[0] += 1
- Functions.node = element
- res = eval( predicate )
- case res
- when true
- results << element
- when Fixnum
- results << element if Functions.pair[0] == res
- when String
- results << element
- end
- end
- return filter( results, rest )
- end
-
- def QuickPath::attribute( name )
- return Functions.node.attributes[name] if Functions.node.kind_of? Element
- end
-
- def QuickPath::name()
- return Functions.node.name if Functions.node.kind_of? Element
- end
-
- def QuickPath::method_missing( id, *args )
- begin
- Functions.send( id.id2name, *args )
- rescue Exception
- raise "METHOD: #{id.id2name}(#{args.join ', '})\n#{$!.message}"
- end
- end
-
- def QuickPath::function( elements, fname, rest )
- args = parse_args( elements, rest )
- Functions.pair = [0, elements.size]
- results = []
- elements.each do |element|
- Functions.pair[0] += 1
- Functions.node = element
- res = Functions.send( fname, *args )
- case res
- when true
- results << element
- when Fixnum
- results << element if Functions.pair[0] == res
- end
- end
- return results
- end
-
- def QuickPath::parse_args( element, string )
- # /.*?(?:\)|,)/
- arguments = []
- buffer = ""
- while string and string != ""
- c = string[0]
- string.sub!(/^./u, "")
- case c
- when ?,
- # if depth = 1, then we start a new argument
- arguments << evaluate( buffer )
- #arguments << evaluate( string[0..count] )
- when ?(
- # start a new method call
- function( element, buffer, string )
- buffer = ""
- when ?)
- # close the method call and return arguments
- return arguments
- else
- buffer << c
- end
- end
- ""
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/rexml.rb b/ruby_1_9_3/lib/rexml/rexml.rb
deleted file mode 100644
index bc59a30c64..0000000000
--- a/ruby_1_9_3/lib/rexml/rexml.rb
+++ /dev/null
@@ -1,43 +0,0 @@
-# -*- encoding: utf-8 -*-
-# REXML is an XML toolkit for Ruby[http://www.ruby-lang.org], in Ruby.
-#
-# REXML is a _pure_ Ruby, XML 1.0 conforming,
-# non-validating[http://www.w3.org/TR/2004/REC-xml-20040204/#sec-conformance]
-# toolkit with an intuitive API. REXML passes 100% of the non-validating Oasis
-# tests[http://www.oasis-open.org/committees/xml-conformance/xml-test-suite.shtml],
-# and provides tree, stream, SAX2, pull, and lightweight APIs. REXML also
-# includes a full XPath[http://www.w3c.org/tr/xpath] 1.0 implementation. Since
-# Ruby 1.8, REXML is included in the standard Ruby distribution.
-#
-# Main page:: http://www.germane-software.com/software/rexml
-# Author:: Sean Russell <serATgermaneHYPHENsoftwareDOTcom>
-# Date:: 2008/019
-# Version:: 3.1.7.3
-#
-# This API documentation can be downloaded from the REXML home page, or can
-# be accessed online[http://www.germane-software.com/software/rexml_doc]
-#
-# A tutorial is available in the REXML distribution in docs/tutorial.html,
-# or can be accessed
-# online[http://www.germane-software.com/software/rexml/docs/tutorial.html]
-module REXML
- COPYRIGHT = "Copyright © 2001-2008 Sean Russell <ser@germane-software.com>"
- DATE = "2008/019"
- VERSION = "3.1.7.3"
- REVISION = %w$Revision$[1] || ''
-
- Copyright = COPYRIGHT
- Version = VERSION
-
- @@entity_expansion_text_limit = 10_240
-
- # Set the entity expansion limit. By default the limit is set to 10240.
- def self.entity_expansion_text_limit=( val )
- @@entity_expansion_text_limit = val
- end
-
- # Get the entity expansion limit. By default the limit is set to 10240.
- def self.entity_expansion_text_limit
- return @@entity_expansion_text_limit
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/sax2listener.rb b/ruby_1_9_3/lib/rexml/sax2listener.rb
deleted file mode 100644
index 6830e4483a..0000000000
--- a/ruby_1_9_3/lib/rexml/sax2listener.rb
+++ /dev/null
@@ -1,97 +0,0 @@
-module REXML
- # A template for stream parser listeners.
- # Note that the declarations (attlistdecl, elementdecl, etc) are trivially
- # processed; REXML doesn't yet handle doctype entity declarations, so you
- # have to parse them out yourself.
- # === Missing methods from SAX2
- # ignorable_whitespace
- # === Methods extending SAX2
- # +WARNING+
- # These methods are certainly going to change, until DTDs are fully
- # supported. Be aware of this.
- # start_document
- # end_document
- # doctype
- # elementdecl
- # attlistdecl
- # entitydecl
- # notationdecl
- # cdata
- # xmldecl
- # comment
- module SAX2Listener
- def start_document
- end
- def end_document
- end
- def start_prefix_mapping prefix, uri
- end
- def end_prefix_mapping prefix
- end
- def start_element uri, localname, qname, attributes
- end
- def end_element uri, localname, qname
- end
- def characters text
- end
- def processing_instruction target, data
- end
- # Handles a doctype declaration. Any attributes of the doctype which are
- # not supplied will be nil. # EG, <!DOCTYPE me PUBLIC "foo" "bar">
- # @p name the name of the doctype; EG, "me"
- # @p pub_sys "PUBLIC", "SYSTEM", or nil. EG, "PUBLIC"
- # @p long_name the supplied long name, or nil. EG, "foo"
- # @p uri the uri of the doctype, or nil. EG, "bar"
- def doctype name, pub_sys, long_name, uri
- end
- # If a doctype includes an ATTLIST declaration, it will cause this
- # method to be called. The content is the declaration itself, unparsed.
- # EG, <!ATTLIST el attr CDATA #REQUIRED> will come to this method as "el
- # attr CDATA #REQUIRED". This is the same for all of the .*decl
- # methods.
- def attlistdecl(element, pairs, contents)
- end
- # <!ELEMENT ...>
- def elementdecl content
- end
- # <!ENTITY ...>
- # The argument passed to this method is an array of the entity
- # declaration. It can be in a number of formats, but in general it
- # returns (example, result):
- # <!ENTITY % YN '"Yes"'>
- # ["%", "YN", "'\"Yes\"'", "\""]
- # <!ENTITY % YN 'Yes'>
- # ["%", "YN", "'Yes'", "s"]
- # <!ENTITY WhatHeSaid "He said %YN;">
- # ["WhatHeSaid", "\"He said %YN;\"", "YN"]
- # <!ENTITY open-hatch SYSTEM "http://www.textuality.com/boilerplate/OpenHatch.xml">
- # ["open-hatch", "SYSTEM", "\"http://www.textuality.com/boilerplate/OpenHatch.xml\""]
- # <!ENTITY open-hatch PUBLIC "-//Textuality//TEXT Standard open-hatch boilerplate//EN" "http://www.textuality.com/boilerplate/OpenHatch.xml">
- # ["open-hatch", "PUBLIC", "\"-//Textuality//TEXT Standard open-hatch boilerplate//EN\"", "\"http://www.textuality.com/boilerplate/OpenHatch.xml\""]
- # <!ENTITY hatch-pic SYSTEM "../grafix/OpenHatch.gif" NDATA gif>
- # ["hatch-pic", "SYSTEM", "\"../grafix/OpenHatch.gif\"", "\n\t\t\t\t\t\t\tNDATA gif", "gif"]
- def entitydecl name, decl
- end
- # <!NOTATION ...>
- def notationdecl content
- end
- # Called when <![CDATA[ ... ]]> is encountered in a document.
- # @p content "..."
- def cdata content
- end
- # Called when an XML PI is encountered in the document.
- # EG: <?xml version="1.0" encoding="utf"?>
- # @p version the version attribute value. EG, "1.0"
- # @p encoding the encoding attribute value, or nil. EG, "utf"
- # @p standalone the standalone attribute value, or nil. EG, nil
- # @p spaced the declaration is followed by a line break
- def xmldecl version, encoding, standalone
- end
- # Called when a comment is encountered.
- # @p comment The content of the comment
- def comment comment
- end
- def progress position
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/source.rb b/ruby_1_9_3/lib/rexml/source.rb
deleted file mode 100644
index 112393cfd4..0000000000
--- a/ruby_1_9_3/lib/rexml/source.rb
+++ /dev/null
@@ -1,267 +0,0 @@
-require 'rexml/encoding'
-
-module REXML
- # Generates Source-s. USE THIS CLASS.
- class SourceFactory
- # Generates a Source object
- # @param arg Either a String, or an IO
- # @return a Source, or nil if a bad argument was given
- def SourceFactory::create_from(arg)
- if arg.respond_to? :read and
- arg.respond_to? :readline and
- arg.respond_to? :nil? and
- arg.respond_to? :eof?
- IOSource.new(arg)
- elsif arg.respond_to? :to_str
- require 'stringio'
- IOSource.new(StringIO.new(arg))
- elsif arg.kind_of? Source
- arg
- else
- raise "#{arg.class} is not a valid input stream. It must walk \n"+
- "like either a String, an IO, or a Source."
- end
- end
- end
-
- # A Source can be searched for patterns, and wraps buffers and other
- # objects and provides consumption of text
- class Source
- include Encoding
- # The current buffer (what we're going to read next)
- attr_reader :buffer
- # The line number of the last consumed text
- attr_reader :line
- attr_reader :encoding
-
- # Constructor
- # @param arg must be a String, and should be a valid XML document
- # @param encoding if non-null, sets the encoding of the source to this
- # value, overriding all encoding detection
- def initialize(arg, encoding=nil)
- @orig = @buffer = arg
- if encoding
- self.encoding = encoding
- else
- self.encoding = check_encoding( @buffer )
- end
- @line = 0
- end
-
-
- # Inherited from Encoding
- # Overridden to support optimized en/decoding
- def encoding=(enc)
- return unless super
- @line_break = encode( '>' )
- if @encoding != 'UTF-8'
- @buffer = decode(@buffer)
- @to_utf = true
- else
- @to_utf = false
- @buffer.force_encoding ::Encoding::UTF_8
- end
- end
-
- # Scans the source for a given pattern. Note, that this is not your
- # usual scan() method. For one thing, the pattern argument has some
- # requirements; for another, the source can be consumed. You can easily
- # confuse this method. Originally, the patterns were easier
- # to construct and this method more robust, because this method
- # generated search regexes on the fly; however, this was
- # computationally expensive and slowed down the entire REXML package
- # considerably, since this is by far the most commonly called method.
- # @param pattern must be a Regexp, and must be in the form of
- # /^\s*(#{your pattern, with no groups})(.*)/. The first group
- # will be returned; the second group is used if the consume flag is
- # set.
- # @param consume if true, the pattern returned will be consumed, leaving
- # everything after it in the Source.
- # @return the pattern, if found, or nil if the Source is empty or the
- # pattern is not found.
- def scan(pattern, cons=false)
- return nil if @buffer.nil?
- rv = @buffer.scan(pattern)
- @buffer = $' if cons and rv.size>0
- rv
- end
-
- def read
- end
-
- def consume( pattern )
- @buffer = $' if pattern.match( @buffer )
- end
-
- def match_to( char, pattern )
- return pattern.match(@buffer)
- end
-
- def match_to_consume( char, pattern )
- md = pattern.match(@buffer)
- @buffer = $'
- return md
- end
-
- def match(pattern, cons=false)
- md = pattern.match(@buffer)
- @buffer = $' if cons and md
- return md
- end
-
- # @return true if the Source is exhausted
- def empty?
- @buffer == ""
- end
-
- def position
- @orig.index( @buffer )
- end
-
- # @return the current line in the source
- def current_line
- lines = @orig.split
- res = lines.grep @buffer[0..30]
- res = res[-1] if res.kind_of? Array
- lines.index( res ) if res
- end
- end
-
- # A Source that wraps an IO. See the Source class for method
- # documentation
- class IOSource < Source
- #attr_reader :block_size
-
- # block_size has been deprecated
- def initialize(arg, block_size=500, encoding=nil)
- @er_source = @source = arg
- @to_utf = false
-
- # Determining the encoding is a deceptively difficult issue to resolve.
- # First, we check the first two bytes for UTF-16. Then we
- # assume that the encoding is at least ASCII enough for the '>', and
- # we read until we get one of those. This gives us the XML declaration,
- # if there is one. If there isn't one, the file MUST be UTF-8, as per
- # the XML spec. If there is one, we can determine the encoding from
- # it.
- @buffer = ""
- str = @source.read( 2 ) || ''
- if encoding
- self.encoding = encoding
- elsif str[0,2] == "\xfe\xff"
- @line_break = "\000>"
- elsif str[0,2] == "\xff\xfe"
- @line_break = ">\000"
- elsif str[0,2] == "\xef\xbb"
- str += @source.read(1)
- str = '' if (str[2,1] == "\xBF")
- @line_break = ">"
- else
- @line_break = ">"
- end
- super( @source.eof? ? str : str+@source.readline( @line_break ) )
-
- if !@to_utf and
- @buffer.respond_to?(:force_encoding) and
- @source.respond_to?(:external_encoding) and
- @source.external_encoding != ::Encoding::UTF_8
- @force_utf8 = true
- else
- @force_utf8 = false
- end
- end
-
- def scan(pattern, cons=false)
- rv = super
- # You'll notice that this next section is very similar to the same
- # section in match(), but just a liiittle different. This is
- # because it is a touch faster to do it this way with scan()
- # than the way match() does it; enough faster to warrent duplicating
- # some code
- if rv.size == 0
- until @buffer =~ pattern or @source.nil?
- begin
- @buffer << readline
- rescue Iconv::IllegalSequence
- raise
- rescue
- @source = nil
- end
- end
- rv = super
- end
- rv.taint
- rv
- end
-
- def read
- begin
- @buffer << readline
- rescue Exception, NameError
- @source = nil
- end
- end
-
- def consume( pattern )
- match( pattern, true )
- end
-
- def match( pattern, cons=false )
- rv = pattern.match(@buffer)
- @buffer = $' if cons and rv
- while !rv and @source
- begin
- @buffer << readline
- rv = pattern.match(@buffer)
- @buffer = $' if cons and rv
- rescue
- @source = nil
- end
- end
- rv.taint
- rv
- end
-
- def empty?
- super and ( @source.nil? || @source.eof? )
- end
-
- def position
- @er_source.pos rescue 0
- end
-
- # @return the current line in the source
- def current_line
- begin
- pos = @er_source.pos # The byte position in the source
- lineno = @er_source.lineno # The XML < position in the source
- @er_source.rewind
- line = 0 # The \r\n position in the source
- begin
- while @er_source.pos < pos
- @er_source.readline
- line += 1
- end
- rescue
- end
- rescue IOError
- pos = -1
- line = -1
- end
- [pos, lineno, line]
- end
-
- private
- def readline
- str = @source.readline(@line_break)
- return nil if str.nil?
-
- if @to_utf
- decode(str)
- else
- str.force_encoding(::Encoding::UTF_8) if @force_utf8
- str
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/streamlistener.rb b/ruby_1_9_3/lib/rexml/streamlistener.rb
deleted file mode 100644
index 619c529578..0000000000
--- a/ruby_1_9_3/lib/rexml/streamlistener.rb
+++ /dev/null
@@ -1,92 +0,0 @@
-module REXML
- # A template for stream parser listeners.
- # Note that the declarations (attlistdecl, elementdecl, etc) are trivially
- # processed; REXML doesn't yet handle doctype entity declarations, so you
- # have to parse them out yourself.
- module StreamListener
- # Called when a tag is encountered.
- # @p name the tag name
- # @p attrs an array of arrays of attribute/value pairs, suitable for
- # use with assoc or rassoc. IE, <tag attr1="value1" attr2="value2">
- # will result in
- # tag_start( "tag", # [["attr1","value1"],["attr2","value2"]])
- def tag_start name, attrs
- end
- # Called when the end tag is reached. In the case of <tag/>, tag_end
- # will be called immidiately after tag_start
- # @p the name of the tag
- def tag_end name
- end
- # Called when text is encountered in the document
- # @p text the text content.
- def text text
- end
- # Called when an instruction is encountered. EG: <?xsl sheet='foo'?>
- # @p name the instruction name; in the example, "xsl"
- # @p instruction the rest of the instruction. In the example,
- # "sheet='foo'"
- def instruction name, instruction
- end
- # Called when a comment is encountered.
- # @p comment The content of the comment
- def comment comment
- end
- # Handles a doctype declaration. Any attributes of the doctype which are
- # not supplied will be nil. # EG, <!DOCTYPE me PUBLIC "foo" "bar">
- # @p name the name of the doctype; EG, "me"
- # @p pub_sys "PUBLIC", "SYSTEM", or nil. EG, "PUBLIC"
- # @p long_name the supplied long name, or nil. EG, "foo"
- # @p uri the uri of the doctype, or nil. EG, "bar"
- def doctype name, pub_sys, long_name, uri
- end
- # Called when the doctype is done
- def doctype_end
- end
- # If a doctype includes an ATTLIST declaration, it will cause this
- # method to be called. The content is the declaration itself, unparsed.
- # EG, <!ATTLIST el attr CDATA #REQUIRED> will come to this method as "el
- # attr CDATA #REQUIRED". This is the same for all of the .*decl
- # methods.
- def attlistdecl element_name, attributes, raw_content
- end
- # <!ELEMENT ...>
- def elementdecl content
- end
- # <!ENTITY ...>
- # The argument passed to this method is an array of the entity
- # declaration. It can be in a number of formats, but in general it
- # returns (example, result):
- # <!ENTITY % YN '"Yes"'>
- # ["%", "YN", "'\"Yes\"'", "\""]
- # <!ENTITY % YN 'Yes'>
- # ["%", "YN", "'Yes'", "s"]
- # <!ENTITY WhatHeSaid "He said %YN;">
- # ["WhatHeSaid", "\"He said %YN;\"", "YN"]
- # <!ENTITY open-hatch SYSTEM "http://www.textuality.com/boilerplate/OpenHatch.xml">
- # ["open-hatch", "SYSTEM", "\"http://www.textuality.com/boilerplate/OpenHatch.xml\""]
- # <!ENTITY open-hatch PUBLIC "-//Textuality//TEXT Standard open-hatch boilerplate//EN" "http://www.textuality.com/boilerplate/OpenHatch.xml">
- # ["open-hatch", "PUBLIC", "\"-//Textuality//TEXT Standard open-hatch boilerplate//EN\"", "\"http://www.textuality.com/boilerplate/OpenHatch.xml\""]
- # <!ENTITY hatch-pic SYSTEM "../grafix/OpenHatch.gif" NDATA gif>
- # ["hatch-pic", "SYSTEM", "\"../grafix/OpenHatch.gif\"", "\n\t\t\t\t\t\t\tNDATA gif", "gif"]
- def entitydecl content
- end
- # <!NOTATION ...>
- def notationdecl content
- end
- # Called when %foo; is encountered in a doctype declaration.
- # @p content "foo"
- def entity content
- end
- # Called when <![CDATA[ ... ]]> is encountered in a document.
- # @p content "..."
- def cdata content
- end
- # Called when an XML PI is encountered in the document.
- # EG: <?xml version="1.0" encoding="utf"?>
- # @p version the version attribute value. EG, "1.0"
- # @p encoding the encoding attribute value, or nil. EG, "utf"
- # @p standalone the standalone attribute value, or nil. EG, nil
- def xmldecl version, encoding, standalone
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/syncenumerator.rb b/ruby_1_9_3/lib/rexml/syncenumerator.rb
deleted file mode 100644
index 11609bdf3d..0000000000
--- a/ruby_1_9_3/lib/rexml/syncenumerator.rb
+++ /dev/null
@@ -1,32 +0,0 @@
-module REXML
- class SyncEnumerator
- include Enumerable
-
- # Creates a new SyncEnumerator which enumerates rows of given
- # Enumerable objects.
- def initialize(*enums)
- @gens = enums
- @length = @gens.collect {|x| x.size }.max
- end
-
- # Returns the number of enumerated Enumerable objects, i.e. the size
- # of each row.
- def size
- @gens.size
- end
-
- # Returns the number of enumerated Enumerable objects, i.e. the size
- # of each row.
- def length
- @gens.length
- end
-
- # Enumerates rows of the Enumerable objects.
- def each
- @length.times {|i|
- yield @gens.collect {|x| x[i]}
- }
- self
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/text.rb b/ruby_1_9_3/lib/rexml/text.rb
deleted file mode 100644
index 7b00b0f104..0000000000
--- a/ruby_1_9_3/lib/rexml/text.rb
+++ /dev/null
@@ -1,415 +0,0 @@
-require 'rexml/rexml'
-require 'rexml/entity'
-require 'rexml/doctype'
-require 'rexml/child'
-require 'rexml/doctype'
-require 'rexml/parseexception'
-
-module REXML
- # Represents text nodes in an XML document
- class Text < Child
- include Comparable
- # The order in which the substitutions occur
- SPECIALS = [ /&(?!#?[\w-]+;)/u, /</u, />/u, /"/u, /'/u, /\r/u ]
- SUBSTITUTES = ['&amp;', '&lt;', '&gt;', '&quot;', '&apos;', '&#13;']
- # Characters which are substituted in written strings
- SLAICEPS = [ '<', '>', '"', "'", '&' ]
- SETUTITSBUS = [ /&lt;/u, /&gt;/u, /&quot;/u, /&apos;/u, /&amp;/u ]
-
- # If +raw+ is true, then REXML leaves the value alone
- attr_accessor :raw
-
- NEEDS_A_SECOND_CHECK = /(<|&((#{Entity::NAME});|(#0*((?:\d+)|(?:x[a-fA-F0-9]+)));)?)/um
- NUMERICENTITY = /&#0*((?:\d+)|(?:x[a-fA-F0-9]+));/
- VALID_CHAR = [
- 0x9, 0xA, 0xD,
- (0x20..0xD7FF),
- (0xE000..0xFFFD),
- (0x10000..0x10FFFF)
- ]
-
- if String.method_defined? :encode
- VALID_XML_CHARS = Regexp.new('^['+
- VALID_CHAR.map { |item|
- case item
- when Fixnum
- [item].pack('U').force_encoding('utf-8')
- when Range
- [item.first, '-'.ord, item.last].pack('UUU').force_encoding('utf-8')
- end
- }.join +
- ']*$')
- else
- VALID_XML_CHARS = /^(
- [\x09\x0A\x0D\x20-\x7E] # ASCII
- | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
- | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
- | [\xE1-\xEC\xEE][\x80-\xBF]{2} # straight 3-byte
- | \xEF[\x80-\xBE]{2} #
- | \xEF\xBF[\x80-\xBD] # excluding U+fffe and U+ffff
- | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
- | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
- | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
- | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
- )*$/nx;
- end
-
- # Constructor
- # +arg+ if a String, the content is set to the String. If a Text,
- # the object is shallowly cloned.
- #
- # +respect_whitespace+ (boolean, false) if true, whitespace is
- # respected
- #
- # +parent+ (nil) if this is a Parent object, the parent
- # will be set to this.
- #
- # +raw+ (nil) This argument can be given three values.
- # If true, then the value of used to construct this object is expected to
- # contain no unescaped XML markup, and REXML will not change the text. If
- # this value is false, the string may contain any characters, and REXML will
- # escape any and all defined entities whose values are contained in the
- # text. If this value is nil (the default), then the raw value of the
- # parent will be used as the raw value for this node. If there is no raw
- # value for the parent, and no value is supplied, the default is false.
- # Use this field if you have entities defined for some text, and you don't
- # want REXML to escape that text in output.
- # Text.new( "<&", false, nil, false ) #-> "&lt;&amp;"
- # Text.new( "&lt;&amp;", false, nil, false ) #-> "&amp;lt;&amp;amp;"
- # Text.new( "<&", false, nil, true ) #-> Parse exception
- # Text.new( "&lt;&amp;", false, nil, true ) #-> "&lt;&amp;"
- # # Assume that the entity "s" is defined to be "sean"
- # # and that the entity "r" is defined to be "russell"
- # Text.new( "sean russell" ) #-> "&s; &r;"
- # Text.new( "sean russell", false, nil, true ) #-> "sean russell"
- #
- # +entity_filter+ (nil) This can be an array of entities to match in the
- # supplied text. This argument is only useful if +raw+ is set to false.
- # Text.new( "sean russell", false, nil, false, ["s"] ) #-> "&s; russell"
- # Text.new( "sean russell", false, nil, true, ["s"] ) #-> "sean russell"
- # In the last example, the +entity_filter+ argument is ignored.
- #
- # +illegal+ INTERNAL USE ONLY
- def initialize(arg, respect_whitespace=false, parent=nil, raw=nil,
- entity_filter=nil, illegal=NEEDS_A_SECOND_CHECK )
-
- @raw = false
- @parent = nil
-
- if parent
- super( parent )
- @raw = parent.raw
- end
-
- @raw = raw unless raw.nil?
- @entity_filter = entity_filter
- @normalized = @unnormalized = nil
-
- if arg.kind_of? String
- @string = arg.dup
- @string.squeeze!(" \n\t") unless respect_whitespace
- elsif arg.kind_of? Text
- @string = arg.to_s
- @raw = arg.raw
- elsif
- raise "Illegal argument of type #{arg.type} for Text constructor (#{arg})"
- end
-
- @string.gsub!( /\r\n?/, "\n" )
-
- Text.check(@string, illegal, doctype) if @raw
- end
-
- def parent= parent
- super(parent)
- Text.check(@string, NEEDS_A_SECOND_CHECK, doctype) if @raw and @parent
- end
-
- # check for illegal characters
- def Text.check string, pattern, doctype
-
- # illegal anywhere
- if string !~ VALID_XML_CHARS
- if String.method_defined? :encode
- string.chars.each do |c|
- case c.ord
- when *VALID_CHAR
- else
- raise "Illegal character #{c.inspect} in raw string \"#{string}\""
- end
- end
- else
- string.scan(/[\x00-\x7F]|[\x80-\xBF][\xC0-\xF0]*|[\xC0-\xF0]/n) do |c|
- case c.unpack('U')
- when *VALID_CHAR
- else
- raise "Illegal character #{c.inspect} in raw string \"#{string}\""
- end
- end
- end
- end
-
- # context sensitive
- string.scan(pattern) do
- if $1[-1] != ?;
- raise "Illegal character '#{$1}' in raw string \"#{string}\""
- elsif $1[0] == ?&
- if $5 and $5[0] == ?#
- case ($5[1] == ?x ? $5[2..-1].to_i(16) : $5[1..-1].to_i)
- when *VALID_CHAR
- else
- raise "Illegal character '#{$1}' in raw string \"#{string}\""
- end
- # FIXME: below can't work but this needs API change.
- # elsif @parent and $3 and !SUBSTITUTES.include?($1)
- # if !doctype or !doctype.entities.has_key?($3)
- # raise "Undeclared entity '#{$1}' in raw string \"#{string}\""
- # end
- end
- end
- end
- end
-
- def node_type
- :text
- end
-
- def empty?
- @string.size==0
- end
-
-
- def clone
- return Text.new(self)
- end
-
-
- # Appends text to this text node. The text is appended in the +raw+ mode
- # of this text node.
- def <<( to_append )
- @string << to_append.gsub( /\r\n?/, "\n" )
- end
-
-
- # +other+ a String or a Text
- # +returns+ the result of (to_s <=> arg.to_s)
- def <=>( other )
- to_s() <=> other.to_s
- end
-
- def doctype
- if @parent
- doc = @parent.document
- doc.doctype if doc
- end
- end
-
- REFERENCE = /#{Entity::REFERENCE}/
- # Returns the string value of this text node. This string is always
- # escaped, meaning that it is a valid XML text node string, and all
- # entities that can be escaped, have been inserted. This method respects
- # the entity filter set in the constructor.
- #
- # # Assume that the entity "s" is defined to be "sean", and that the
- # # entity "r" is defined to be "russell"
- # t = Text.new( "< & sean russell", false, nil, false, ['s'] )
- # t.to_s #-> "&lt; &amp; &s; russell"
- # t = Text.new( "< & &s; russell", false, nil, false )
- # t.to_s #-> "&lt; &amp; &s; russell"
- # u = Text.new( "sean russell", false, nil, true )
- # u.to_s #-> "sean russell"
- def to_s
- return @string if @raw
- return @normalized if @normalized
-
- @normalized = Text::normalize( @string, doctype, @entity_filter )
- end
-
- def inspect
- @string.inspect
- end
-
- # Returns the string value of this text. This is the text without
- # entities, as it might be used programmatically, or printed to the
- # console. This ignores the 'raw' attribute setting, and any
- # entity_filter.
- #
- # # Assume that the entity "s" is defined to be "sean", and that the
- # # entity "r" is defined to be "russell"
- # t = Text.new( "< & sean russell", false, nil, false, ['s'] )
- # t.value #-> "< & sean russell"
- # t = Text.new( "< & &s; russell", false, nil, false )
- # t.value #-> "< & sean russell"
- # u = Text.new( "sean russell", false, nil, true )
- # u.value #-> "sean russell"
- def value
- return @unnormalized if @unnormalized
- @unnormalized = Text::unnormalize( @string, doctype )
- end
-
- # Sets the contents of this text node. This expects the text to be
- # unnormalized. It returns self.
- #
- # e = Element.new( "a" )
- # e.add_text( "foo" ) # <a>foo</a>
- # e[0].value = "bar" # <a>bar</a>
- # e[0].value = "<a>" # <a>&lt;a&gt;</a>
- def value=( val )
- @string = val.gsub( /\r\n?/, "\n" )
- @unnormalized = nil
- @normalized = nil
- @raw = false
- end
-
- def wrap(string, width, addnewline=false)
- # Recursively wrap string at width.
- return string if string.length <= width
- place = string.rindex(' ', width) # Position in string with last ' ' before cutoff
- if addnewline then
- return "\n" + string[0,place] + "\n" + wrap(string[place+1..-1], width)
- else
- return string[0,place] + "\n" + wrap(string[place+1..-1], width)
- end
- end
-
- def indent_text(string, level=1, style="\t", indentfirstline=true)
- return string if level < 0
- new_string = ''
- string.each_line { |line|
- indent_string = style * level
- new_line = (indent_string + line).sub(/[\s]+$/,'')
- new_string << new_line
- }
- new_string.strip! unless indentfirstline
- return new_string
- end
-
- # == DEPRECATED
- # See REXML::Formatters
- #
- def write( writer, indent=-1, transitive=false, ie_hack=false )
- Kernel.warn("#{self.class.name}.write is deprecated. See REXML::Formatters")
- formatter = if indent > -1
- REXML::Formatters::Pretty.new( indent )
- else
- REXML::Formatters::Default.new
- end
- formatter.write( self, writer )
- end
-
- # FIXME
- # This probably won't work properly
- def xpath
- path = @parent.xpath
- path += "/text()"
- return path
- end
-
- # Writes out text, substituting special characters beforehand.
- # +out+ A String, IO, or any other object supporting <<( String )
- # +input+ the text to substitute and the write out
- #
- # z=utf8.unpack("U*")
- # ascOut=""
- # z.each{|r|
- # if r < 0x100
- # ascOut.concat(r.chr)
- # else
- # ascOut.concat(sprintf("&#x%x;", r))
- # end
- # }
- # puts ascOut
- def write_with_substitution out, input
- copy = input.clone
- # Doing it like this rather than in a loop improves the speed
- copy.gsub!( SPECIALS[0], SUBSTITUTES[0] )
- copy.gsub!( SPECIALS[1], SUBSTITUTES[1] )
- copy.gsub!( SPECIALS[2], SUBSTITUTES[2] )
- copy.gsub!( SPECIALS[3], SUBSTITUTES[3] )
- copy.gsub!( SPECIALS[4], SUBSTITUTES[4] )
- copy.gsub!( SPECIALS[5], SUBSTITUTES[5] )
- out << copy
- end
-
- # Reads text, substituting entities
- def Text::read_with_substitution( input, illegal=nil )
- copy = input.clone
-
- if copy =~ illegal
- raise ParseException.new( "malformed text: Illegal character #$& in \"#{copy}\"" )
- end if illegal
-
- copy.gsub!( /\r\n?/, "\n" )
- if copy.include? ?&
- copy.gsub!( SETUTITSBUS[0], SLAICEPS[0] )
- copy.gsub!( SETUTITSBUS[1], SLAICEPS[1] )
- copy.gsub!( SETUTITSBUS[2], SLAICEPS[2] )
- copy.gsub!( SETUTITSBUS[3], SLAICEPS[3] )
- copy.gsub!( SETUTITSBUS[4], SLAICEPS[4] )
- copy.gsub!( /&#0*((?:\d+)|(?:x[a-f0-9]+));/ ) {
- m=$1
- #m='0' if m==''
- m = "0#{m}" if m[0] == ?x
- [Integer(m)].pack('U*')
- }
- end
- copy
- end
-
- EREFERENCE = /&(?!#{Entity::NAME};)/
- # Escapes all possible entities
- def Text::normalize( input, doctype=nil, entity_filter=nil )
- copy = input.to_s
- # Doing it like this rather than in a loop improves the speed
- #copy = copy.gsub( EREFERENCE, '&amp;' )
- copy = copy.gsub( "&", "&amp;" )
- if doctype
- # Replace all ampersands that aren't part of an entity
- doctype.entities.each_value do |entity|
- copy = copy.gsub( entity.value,
- "&#{entity.name};" ) if entity.value and
- not( entity_filter and entity_filter.include?(entity) )
- end
- else
- # Replace all ampersands that aren't part of an entity
- DocType::DEFAULT_ENTITIES.each_value do |entity|
- copy = copy.gsub(entity.value, "&#{entity.name};" )
- end
- end
- copy
- end
-
- # Unescapes all possible entities
- def Text::unnormalize( string, doctype=nil, filter=nil, illegal=nil )
- sum = 0
- string.gsub( /\r\n?/, "\n" ).gsub( REFERENCE ) {
- s = Text.expand($&, doctype, filter)
- if sum + s.bytesize > REXML.entity_expansion_text_limit
- raise "entity expansion has grown too large"
- else
- sum += s.bytesize
- end
- s
- }
- end
-
- def Text.expand(ref, doctype, filter)
- if ref[1] == ?#
- if ref[2] == ?x
- [ref[3...-1].to_i(16)].pack('U*')
- else
- [ref[2...-1].to_i].pack('U*')
- end
- elsif ref == '&amp;'
- '&'
- elsif filter and filter.include?( ref[1...-1] )
- ref
- elsif doctype
- doctype.entity( ref[1...-1] ) or ref
- else
- entity_value = DocType::DEFAULT_ENTITIES[ ref[1...-1] ]
- entity_value ? entity_value.value : ref
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/undefinednamespaceexception.rb b/ruby_1_9_3/lib/rexml/undefinednamespaceexception.rb
deleted file mode 100644
index 8ebfdfd0a9..0000000000
--- a/ruby_1_9_3/lib/rexml/undefinednamespaceexception.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-require 'rexml/parseexception'
-module REXML
- class UndefinedNamespaceException < ParseException
- def initialize( prefix, source, parser )
- super( "Undefined prefix #{prefix} found" )
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/validation/relaxng.rb b/ruby_1_9_3/lib/rexml/validation/relaxng.rb
deleted file mode 100644
index 2441901d7b..0000000000
--- a/ruby_1_9_3/lib/rexml/validation/relaxng.rb
+++ /dev/null
@@ -1,559 +0,0 @@
-require "rexml/validation/validation"
-require "rexml/parsers/baseparser"
-
-module REXML
- module Validation
- # Implemented:
- # * empty
- # * element
- # * attribute
- # * text
- # * optional
- # * choice
- # * oneOrMore
- # * zeroOrMore
- # * group
- # * value
- # * interleave
- # * mixed
- # * ref
- # * grammar
- # * start
- # * define
- #
- # Not implemented:
- # * data
- # * param
- # * include
- # * externalRef
- # * notAllowed
- # * anyName
- # * nsName
- # * except
- # * name
- class RelaxNG
- include Validator
-
- INFINITY = 1.0 / 0.0
- EMPTY = Event.new( nil )
- TEXT = [:start_element, "text"]
- attr_accessor :current
- attr_accessor :count
- attr_reader :references
-
- # FIXME: Namespaces
- def initialize source
- parser = REXML::Parsers::BaseParser.new( source )
-
- @count = 0
- @references = {}
- @root = @current = Sequence.new(self)
- @root.previous = true
- states = [ @current ]
- begin
- event = parser.pull
- case event[0]
- when :start_element
- case event[1]
- when "empty"
- when "element", "attribute", "text", "value"
- states[-1] << event
- when "optional"
- states << Optional.new( self )
- states[-2] << states[-1]
- when "choice"
- states << Choice.new( self )
- states[-2] << states[-1]
- when "oneOrMore"
- states << OneOrMore.new( self )
- states[-2] << states[-1]
- when "zeroOrMore"
- states << ZeroOrMore.new( self )
- states[-2] << states[-1]
- when "group"
- states << Sequence.new( self )
- states[-2] << states[-1]
- when "interleave"
- states << Interleave.new( self )
- states[-2] << states[-1]
- when "mixed"
- states << Interleave.new( self )
- states[-2] << states[-1]
- states[-1] << TEXT
- when "define"
- states << [ event[2]["name"] ]
- when "ref"
- states[-1] << Ref.new( event[2]["name"] )
- when "anyName"
- states << AnyName.new( self )
- states[-2] << states[-1]
- when "nsName"
- when "except"
- when "name"
- when "data"
- when "param"
- when "include"
- when "grammar"
- when "start"
- when "externalRef"
- when "notAllowed"
- end
- when :end_element
- case event[1]
- when "element", "attribute"
- states[-1] << event
- when "zeroOrMore", "oneOrMore", "choice", "optional",
- "interleave", "group", "mixed"
- states.pop
- when "define"
- ref = states.pop
- @references[ ref.shift ] = ref
- #when "empty"
- end
- when :end_document
- states[-1] << event
- when :text
- states[-1] << event
- end
- end while event[0] != :end_document
- end
-
- def receive event
- validate( event )
- end
- end
-
- class State
- def initialize( context )
- @previous = []
- @events = []
- @current = 0
- @count = context.count += 1
- @references = context.references
- @value = false
- end
-
- def reset
- return if @current == 0
- @current = 0
- @events.each {|s| s.reset if s.kind_of? State }
- end
-
- def previous=( previous )
- @previous << previous
- end
-
- def next( event )
- #print "In next with #{event.inspect}. "
- #puts "Next (#@current) is #{@events[@current]}"
- #p @previous
- return @previous.pop.next( event ) if @events[@current].nil?
- expand_ref_in( @events, @current ) if @events[@current].class == Ref
- if ( @events[@current].kind_of? State )
- @current += 1
- @events[@current-1].previous = self
- return @events[@current-1].next( event )
- end
- #puts "Current isn't a state"
- if ( @events[@current].matches?(event) )
- @current += 1
- if @events[@current].nil?
- #puts "#{inspect[0,5]} 1RETURNING #{@previous.inspect[0,5]}"
- return @previous.pop
- elsif @events[@current].kind_of? State
- @current += 1
- #puts "#{inspect[0,5]} 2RETURNING (#{@current-1}) #{@events[@current-1].inspect[0,5]}; on return, next is #{@events[@current]}"
- @events[@current-1].previous = self
- return @events[@current-1]
- else
- #puts "#{inspect[0,5]} RETURNING self w/ next(#@current) = #{@events[@current]}"
- return self
- end
- else
- return nil
- end
- end
-
- def to_s
- # Abbreviated:
- self.class.name =~ /(?:::)(\w)\w+$/
- # Full:
- #self.class.name =~ /(?:::)(\w+)$/
- "#$1.#@count"
- end
-
- def inspect
- "< #{to_s} #{@events.collect{|e|
- pre = e == @events[@current] ? '#' : ''
- pre + e.inspect unless self == e
- }.join(', ')} >"
- end
-
- def expected
- return [@events[@current]]
- end
-
- def <<( event )
- add_event_to_arry( @events, event )
- end
-
-
- protected
- def expand_ref_in( arry, ind )
- new_events = []
- @references[ arry[ind].to_s ].each{ |evt|
- add_event_to_arry(new_events,evt)
- }
- arry[ind,1] = new_events
- end
-
- def add_event_to_arry( arry, evt )
- evt = generate_event( evt )
- if evt.kind_of? String
- arry[-1].event_arg = evt if arry[-1].kind_of? Event and @value
- @value = false
- else
- arry << evt
- end
- end
-
- def generate_event( event )
- return event if event.kind_of? State or event.class == Ref
- evt = nil
- arg = nil
- case event[0]
- when :start_element
- case event[1]
- when "element"
- evt = :start_element
- arg = event[2]["name"]
- when "attribute"
- evt = :start_attribute
- arg = event[2]["name"]
- when "text"
- evt = :text
- when "value"
- evt = :text
- @value = true
- end
- when :text
- return event[1]
- when :end_document
- return Event.new( event[0] )
- else # then :end_element
- case event[1]
- when "element"
- evt = :end_element
- when "attribute"
- evt = :end_attribute
- end
- end
- return Event.new( evt, arg )
- end
- end
-
-
- class Sequence < State
- def matches?(event)
- @events[@current].matches?( event )
- end
- end
-
-
- class Optional < State
- def next( event )
- if @current == 0
- rv = super
- return rv if rv
- @prior = @previous.pop
- return @prior.next( event )
- end
- super
- end
-
- def matches?(event)
- @events[@current].matches?(event) ||
- (@current == 0 and @previous[-1].matches?(event))
- end
-
- def expected
- return [ @prior.expected, @events[0] ].flatten if @current == 0
- return [@events[@current]]
- end
- end
-
-
- class ZeroOrMore < Optional
- def next( event )
- expand_ref_in( @events, @current ) if @events[@current].class == Ref
- if ( @events[@current].matches?(event) )
- @current += 1
- if @events[@current].nil?
- @current = 0
- return self
- elsif @events[@current].kind_of? State
- @current += 1
- @events[@current-1].previous = self
- return @events[@current-1]
- else
- return self
- end
- else
- @prior = @previous.pop
- return @prior.next( event ) if @current == 0
- return nil
- end
- end
-
- def expected
- return [ @prior.expected, @events[0] ].flatten if @current == 0
- return [@events[@current]]
- end
- end
-
-
- class OneOrMore < State
- def initialize context
- super
- @ord = 0
- end
-
- def reset
- super
- @ord = 0
- end
-
- def next( event )
- expand_ref_in( @events, @current ) if @events[@current].class == Ref
- if ( @events[@current].matches?(event) )
- @current += 1
- @ord += 1
- if @events[@current].nil?
- @current = 0
- return self
- elsif @events[@current].kind_of? State
- @current += 1
- @events[@current-1].previous = self
- return @events[@current-1]
- else
- return self
- end
- else
- return @previous.pop.next( event ) if @current == 0 and @ord > 0
- return nil
- end
- end
-
- def matches?( event )
- @events[@current].matches?(event) ||
- (@current == 0 and @ord > 0 and @previous[-1].matches?(event))
- end
-
- def expected
- if @current == 0 and @ord > 0
- return [@previous[-1].expected, @events[0]].flatten
- else
- return [@events[@current]]
- end
- end
- end
-
-
- class Choice < State
- def initialize context
- super
- @choices = []
- end
-
- def reset
- super
- @events = []
- @choices.each { |c| c.each { |s| s.reset if s.kind_of? State } }
- end
-
- def <<( event )
- add_event_to_arry( @choices, event )
- end
-
- def next( event )
- # Make the choice if we haven't
- if @events.size == 0
- c = 0 ; max = @choices.size
- while c < max
- if @choices[c][0].class == Ref
- expand_ref_in( @choices[c], 0 )
- @choices += @choices[c]
- @choices.delete( @choices[c] )
- max -= 1
- else
- c += 1
- end
- end
- @events = @choices.find { |evt| evt[0].matches? event }
- # Remove the references
- # Find the events
- end
- #puts "In next with #{event.inspect}."
- #puts "events is #{@events.inspect}"
- unless @events
- @events = []
- return nil
- end
- #puts "current = #@current"
- super
- end
-
- def matches?( event )
- return @events[@current].matches?( event ) if @events.size > 0
- !@choices.find{|evt| evt[0].matches?(event)}.nil?
- end
-
- def expected
- #puts "IN CHOICE EXPECTED"
- #puts "EVENTS = #{@events.inspect}"
- return [@events[@current]] if @events.size > 0
- return @choices.collect do |x|
- if x[0].kind_of? State
- x[0].expected
- else
- x[0]
- end
- end.flatten
- end
-
- def inspect
- "< #{to_s} #{@choices.collect{|e| e.collect{|f|f.to_s}.join(', ')}.join(' or ')} >"
- end
-
- protected
- def add_event_to_arry( arry, evt )
- if evt.kind_of? State or evt.class == Ref
- arry << [evt]
- elsif evt[0] == :text
- if arry[-1] and
- arry[-1][-1].kind_of?( Event ) and
- arry[-1][-1].event_type == :text and @value
-
- arry[-1][-1].event_arg = evt[1]
- @value = false
- end
- else
- arry << [] if evt[0] == :start_element
- arry[-1] << generate_event( evt )
- end
- end
- end
-
-
- class Interleave < Choice
- def initialize context
- super
- @choice = 0
- end
-
- def reset
- @choice = 0
- end
-
- def next_current( event )
- # Expand references
- c = 0 ; max = @choices.size
- while c < max
- if @choices[c][0].class == Ref
- expand_ref_in( @choices[c], 0 )
- @choices += @choices[c]
- @choices.delete( @choices[c] )
- max -= 1
- else
- c += 1
- end
- end
- @events = @choices[@choice..-1].find { |evt| evt[0].matches? event }
- @current = 0
- if @events
- # reorder the choices
- old = @choices[@choice]
- idx = @choices.index( @events )
- @choices[@choice] = @events
- @choices[idx] = old
- @choice += 1
- end
-
- #puts "In next with #{event.inspect}."
- #puts "events is #{@events.inspect}"
- @events = [] unless @events
- end
-
-
- def next( event )
- # Find the next series
- next_current(event) unless @events[@current]
- return nil unless @events[@current]
-
- expand_ref_in( @events, @current ) if @events[@current].class == Ref
- #puts "In next with #{event.inspect}."
- #puts "Next (#@current) is #{@events[@current]}"
- if ( @events[@current].kind_of? State )
- @current += 1
- @events[@current-1].previous = self
- return @events[@current-1].next( event )
- end
- #puts "Current isn't a state"
- return @previous.pop.next( event ) if @events[@current].nil?
- if ( @events[@current].matches?(event) )
- @current += 1
- if @events[@current].nil?
- #puts "#{inspect[0,5]} 1RETURNING self" unless @choices[@choice].nil?
- return self unless @choices[@choice].nil?
- #puts "#{inspect[0,5]} 1RETURNING #{@previous[-1].inspect[0,5]}"
- return @previous.pop
- elsif @events[@current].kind_of? State
- @current += 1
- #puts "#{inspect[0,5]} 2RETURNING (#{@current-1}) #{@events[@current-1].inspect[0,5]}; on return, next is #{@events[@current]}"
- @events[@current-1].previous = self
- return @events[@current-1]
- else
- #puts "#{inspect[0,5]} RETURNING self w/ next(#@current) = #{@events[@current]}"
- return self
- end
- else
- return nil
- end
- end
-
- def matches?( event )
- return @events[@current].matches?( event ) if @events[@current]
- !@choices[@choice..-1].find{|evt| evt[0].matches?(event)}.nil?
- end
-
- def expected
- #puts "IN CHOICE EXPECTED"
- #puts "EVENTS = #{@events.inspect}"
- return [@events[@current]] if @events[@current]
- return @choices[@choice..-1].collect do |x|
- if x[0].kind_of? State
- x[0].expected
- else
- x[0]
- end
- end.flatten
- end
-
- def inspect
- "< #{to_s} #{@choices.collect{|e| e.collect{|f|f.to_s}.join(', ')}.join(' and ')} >"
- end
- end
-
- class Ref
- def initialize value
- @value = value
- end
- def to_s
- @value
- end
- def inspect
- "{#{to_s}}"
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/validation/validation.rb b/ruby_1_9_3/lib/rexml/validation/validation.rb
deleted file mode 100644
index 8042e5d062..0000000000
--- a/ruby_1_9_3/lib/rexml/validation/validation.rb
+++ /dev/null
@@ -1,155 +0,0 @@
-require 'rexml/validation/validationexception'
-
-module REXML
- module Validation
- module Validator
- NILEVENT = [ nil ]
- def reset
- @current = @root
- @root.reset
- @root.previous = true
- @attr_stack = []
- self
- end
- def dump
- puts @root.inspect
- end
- def validate( event )
- #puts "Current: #@current"
- #puts "Event: #{event.inspect}"
- @attr_stack = [] unless defined? @attr_stack
- match = @current.next(event)
- raise ValidationException.new( "Validation error. Expected: "+
- @current.expected.join( " or " )+" from #{@current.inspect} "+
- " but got #{Event.new( event[0], event[1] ).inspect}" ) unless match
- @current = match
-
- # Check for attributes
- case event[0]
- when :start_element
- #puts "Checking attributes"
- @attr_stack << event[2]
- begin
- sattr = [:start_attribute, nil]
- eattr = [:end_attribute]
- text = [:text, nil]
- k, = event[2].find { |key,value|
- sattr[1] = key
- #puts "Looking for #{sattr.inspect}"
- m = @current.next( sattr )
- #puts "Got #{m.inspect}"
- if m
- # If the state has text children...
- #puts "Looking for #{eattr.inspect}"
- #puts "Expect #{m.expected}"
- if m.matches?( eattr )
- #puts "Got end"
- @current = m
- else
- #puts "Didn't get end"
- text[1] = value
- #puts "Looking for #{text.inspect}"
- m = m.next( text )
- #puts "Got #{m.inspect}"
- text[1] = nil
- return false unless m
- @current = m if m
- end
- m = @current.next( eattr )
- if m
- @current = m
- true
- else
- false
- end
- else
- false
- end
- }
- event[2].delete(k) if k
- end while k
- when :end_element
- attrs = @attr_stack.pop
- raise ValidationException.new( "Validation error. Illegal "+
- " attributes: #{attrs.inspect}") if attrs.length > 0
- end
- end
- end
-
- class Event
- def initialize(event_type, event_arg=nil )
- @event_type = event_type
- @event_arg = event_arg
- end
-
- attr_reader :event_type
- attr_accessor :event_arg
-
- def done?
- @done
- end
-
- def single?
- return (@event_type != :start_element and @event_type != :start_attribute)
- end
-
- def matches?( event )
- #puts "#@event_type =? #{event[0]} && #@event_arg =? #{event[1]} "
- return false unless event[0] == @event_type
- case event[0]
- when nil
- return true
- when :start_element
- return true if event[1] == @event_arg
- when :end_element
- return true
- when :start_attribute
- return true if event[1] == @event_arg
- when :end_attribute
- return true
- when :end_document
- return true
- when :text
- return (@event_arg.nil? or @event_arg == event[1])
-=begin
- when :processing_instruction
- false
- when :xmldecl
- false
- when :start_doctype
- false
- when :end_doctype
- false
- when :externalentity
- false
- when :elementdecl
- false
- when :entity
- false
- when :attlistdecl
- false
- when :notationdecl
- false
- when :end_doctype
- false
-=end
- else
- false
- end
- end
-
- def ==( other )
- return false unless other.kind_of? Event
- @event_type == other.event_type and @event_arg == other.event_arg
- end
-
- def to_s
- inspect
- end
-
- def inspect
- "#{@event_type.inspect}( #@event_arg )"
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/validation/validationexception.rb b/ruby_1_9_3/lib/rexml/validation/validationexception.rb
deleted file mode 100644
index 4723d9e4d3..0000000000
--- a/ruby_1_9_3/lib/rexml/validation/validationexception.rb
+++ /dev/null
@@ -1,9 +0,0 @@
-module REXML
- module Validation
- class ValidationException < RuntimeError
- def initialize msg
- super
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/xmldecl.rb b/ruby_1_9_3/lib/rexml/xmldecl.rb
deleted file mode 100644
index 361e4b7106..0000000000
--- a/ruby_1_9_3/lib/rexml/xmldecl.rb
+++ /dev/null
@@ -1,119 +0,0 @@
-require 'rexml/encoding'
-require 'rexml/source'
-
-module REXML
- # NEEDS DOCUMENTATION
- class XMLDecl < Child
- include Encoding
-
- DEFAULT_VERSION = "1.0";
- DEFAULT_ENCODING = "UTF-8";
- DEFAULT_STANDALONE = "no";
- START = '<\?xml';
- STOP = '\?>';
-
- attr_accessor :version, :standalone
- attr_reader :writeencoding, :writethis
-
- def initialize(version=DEFAULT_VERSION, encoding=nil, standalone=nil)
- @writethis = true
- @writeencoding = !encoding.nil?
- if version.kind_of? XMLDecl
- super()
- @version = version.version
- self.encoding = version.encoding
- @writeencoding = version.writeencoding
- @standalone = version.standalone
- else
- super()
- @version = version
- self.encoding = encoding
- @standalone = standalone
- end
- @version = DEFAULT_VERSION if @version.nil?
- end
-
- def clone
- XMLDecl.new(self)
- end
-
- # indent::
- # Ignored. There must be no whitespace before an XML declaration
- # transitive::
- # Ignored
- # ie_hack::
- # Ignored
- def write(writer, indent=-1, transitive=false, ie_hack=false)
- return nil unless @writethis or writer.kind_of? Output
- writer << START.sub(/\\/u, '')
- if writer.kind_of? Output
- writer << " #{content writer.encoding}"
- else
- writer << " #{content encoding}"
- end
- writer << STOP.sub(/\\/u, '')
- end
-
- def ==( other )
- other.kind_of?(XMLDecl) and
- other.version == @version and
- other.encoding == self.encoding and
- other.standalone == @standalone
- end
-
- def xmldecl version, encoding, standalone
- @version = version
- self.encoding = encoding
- @standalone = standalone
- end
-
- def node_type
- :xmldecl
- end
-
- alias :stand_alone? :standalone
- alias :old_enc= :encoding=
-
- def encoding=( enc )
- if enc.nil?
- self.old_enc = "UTF-8"
- @writeencoding = false
- else
- self.old_enc = enc
- @writeencoding = true
- end
- self.dowrite
- end
-
- # Only use this if you do not want the XML declaration to be written;
- # this object is ignored by the XML writer. Otherwise, instantiate your
- # own XMLDecl and add it to the document.
- #
- # Note that XML 1.1 documents *must* include an XML declaration
- def XMLDecl.default
- rv = XMLDecl.new( "1.0" )
- rv.nowrite
- rv
- end
-
- def nowrite
- @writethis = false
- end
-
- def dowrite
- @writethis = true
- end
-
- def inspect
- START.sub(/\\/u, '') + " ... " + STOP.sub(/\\/u, '')
- end
-
- private
- def content(enc)
- rv = "version='#@version'"
- rv << " encoding='#{enc}'" if @writeencoding || enc !~ /utf-8/i
- rv << " standalone='#@standalone'" if @standalone
- rv
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/xmltokens.rb b/ruby_1_9_3/lib/rexml/xmltokens.rb
deleted file mode 100644
index 7dc4e8b2ba..0000000000
--- a/ruby_1_9_3/lib/rexml/xmltokens.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-module REXML
- # Defines a number of tokens used for parsing XML. Not for general
- # consumption.
- module XMLTokens
- NCNAME_STR= '[\w:][\-\w.]*'
- NAME_STR= "(?:#{NCNAME_STR}:)?#{NCNAME_STR}"
-
- NAMECHAR = '[\-\w\.:]'
- NAME = "([\\w:]#{NAMECHAR}*)"
- NMTOKEN = "(?:#{NAMECHAR})+"
- NMTOKENS = "#{NMTOKEN}(\\s+#{NMTOKEN})*"
- REFERENCE = "(?:&#{NAME};|&#\\d+;|&#x[0-9a-fA-F]+;)"
-
- #REFERENCE = "(?:#{ENTITYREF}|#{CHARREF})"
- #ENTITYREF = "&#{NAME};"
- #CHARREF = "&#\\d+;|&#x[0-9a-fA-F]+;"
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/xpath.rb b/ruby_1_9_3/lib/rexml/xpath.rb
deleted file mode 100644
index 0f99808def..0000000000
--- a/ruby_1_9_3/lib/rexml/xpath.rb
+++ /dev/null
@@ -1,80 +0,0 @@
-require 'rexml/functions'
-require 'rexml/xpath_parser'
-
-module REXML
- # Wrapper class. Use this class to access the XPath functions.
- class XPath
- include Functions
- # A base Hash object, supposing to be used when initializing a
- # default empty namespaces set, but is currently unused.
- # TODO: either set the namespaces=EMPTY_HASH, or deprecate this.
- EMPTY_HASH = {}
-
- # Finds and returns the first node that matches the supplied xpath.
- # element::
- # The context element
- # path::
- # The xpath to search for. If not supplied or nil, returns the first
- # node matching '*'.
- # namespaces::
- # If supplied, a Hash which defines a namespace mapping.
- # variables::
- # If supplied, a Hash which maps $variables in the query
- # to values. This can be used to avoid XPath injection attacks
- # or to automatically handle escaping string values.
- #
- # XPath.first( node )
- # XPath.first( doc, "//b"} )
- # XPath.first( node, "a/x:b", { "x"=>"http://doofus" } )
- # XPath.first( node, '/book/publisher/text()=$publisher', {}, {"publisher"=>"O'Reilly"})
- def XPath::first element, path=nil, namespaces=nil, variables={}
- raise "The namespaces argument, if supplied, must be a hash object." unless namespaces.nil? or namespaces.kind_of?(Hash)
- raise "The variables argument, if supplied, must be a hash object." unless variables.kind_of?(Hash)
- parser = XPathParser.new
- parser.namespaces = namespaces
- parser.variables = variables
- path = "*" unless path
- element = [element] unless element.kind_of? Array
- parser.parse(path, element).flatten[0]
- end
-
- # Iterates over nodes that match the given path, calling the supplied
- # block with the match.
- # element::
- # The context element
- # path::
- # The xpath to search for. If not supplied or nil, defaults to '*'
- # namespaces::
- # If supplied, a Hash which defines a namespace mapping
- # variables::
- # If supplied, a Hash which maps $variables in the query
- # to values. This can be used to avoid XPath injection attacks
- # or to automatically handle escaping string values.
- #
- # XPath.each( node ) { |el| ... }
- # XPath.each( node, '/*[@attr='v']' ) { |el| ... }
- # XPath.each( node, 'ancestor::x' ) { |el| ... }
- # XPath.each( node, '/book/publisher/text()=$publisher', {}, {"publisher"=>"O'Reilly"}) \
- # {|el| ... }
- def XPath::each element, path=nil, namespaces=nil, variables={}, &block
- raise "The namespaces argument, if supplied, must be a hash object." unless namespaces.nil? or namespaces.kind_of?(Hash)
- raise "The variables argument, if supplied, must be a hash object." unless variables.kind_of?(Hash)
- parser = XPathParser.new
- parser.namespaces = namespaces
- parser.variables = variables
- path = "*" unless path
- element = [element] unless element.kind_of? Array
- parser.parse(path, element).each( &block )
- end
-
- # Returns an array of nodes matching a given XPath.
- def XPath::match element, path=nil, namespaces=nil, variables={}
- parser = XPathParser.new
- parser.namespaces = namespaces
- parser.variables = variables
- path = "*" unless path
- element = [element] unless element.kind_of? Array
- parser.parse(path,element)
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rexml/xpath_parser.rb b/ruby_1_9_3/lib/rexml/xpath_parser.rb
deleted file mode 100644
index 0fc9da2e08..0000000000
--- a/ruby_1_9_3/lib/rexml/xpath_parser.rb
+++ /dev/null
@@ -1,803 +0,0 @@
-require 'rexml/namespace'
-require 'rexml/xmltokens'
-require 'rexml/attribute'
-require 'rexml/syncenumerator'
-require 'rexml/parsers/xpathparser'
-
-class Object
- # provides a unified +clone+ operation, for REXML::XPathParser
- # to use across multiple Object types
- def dclone
- clone
- end
-end
-class Symbol
- # provides a unified +clone+ operation, for REXML::XPathParser
- # to use across multiple Object types
- def dclone ; self ; end
-end
-class Fixnum
- # provides a unified +clone+ operation, for REXML::XPathParser
- # to use across multiple Object types
- def dclone ; self ; end
-end
-class Float
- # provides a unified +clone+ operation, for REXML::XPathParser
- # to use across multiple Object types
- def dclone ; self ; end
-end
-class Array
- # provides a unified +clone+ operation, for REXML::XPathParser
- # to use across multiple Object+ types
- def dclone
- klone = self.clone
- klone.clear
- self.each{|v| klone << v.dclone}
- klone
- end
-end
-
-module REXML
- # You don't want to use this class. Really. Use XPath, which is a wrapper
- # for this class. Believe me. You don't want to poke around in here.
- # There is strange, dark magic at work in this code. Beware. Go back! Go
- # back while you still can!
- class XPathParser
- include XMLTokens
- LITERAL = /^'([^']*)'|^"([^"]*)"/u
-
- def initialize( )
- @parser = REXML::Parsers::XPathParser.new
- @namespaces = nil
- @variables = {}
- end
-
- def namespaces=( namespaces={} )
- Functions::namespace_context = namespaces
- @namespaces = namespaces
- end
-
- def variables=( vars={} )
- Functions::variables = vars
- @variables = vars
- end
-
- def parse path, nodeset
- #puts "#"*40
- path_stack = @parser.parse( path )
- #puts "PARSE: #{path} => #{path_stack.inspect}"
- #puts "PARSE: nodeset = #{nodeset.inspect}"
- match( path_stack, nodeset )
- end
-
- def get_first path, nodeset
- #puts "#"*40
- path_stack = @parser.parse( path )
- #puts "PARSE: #{path} => #{path_stack.inspect}"
- #puts "PARSE: nodeset = #{nodeset.inspect}"
- first( path_stack, nodeset )
- end
-
- def predicate path, nodeset
- path_stack = @parser.parse( path )
- expr( path_stack, nodeset )
- end
-
- def []=( variable_name, value )
- @variables[ variable_name ] = value
- end
-
-
- # Performs a depth-first (document order) XPath search, and returns the
- # first match. This is the fastest, lightest way to return a single result.
- #
- # FIXME: This method is incomplete!
- def first( path_stack, node )
- #puts "#{depth}) Entering match( #{path.inspect}, #{tree.inspect} )"
- return nil if path.size == 0
-
- case path[0]
- when :document
- # do nothing
- return first( path[1..-1], node )
- when :child
- for c in node.children
- #puts "#{depth}) CHILD checking #{name(c)}"
- r = first( path[1..-1], c )
- #puts "#{depth}) RETURNING #{r.inspect}" if r
- return r if r
- end
- when :qname
- name = path[2]
- #puts "#{depth}) QNAME #{name(tree)} == #{name} (path => #{path.size})"
- if node.name == name
- #puts "#{depth}) RETURNING #{tree.inspect}" if path.size == 3
- return node if path.size == 3
- return first( path[3..-1], node )
- else
- return nil
- end
- when :descendant_or_self
- r = first( path[1..-1], node )
- return r if r
- for c in node.children
- r = first( path, c )
- return r if r
- end
- when :node
- return first( path[1..-1], node )
- when :any
- return first( path[1..-1], node )
- end
- return nil
- end
-
-
- def match( path_stack, nodeset )
- #puts "MATCH: path_stack = #{path_stack.inspect}"
- #puts "MATCH: nodeset = #{nodeset.inspect}"
- r = expr( path_stack, nodeset )
- #puts "MAIN EXPR => #{r.inspect}"
- r
- end
-
- private
-
-
- # Returns a String namespace for a node, given a prefix
- # The rules are:
- #
- # 1. Use the supplied namespace mapping first.
- # 2. If no mapping was supplied, use the context node to look up the namespace
- def get_namespace( node, prefix )
- if @namespaces
- return @namespaces[prefix] || ''
- else
- return node.namespace( prefix ) if node.node_type == :element
- return ''
- end
- end
-
-
- # Expr takes a stack of path elements and a set of nodes (either a Parent
- # or an Array and returns an Array of matching nodes
- ALL = [ :attribute, :element, :text, :processing_instruction, :comment ]
- ELEMENTS = [ :element ]
- def expr( path_stack, nodeset, context=nil )
- #puts "#"*15
- #puts "In expr with #{path_stack.inspect}"
- #puts "Returning" if path_stack.length == 0 || nodeset.length == 0
- node_types = ELEMENTS
- return nodeset if path_stack.length == 0 || nodeset.length == 0
- while path_stack.length > 0
- #puts "#"*5
- #puts "Path stack = #{path_stack.inspect}"
- #puts "Nodeset is #{nodeset.inspect}"
- if nodeset.length == 0
- path_stack.clear
- return []
- end
- case (op = path_stack.shift)
- when :document
- nodeset = [ nodeset[0].root_node ]
- #puts ":document, nodeset = #{nodeset.inspect}"
-
- when :qname
- #puts "IN QNAME"
- prefix = path_stack.shift
- name = path_stack.shift
- nodeset.delete_if do |node|
- # FIXME: This DOUBLES the time XPath searches take
- ns = get_namespace( node, prefix )
- #puts "NS = #{ns.inspect}"
- #puts "node.node_type == :element => #{node.node_type == :element}"
- if node.node_type == :element
- #puts "node.name == #{name} => #{node.name == name}"
- if node.name == name
- #puts "node.namespace == #{ns.inspect} => #{node.namespace == ns}"
- end
- end
- !(node.node_type == :element and
- node.name == name and
- node.namespace == ns )
- end
- node_types = ELEMENTS
-
- when :any
- #puts "ANY 1: nodeset = #{nodeset.inspect}"
- #puts "ANY 1: node_types = #{node_types.inspect}"
- nodeset.delete_if { |node| !node_types.include?(node.node_type) }
- #puts "ANY 2: nodeset = #{nodeset.inspect}"
-
- when :self
- # This space left intentionally blank
-
- when :processing_instruction
- target = path_stack.shift
- nodeset.delete_if do |node|
- (node.node_type != :processing_instruction) or
- ( target!='' and ( node.target != target ) )
- end
-
- when :text
- nodeset.delete_if { |node| node.node_type != :text }
-
- when :comment
- nodeset.delete_if { |node| node.node_type != :comment }
-
- when :node
- # This space left intentionally blank
- node_types = ALL
-
- when :child
- new_nodeset = []
- nt = nil
- nodeset.each do |node|
- nt = node.node_type
- new_nodeset += node.children if nt == :element or nt == :document
- end
- nodeset = new_nodeset
- node_types = ELEMENTS
-
- when :literal
- return path_stack.shift
-
- when :attribute
- new_nodeset = []
- case path_stack.shift
- when :qname
- prefix = path_stack.shift
- name = path_stack.shift
- for element in nodeset
- if element.node_type == :element
- #puts "Element name = #{element.name}"
- #puts "get_namespace( #{element.inspect}, #{prefix} ) = #{get_namespace(element, prefix)}"
- attrib = element.attribute( name, get_namespace(element, prefix) )
- #puts "attrib = #{attrib.inspect}"
- new_nodeset << attrib if attrib
- end
- end
- when :any
- #puts "ANY"
- for element in nodeset
- if element.node_type == :element
- new_nodeset += element.attributes.to_a
- end
- end
- end
- nodeset = new_nodeset
-
- when :parent
- #puts "PARENT 1: nodeset = #{nodeset}"
- nodeset = nodeset.collect{|n| n.parent}.compact
- #nodeset = expr(path_stack.dclone, nodeset.collect{|n| n.parent}.compact)
- #puts "PARENT 2: nodeset = #{nodeset.inspect}"
- node_types = ELEMENTS
-
- when :ancestor
- new_nodeset = []
- nodeset.each do |node|
- while node.parent
- node = node.parent
- new_nodeset << node unless new_nodeset.include? node
- end
- end
- nodeset = new_nodeset
- node_types = ELEMENTS
-
- when :ancestor_or_self
- new_nodeset = []
- nodeset.each do |node|
- if node.node_type == :element
- new_nodeset << node
- while ( node.parent )
- node = node.parent
- new_nodeset << node unless new_nodeset.include? node
- end
- end
- end
- nodeset = new_nodeset
- node_types = ELEMENTS
-
- when :predicate
- new_nodeset = []
- subcontext = { :size => nodeset.size }
- pred = path_stack.shift
- nodeset.each_with_index { |node, index|
- subcontext[ :node ] = node
- #puts "PREDICATE SETTING CONTEXT INDEX TO #{index+1}"
- subcontext[ :index ] = index+1
- pc = pred.dclone
- #puts "#{node.hash}) Recursing with #{pred.inspect} and [#{node.inspect}]"
- result = expr( pc, [node], subcontext )
- result = result[0] if result.kind_of? Array and result.length == 1
- #puts "#{node.hash}) Result = #{result.inspect} (#{result.class.name})"
- if result.kind_of? Numeric
- #puts "Adding node #{node.inspect}" if result == (index+1)
- new_nodeset << node if result == (index+1)
- elsif result.instance_of? Array
- if result.size > 0 and result.inject(false) {|k,s| s or k}
- #puts "Adding node #{node.inspect}" if result.size > 0
- new_nodeset << node if result.size > 0
- end
- else
- #puts "Adding node #{node.inspect}" if result
- new_nodeset << node if result
- end
- }
- #puts "New nodeset = #{new_nodeset.inspect}"
- #puts "Path_stack = #{path_stack.inspect}"
- nodeset = new_nodeset
-=begin
- predicate = path_stack.shift
- ns = nodeset.clone
- result = expr( predicate, ns )
- #puts "Result = #{result.inspect} (#{result.class.name})"
- #puts "nodeset = #{nodeset.inspect}"
- if result.kind_of? Array
- nodeset = result.zip(ns).collect{|m,n| n if m}.compact
- else
- nodeset = result ? nodeset : []
- end
- #puts "Outgoing NS = #{nodeset.inspect}"
-=end
-
- when :descendant_or_self
- rv = descendant_or_self( path_stack, nodeset )
- path_stack.clear
- nodeset = rv
- node_types = ELEMENTS
-
- when :descendant
- results = []
- nt = nil
- nodeset.each do |node|
- nt = node.node_type
- results += expr( path_stack.dclone.unshift( :descendant_or_self ),
- node.children ) if nt == :element or nt == :document
- end
- nodeset = results
- node_types = ELEMENTS
-
- when :following_sibling
- #puts "FOLLOWING_SIBLING 1: nodeset = #{nodeset}"
- results = []
- nodeset.each do |node|
- next if node.parent.nil?
- all_siblings = node.parent.children
- current_index = all_siblings.index( node )
- following_siblings = all_siblings[ current_index+1 .. -1 ]
- results += expr( path_stack.dclone, following_siblings )
- end
- #puts "FOLLOWING_SIBLING 2: nodeset = #{nodeset}"
- nodeset = results
-
- when :preceding_sibling
- results = []
- nodeset.each do |node|
- next if node.parent.nil?
- all_siblings = node.parent.children
- current_index = all_siblings.index( node )
- preceding_siblings = all_siblings[ 0, current_index ].reverse
- results += preceding_siblings
- end
- nodeset = results
- node_types = ELEMENTS
-
- when :preceding
- new_nodeset = []
- nodeset.each do |node|
- new_nodeset += preceding( node )
- end
- #puts "NEW NODESET => #{new_nodeset.inspect}"
- nodeset = new_nodeset
- node_types = ELEMENTS
-
- when :following
- new_nodeset = []
- nodeset.each do |node|
- new_nodeset += following( node )
- end
- nodeset = new_nodeset
- node_types = ELEMENTS
-
- when :namespace
- #puts "In :namespace"
- new_nodeset = []
- prefix = path_stack.shift
- nodeset.each do |node|
- if (node.node_type == :element or node.node_type == :attribute)
- if @namespaces
- namespaces = @namespaces
- elsif (node.node_type == :element)
- namespaces = node.namespaces
- else
- namespaces = node.element.namesapces
- end
- #puts "Namespaces = #{namespaces.inspect}"
- #puts "Prefix = #{prefix.inspect}"
- #puts "Node.namespace = #{node.namespace}"
- if (node.namespace == namespaces[prefix])
- new_nodeset << node
- end
- end
- end
- nodeset = new_nodeset
-
- when :variable
- var_name = path_stack.shift
- return @variables[ var_name ]
-
- # :and, :or, :eq, :neq, :lt, :lteq, :gt, :gteq
- # TODO: Special case for :or and :and -- not evaluate the right
- # operand if the left alone determines result (i.e. is true for
- # :or and false for :and).
- when :eq, :neq, :lt, :lteq, :gt, :gteq, :or
- left = expr( path_stack.shift, nodeset.dup, context )
- #puts "LEFT => #{left.inspect} (#{left.class.name})"
- right = expr( path_stack.shift, nodeset.dup, context )
- #puts "RIGHT => #{right.inspect} (#{right.class.name})"
- res = equality_relational_compare( left, op, right )
- #puts "RES => #{res.inspect}"
- return res
-
- when :and
- left = expr( path_stack.shift, nodeset.dup, context )
- #puts "LEFT => #{left.inspect} (#{left.class.name})"
- return [] unless left
- if left.respond_to?(:inject) and !left.inject(false) {|a,b| a | b}
- return []
- end
- right = expr( path_stack.shift, nodeset.dup, context )
- #puts "RIGHT => #{right.inspect} (#{right.class.name})"
- res = equality_relational_compare( left, op, right )
- #puts "RES => #{res.inspect}"
- return res
-
- when :div
- left = Functions::number(expr(path_stack.shift, nodeset, context)).to_f
- right = Functions::number(expr(path_stack.shift, nodeset, context)).to_f
- return (left / right)
-
- when :mod
- left = Functions::number(expr(path_stack.shift, nodeset, context )).to_f
- right = Functions::number(expr(path_stack.shift, nodeset, context )).to_f
- return (left % right)
-
- when :mult
- left = Functions::number(expr(path_stack.shift, nodeset, context )).to_f
- right = Functions::number(expr(path_stack.shift, nodeset, context )).to_f
- return (left * right)
-
- when :plus
- left = Functions::number(expr(path_stack.shift, nodeset, context )).to_f
- right = Functions::number(expr(path_stack.shift, nodeset, context )).to_f
- return (left + right)
-
- when :minus
- left = Functions::number(expr(path_stack.shift, nodeset, context )).to_f
- right = Functions::number(expr(path_stack.shift, nodeset, context )).to_f
- return (left - right)
-
- when :union
- left = expr( path_stack.shift, nodeset, context )
- right = expr( path_stack.shift, nodeset, context )
- return (left | right)
-
- when :neg
- res = expr( path_stack, nodeset, context )
- return -(res.to_f)
-
- when :not
- when :function
- func_name = path_stack.shift.tr('-','_')
- arguments = path_stack.shift
- #puts "FUNCTION 0: #{func_name}(#{arguments.collect{|a|a.inspect}.join(', ')})"
- subcontext = context ? nil : { :size => nodeset.size }
-
- res = []
- cont = context
- nodeset.each_with_index { |n, i|
- if subcontext
- subcontext[:node] = n
- subcontext[:index] = i
- cont = subcontext
- end
- arg_clone = arguments.dclone
- args = arg_clone.collect { |arg|
- #puts "FUNCTION 1: Calling expr( #{arg.inspect}, [#{n.inspect}] )"
- expr( arg, [n], cont )
- }
- #puts "FUNCTION 2: #{func_name}(#{args.collect{|a|a.inspect}.join(', ')})"
- Functions.context = cont
- res << Functions.send( func_name, *args )
- #puts "FUNCTION 3: #{res[-1].inspect}"
- }
- return res
-
- end
- end # while
- #puts "EXPR returning #{nodeset.inspect}"
- return nodeset
- end
-
-
- ##########################################################
- # FIXME
- # The next two methods are BAD MOJO!
- # This is my achilles heel. If anybody thinks of a better
- # way of doing this, be my guest. This really sucks, but
- # it is a wonder it works at all.
- # ########################################################
-
- def descendant_or_self( path_stack, nodeset )
- rs = []
- #puts "#"*80
- #puts "PATH_STACK = #{path_stack.inspect}"
- #puts "NODESET = #{nodeset.collect{|n|n.inspect}.inspect}"
- d_o_s( path_stack, nodeset, rs )
- #puts "RS = #{rs.collect{|n|n.inspect}.inspect}"
- document_order(rs.flatten.compact)
- #rs.flatten.compact
- end
-
- def d_o_s( p, ns, r )
- #puts "IN DOS with #{ns.inspect}; ALREADY HAVE #{r.inspect}"
- nt = nil
- ns.each_index do |i|
- n = ns[i]
- #puts "P => #{p.inspect}"
- x = expr( p.dclone, [ n ] )
- nt = n.node_type
- d_o_s( p, n.children, x ) if nt == :element or nt == :document and n.children.size > 0
- r.concat(x) if x.size > 0
- end
- end
-
-
- # Reorders an array of nodes so that they are in document order
- # It tries to do this efficiently.
- #
- # FIXME: I need to get rid of this, but the issue is that most of the XPath
- # interpreter functions as a filter, which means that we lose context going
- # in and out of function calls. If I knew what the index of the nodes was,
- # I wouldn't have to do this. Maybe add a document IDX for each node?
- # Problems with mutable documents. Or, rewrite everything.
- def document_order( array_of_nodes )
- new_arry = []
- array_of_nodes.each { |node|
- node_idx = []
- np = node.node_type == :attribute ? node.element : node
- while np.parent and np.parent.node_type == :element
- node_idx << np.parent.index( np )
- np = np.parent
- end
- new_arry << [ node_idx.reverse, node ]
- }
- #puts "new_arry = #{new_arry.inspect}"
- new_arry.sort{ |s1, s2| s1[0] <=> s2[0] }.collect{ |s| s[1] }
- end
-
-
- def recurse( nodeset, &block )
- for node in nodeset
- yield node
- recurse( node, &block ) if node.node_type == :element
- end
- end
-
-
-
- # Builds a nodeset of all of the preceding nodes of the supplied node,
- # in reverse document order
- # preceding:: includes every element in the document that precedes this node,
- # except for ancestors
- def preceding( node )
- #puts "IN PRECEDING"
- ancestors = []
- p = node.parent
- while p
- ancestors << p
- p = p.parent
- end
-
- acc = []
- p = preceding_node_of( node )
- #puts "P = #{p.inspect}"
- while p
- if ancestors.include? p
- ancestors.delete(p)
- else
- acc << p
- end
- p = preceding_node_of( p )
- #puts "P = #{p.inspect}"
- end
- acc
- end
-
- def preceding_node_of( node )
- #puts "NODE: #{node.inspect}"
- #puts "PREVIOUS NODE: #{node.previous_sibling_node.inspect}"
- #puts "PARENT NODE: #{node.parent}"
- psn = node.previous_sibling_node
- if psn.nil?
- if node.parent.nil? or node.parent.class == Document
- return nil
- end
- return node.parent
- #psn = preceding_node_of( node.parent )
- end
- while psn and psn.kind_of? Element and psn.children.size > 0
- psn = psn.children[-1]
- end
- psn
- end
-
- def following( node )
- #puts "IN PRECEDING"
- acc = []
- p = next_sibling_node( node )
- #puts "P = #{p.inspect}"
- while p
- acc << p
- p = following_node_of( p )
- #puts "P = #{p.inspect}"
- end
- acc
- end
-
- def following_node_of( node )
- #puts "NODE: #{node.inspect}"
- #puts "PREVIOUS NODE: #{node.previous_sibling_node.inspect}"
- #puts "PARENT NODE: #{node.parent}"
- if node.kind_of? Element and node.children.size > 0
- return node.children[0]
- end
- return next_sibling_node(node)
- end
-
- def next_sibling_node(node)
- psn = node.next_sibling_node
- while psn.nil?
- if node.parent.nil? or node.parent.class == Document
- return nil
- end
- node = node.parent
- psn = node.next_sibling_node
- #puts "psn = #{psn.inspect}"
- end
- return psn
- end
-
- def norm b
- case b
- when true, false
- return b
- when 'true', 'false'
- return Functions::boolean( b )
- when /^\d+(\.\d+)?$/
- return Functions::number( b )
- else
- return Functions::string( b )
- end
- end
-
- def equality_relational_compare( set1, op, set2 )
- #puts "EQ_REL_COMP(#{set1.inspect} #{op.inspect} #{set2.inspect})"
- if set1.kind_of? Array and set2.kind_of? Array
- #puts "#{set1.size} & #{set2.size}"
- if set1.size == 1 and set2.size == 1
- set1 = set1[0]
- set2 = set2[0]
- elsif set1.size == 0 or set2.size == 0
- nd = set1.size==0 ? set2 : set1
- rv = nd.collect { |il| compare( il, op, nil ) }
- #puts "RV = #{rv.inspect}"
- return rv
- else
- res = []
- SyncEnumerator.new( set1, set2 ).each { |i1, i2|
- #puts "i1 = #{i1.inspect} (#{i1.class.name})"
- #puts "i2 = #{i2.inspect} (#{i2.class.name})"
- i1 = norm( i1 )
- i2 = norm( i2 )
- res << compare( i1, op, i2 )
- }
- return res
- end
- end
- #puts "EQ_REL_COMP: #{set1.inspect} (#{set1.class.name}), #{op}, #{set2.inspect} (#{set2.class.name})"
- #puts "COMPARING VALUES"
- # If one is nodeset and other is number, compare number to each item
- # in nodeset s.t. number op number(string(item))
- # If one is nodeset and other is string, compare string to each item
- # in nodeset s.t. string op string(item)
- # If one is nodeset and other is boolean, compare boolean to each item
- # in nodeset s.t. boolean op boolean(item)
- if set1.kind_of? Array or set2.kind_of? Array
- #puts "ISA ARRAY"
- if set1.kind_of? Array
- a = set1
- b = set2
- else
- a = set2
- b = set1
- end
-
- case b
- when true, false
- return a.collect {|v| compare( Functions::boolean(v), op, b ) }
- when Numeric
- return a.collect {|v| compare( Functions::number(v), op, b )}
- when /^\d+(\.\d+)?$/
- b = Functions::number( b )
- #puts "B = #{b.inspect}"
- return a.collect {|v| compare( Functions::number(v), op, b )}
- else
- #puts "Functions::string( #{b}(#{b.class.name}) ) = #{Functions::string(b)}"
- b = Functions::string( b )
- return a.collect { |v| compare( Functions::string(v), op, b ) }
- end
- else
- # If neither is nodeset,
- # If op is = or !=
- # If either boolean, convert to boolean
- # If either number, convert to number
- # Else, convert to string
- # Else
- # Convert both to numbers and compare
- s1 = set1.to_s
- s2 = set2.to_s
- #puts "EQ_REL_COMP: #{set1}=>#{s1}, #{set2}=>#{s2}"
- if s1 == 'true' or s1 == 'false' or s2 == 'true' or s2 == 'false'
- #puts "Functions::boolean(#{set1})=>#{Functions::boolean(set1)}"
- #puts "Functions::boolean(#{set2})=>#{Functions::boolean(set2)}"
- set1 = Functions::boolean( set1 )
- set2 = Functions::boolean( set2 )
- else
- if op == :eq or op == :neq
- if s1 =~ /^\d+(\.\d+)?$/ or s2 =~ /^\d+(\.\d+)?$/
- set1 = Functions::number( s1 )
- set2 = Functions::number( s2 )
- else
- set1 = Functions::string( set1 )
- set2 = Functions::string( set2 )
- end
- else
- set1 = Functions::number( set1 )
- set2 = Functions::number( set2 )
- end
- end
- #puts "EQ_REL_COMP: #{set1} #{op} #{set2}"
- #puts ">>> #{compare( set1, op, set2 )}"
- return compare( set1, op, set2 )
- end
- return false
- end
-
- def compare a, op, b
- #puts "COMPARE #{a.inspect}(#{a.class.name}) #{op} #{b.inspect}(#{b.class.name})"
- case op
- when :eq
- a == b
- when :neq
- a != b
- when :lt
- a < b
- when :lteq
- a <= b
- when :gt
- a > b
- when :gteq
- a >= b
- when :and
- a and b
- when :or
- a or b
- else
- false
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rinda/rinda.rb b/ruby_1_9_3/lib/rinda/rinda.rb
deleted file mode 100644
index 18e284a544..0000000000
--- a/ruby_1_9_3/lib/rinda/rinda.rb
+++ /dev/null
@@ -1,283 +0,0 @@
-require 'drb/drb'
-require 'thread'
-
-##
-# A module to implement the Linda distributed computing paradigm in Ruby.
-#
-# Rinda is part of DRb (dRuby).
-#
-# == Example(s)
-#
-# See the sample/drb/ directory in the Ruby distribution, from 1.8.2 onwards.
-#
-#--
-# TODO
-# == Introduction to Linda/rinda?
-#
-# == Why is this library separate from DRb?
-
-module Rinda
-
- ##
- # Rinda error base class
-
- class RindaError < RuntimeError; end
-
- ##
- # Raised when a hash-based tuple has an invalid key.
-
- class InvalidHashTupleKey < RindaError; end
-
- ##
- # Raised when trying to use a canceled tuple.
-
- class RequestCanceledError < ThreadError; end
-
- ##
- # Raised when trying to use an expired tuple.
-
- class RequestExpiredError < ThreadError; end
-
- ##
- # A tuple is the elementary object in Rinda programming.
- # Tuples may be matched against templates if the tuple and
- # the template are the same size.
-
- class Tuple
-
- ##
- # Creates a new Tuple from +ary_or_hash+ which must be an Array or Hash.
-
- def initialize(ary_or_hash)
- if hash?(ary_or_hash)
- init_with_hash(ary_or_hash)
- else
- init_with_ary(ary_or_hash)
- end
- end
-
- ##
- # The number of elements in the tuple.
-
- def size
- @tuple.size
- end
-
- ##
- # Accessor method for elements of the tuple.
-
- def [](k)
- @tuple[k]
- end
-
- ##
- # Fetches item +k+ from the tuple.
-
- def fetch(k)
- @tuple.fetch(k)
- end
-
- ##
- # Iterate through the tuple, yielding the index or key, and the
- # value, thus ensuring arrays are iterated similarly to hashes.
-
- def each # FIXME
- if Hash === @tuple
- @tuple.each { |k, v| yield(k, v) }
- else
- @tuple.each_with_index { |v, k| yield(k, v) }
- end
- end
-
- ##
- # Return the tuple itself
- def value
- @tuple
- end
-
- private
-
- def hash?(ary_or_hash)
- ary_or_hash.respond_to?(:keys)
- end
-
- ##
- # Munges +ary+ into a valid Tuple.
-
- def init_with_ary(ary)
- @tuple = Array.new(ary.size)
- @tuple.size.times do |i|
- @tuple[i] = ary[i]
- end
- end
-
- ##
- # Ensures +hash+ is a valid Tuple.
-
- def init_with_hash(hash)
- @tuple = Hash.new
- hash.each do |k, v|
- raise InvalidHashTupleKey unless String === k
- @tuple[k] = v
- end
- end
-
- end
-
- ##
- # Templates are used to match tuples in Rinda.
-
- class Template < Tuple
-
- ##
- # Matches this template against +tuple+. The +tuple+ must be the same
- # size as the template. An element with a +nil+ value in a template acts
- # as a wildcard, matching any value in the corresponding position in the
- # tuple. Elements of the template match the +tuple+ if the are #== or
- # #===.
- #
- # Template.new([:foo, 5]).match Tuple.new([:foo, 5]) # => true
- # Template.new([:foo, nil]).match Tuple.new([:foo, 5]) # => true
- # Template.new([String]).match Tuple.new(['hello']) # => true
- #
- # Template.new([:foo]).match Tuple.new([:foo, 5]) # => false
- # Template.new([:foo, 6]).match Tuple.new([:foo, 5]) # => false
- # Template.new([:foo, nil]).match Tuple.new([:foo]) # => false
- # Template.new([:foo, 6]).match Tuple.new([:foo]) # => false
-
- def match(tuple)
- return false unless tuple.respond_to?(:size)
- return false unless tuple.respond_to?(:fetch)
- return false unless self.size == tuple.size
- each do |k, v|
- begin
- it = tuple.fetch(k)
- rescue
- return false
- end
- next if v.nil?
- next if v == it
- next if v === it
- return false
- end
- return true
- end
-
- ##
- # Alias for #match.
-
- def ===(tuple)
- match(tuple)
- end
-
- end
-
- ##
- # <i>Documentation?</i>
-
- class DRbObjectTemplate
-
- ##
- # Creates a new DRbObjectTemplate that will match against +uri+ and +ref+.
-
- def initialize(uri=nil, ref=nil)
- @drb_uri = uri
- @drb_ref = ref
- end
-
- ##
- # This DRbObjectTemplate matches +ro+ if the remote object's drburi and
- # drbref are the same. +nil+ is used as a wildcard.
-
- def ===(ro)
- return true if super(ro)
- unless @drb_uri.nil?
- return false unless (@drb_uri === ro.__drburi rescue false)
- end
- unless @drb_ref.nil?
- return false unless (@drb_ref === ro.__drbref rescue false)
- end
- true
- end
-
- end
-
- ##
- # TupleSpaceProxy allows a remote Tuplespace to appear as local.
-
- class TupleSpaceProxy
-
- ##
- # Creates a new TupleSpaceProxy to wrap +ts+.
-
- def initialize(ts)
- @ts = ts
- end
-
- ##
- # Adds +tuple+ to the proxied TupleSpace. See TupleSpace#write.
-
- def write(tuple, sec=nil)
- @ts.write(tuple, sec)
- end
-
- ##
- # Takes +tuple+ from the proxied TupleSpace. See TupleSpace#take.
-
- def take(tuple, sec=nil, &block)
- port = []
- @ts.move(DRbObject.new(port), tuple, sec, &block)
- port[0]
- end
-
- ##
- # Reads +tuple+ from the proxied TupleSpace. See TupleSpace#read.
-
- def read(tuple, sec=nil, &block)
- @ts.read(tuple, sec, &block)
- end
-
- ##
- # Reads all tuples matching +tuple+ from the proxied TupleSpace. See
- # TupleSpace#read_all.
-
- def read_all(tuple)
- @ts.read_all(tuple)
- end
-
- ##
- # Registers for notifications of event +ev+ on the proxied TupleSpace.
- # See TupleSpace#notify
-
- def notify(ev, tuple, sec=nil)
- @ts.notify(ev, tuple, sec)
- end
-
- end
-
- ##
- # An SimpleRenewer allows a TupleSpace to check if a TupleEntry is still
- # alive.
-
- class SimpleRenewer
-
- include DRbUndumped
-
- ##
- # Creates a new SimpleRenewer that keeps an object alive for another +sec+
- # seconds.
-
- def initialize(sec=180)
- @sec = sec
- end
-
- ##
- # Called by the TupleSpace to check if the object is still alive.
-
- def renew
- @sec
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rinda/ring.rb b/ruby_1_9_3/lib/rinda/ring.rb
deleted file mode 100644
index 3ff4606e2a..0000000000
--- a/ruby_1_9_3/lib/rinda/ring.rb
+++ /dev/null
@@ -1,271 +0,0 @@
-#
-# Note: Rinda::Ring API is unstable.
-#
-require 'drb/drb'
-require 'rinda/rinda'
-require 'thread'
-
-module Rinda
-
- ##
- # The default port Ring discovery will use.
-
- Ring_PORT = 7647
-
- ##
- # A RingServer allows a Rinda::TupleSpace to be located via UDP broadcasts.
- # Service location uses the following steps:
- #
- # 1. A RingServer begins listening on the broadcast UDP address.
- # 2. A RingFinger sends a UDP packet containing the DRb URI where it will
- # listen for a reply.
- # 3. The RingServer receives the UDP packet and connects back to the
- # provided DRb URI with the DRb service.
-
- class RingServer
-
- include DRbUndumped
-
- ##
- # Advertises +ts+ on the UDP broadcast address at +port+.
-
- def initialize(ts, port=Ring_PORT)
- @ts = ts
- @soc = UDPSocket.open
- @soc.bind('', port)
- @w_service = write_service
- @r_service = reply_service
- end
-
- ##
- # Creates a thread that picks up UDP packets and passes them to do_write
- # for decoding.
-
- def write_service
- Thread.new do
- loop do
- msg = @soc.recv(1024)
- do_write(msg)
- end
- end
- end
-
- ##
- # Extracts the response URI from +msg+ and adds it to TupleSpace where it
- # will be picked up by +reply_service+ for notification.
-
- def do_write(msg)
- Thread.new do
- begin
- tuple, sec = Marshal.load(msg)
- @ts.write(tuple, sec)
- rescue
- end
- end
- end
-
- ##
- # Creates a thread that notifies waiting clients from the TupleSpace.
-
- def reply_service
- Thread.new do
- loop do
- do_reply
- end
- end
- end
-
- ##
- # Pulls lookup tuples out of the TupleSpace and sends their DRb object the
- # address of the local TupleSpace.
-
- def do_reply
- tuple = @ts.take([:lookup_ring, DRbObject])
- Thread.new { tuple[1].call(@ts) rescue nil}
- rescue
- end
-
- end
-
- ##
- # RingFinger is used by RingServer clients to discover the RingServer's
- # TupleSpace. Typically, all a client needs to do is call
- # RingFinger.primary to retrieve the remote TupleSpace, which it can then
- # begin using.
-
- class RingFinger
-
- @@broadcast_list = ['<broadcast>', 'localhost']
-
- @@finger = nil
-
- ##
- # Creates a singleton RingFinger and looks for a RingServer. Returns the
- # created RingFinger.
-
- def self.finger
- unless @@finger
- @@finger = self.new
- @@finger.lookup_ring_any
- end
- @@finger
- end
-
- ##
- # Returns the first advertised TupleSpace.
-
- def self.primary
- finger.primary
- end
-
- ##
- # Contains all discovered TupleSpaces except for the primary.
-
- def self.to_a
- finger.to_a
- end
-
- ##
- # The list of addresses where RingFinger will send query packets.
-
- attr_accessor :broadcast_list
-
- ##
- # The port that RingFinger will send query packets to.
-
- attr_accessor :port
-
- ##
- # Contain the first advertised TupleSpace after lookup_ring_any is called.
-
- attr_accessor :primary
-
- ##
- # Creates a new RingFinger that will look for RingServers at +port+ on
- # the addresses in +broadcast_list+.
-
- def initialize(broadcast_list=@@broadcast_list, port=Ring_PORT)
- @broadcast_list = broadcast_list || ['localhost']
- @port = port
- @primary = nil
- @rings = []
- end
-
- ##
- # Contains all discovered TupleSpaces except for the primary.
-
- def to_a
- @rings
- end
-
- ##
- # Iterates over all discovered TupleSpaces starting with the primary.
-
- def each
- lookup_ring_any unless @primary
- return unless @primary
- yield(@primary)
- @rings.each { |x| yield(x) }
- end
-
- ##
- # Looks up RingServers waiting +timeout+ seconds. RingServers will be
- # given +block+ as a callback, which will be called with the remote
- # TupleSpace.
-
- def lookup_ring(timeout=5, &block)
- return lookup_ring_any(timeout) unless block_given?
-
- msg = Marshal.dump([[:lookup_ring, DRbObject.new(block)], timeout])
- @broadcast_list.each do |it|
- soc = UDPSocket.open
- begin
- soc.setsockopt(Socket::SOL_SOCKET, Socket::SO_BROADCAST, true)
- soc.send(msg, 0, it, @port)
- rescue
- nil
- ensure
- soc.close
- end
- end
- sleep(timeout)
- end
-
- ##
- # Returns the first found remote TupleSpace. Any further recovered
- # TupleSpaces can be found by calling +to_a+.
-
- def lookup_ring_any(timeout=5)
- queue = Queue.new
-
- Thread.new do
- self.lookup_ring(timeout) do |ts|
- queue.push(ts)
- end
- queue.push(nil)
- while it = queue.pop
- @rings.push(it)
- end
- end
-
- @primary = queue.pop
- raise('RingNotFound') if @primary.nil?
- @primary
- end
-
- end
-
- ##
- # RingProvider uses a RingServer advertised TupleSpace as a name service.
- # TupleSpace clients can register themselves with the remote TupleSpace and
- # look up other provided services via the remote TupleSpace.
- #
- # Services are registered with a tuple of the format [:name, klass,
- # DRbObject, description].
-
- class RingProvider
-
- ##
- # Creates a RingProvider that will provide a +klass+ service running on
- # +front+, with a +description+. +renewer+ is optional.
-
- def initialize(klass, front, desc, renewer = nil)
- @tuple = [:name, klass, front, desc]
- @renewer = renewer || Rinda::SimpleRenewer.new
- end
-
- ##
- # Advertises this service on the primary remote TupleSpace.
-
- def provide
- ts = Rinda::RingFinger.primary
- ts.write(@tuple, @renewer)
- end
-
- end
-
-end
-
-if __FILE__ == $0
- DRb.start_service
- case ARGV.shift
- when 's'
- require 'rinda/tuplespace'
- ts = Rinda::TupleSpace.new
- Rinda::RingServer.new(ts)
- $stdin.gets
- when 'w'
- finger = Rinda::RingFinger.new(nil)
- finger.lookup_ring do |ts2|
- p ts2
- ts2.write([:hello, :world])
- end
- when 'r'
- finger = Rinda::RingFinger.new(nil)
- finger.lookup_ring do |ts2|
- p ts2
- p ts2.take([nil, nil])
- end
- end
-end
-
diff --git a/ruby_1_9_3/lib/rinda/tuplespace.rb b/ruby_1_9_3/lib/rinda/tuplespace.rb
deleted file mode 100644
index 113aa0de15..0000000000
--- a/ruby_1_9_3/lib/rinda/tuplespace.rb
+++ /dev/null
@@ -1,642 +0,0 @@
-require 'monitor'
-require 'thread'
-require 'drb/drb'
-require 'rinda/rinda'
-require 'enumerator'
-require 'forwardable'
-
-module Rinda
-
- ##
- # A TupleEntry is a Tuple (i.e. a possible entry in some Tuplespace)
- # together with expiry and cancellation data.
-
- class TupleEntry
-
- include DRbUndumped
-
- attr_accessor :expires
-
- ##
- # Creates a TupleEntry based on +ary+ with an optional renewer or expiry
- # time +sec+.
- #
- # A renewer must implement the +renew+ method which returns a Numeric,
- # nil, or true to indicate when the tuple has expired.
-
- def initialize(ary, sec=nil)
- @cancel = false
- @expires = nil
- @tuple = make_tuple(ary)
- @renewer = nil
- renew(sec)
- end
-
- ##
- # Marks this TupleEntry as canceled.
-
- def cancel
- @cancel = true
- end
-
- ##
- # A TupleEntry is dead when it is canceled or expired.
-
- def alive?
- !canceled? && !expired?
- end
-
- ##
- # Return the object which makes up the tuple itself: the Array
- # or Hash.
-
- def value; @tuple.value; end
-
- ##
- # Returns the canceled status.
-
- def canceled?; @cancel; end
-
- ##
- # Has this tuple expired? (true/false).
- #
- # A tuple has expired when its expiry timer based on the +sec+ argument to
- # #initialize runs out.
-
- def expired?
- return true unless @expires
- return false if @expires > Time.now
- return true if @renewer.nil?
- renew(@renewer)
- return true unless @expires
- return @expires < Time.now
- end
-
- ##
- # Reset the expiry time according to +sec_or_renewer+.
- #
- # +nil+:: it is set to expire in the far future.
- # +false+:: it has expired.
- # Numeric:: it will expire in that many seconds.
- #
- # Otherwise the argument refers to some kind of renewer object
- # which will reset its expiry time.
-
- def renew(sec_or_renewer)
- sec, @renewer = get_renewer(sec_or_renewer)
- @expires = make_expires(sec)
- end
-
- ##
- # Returns an expiry Time based on +sec+ which can be one of:
- # Numeric:: +sec+ seconds into the future
- # +true+:: the expiry time is the start of 1970 (i.e. expired)
- # +nil+:: it is Tue Jan 19 03:14:07 GMT Standard Time 2038 (i.e. when
- # UNIX clocks will die)
-
- def make_expires(sec=nil)
- case sec
- when Numeric
- Time.now + sec
- when true
- Time.at(1)
- when nil
- Time.at(2**31-1)
- end
- end
-
- ##
- # Retrieves +key+ from the tuple.
-
- def [](key)
- @tuple[key]
- end
-
- ##
- # Fetches +key+ from the tuple.
-
- def fetch(key)
- @tuple.fetch(key)
- end
-
- ##
- # The size of the tuple.
-
- def size
- @tuple.size
- end
-
- ##
- # Creates a Rinda::Tuple for +ary+.
-
- def make_tuple(ary)
- Rinda::Tuple.new(ary)
- end
-
- private
-
- ##
- # Returns a valid argument to make_expires and the renewer or nil.
- #
- # Given +true+, +nil+, or Numeric, returns that value and +nil+ (no actual
- # renewer). Otherwise it returns an expiry value from calling +it.renew+
- # and the renewer.
-
- def get_renewer(it)
- case it
- when Numeric, true, nil
- return it, nil
- else
- begin
- return it.renew, it
- rescue Exception
- return it, nil
- end
- end
- end
-
- end
-
- ##
- # A TemplateEntry is a Template together with expiry and cancellation data.
-
- class TemplateEntry < TupleEntry
- ##
- # Matches this TemplateEntry against +tuple+. See Template#match for
- # details on how a Template matches a Tuple.
-
- def match(tuple)
- @tuple.match(tuple)
- end
-
- alias === match
-
- def make_tuple(ary) # :nodoc:
- Rinda::Template.new(ary)
- end
-
- end
-
- ##
- # <i>Documentation?</i>
-
- class WaitTemplateEntry < TemplateEntry
-
- attr_reader :found
-
- def initialize(place, ary, expires=nil)
- super(ary, expires)
- @place = place
- @cond = place.new_cond
- @found = nil
- end
-
- def cancel
- super
- signal
- end
-
- def wait
- @cond.wait
- end
-
- def read(tuple)
- @found = tuple
- signal
- end
-
- def signal
- @place.synchronize do
- @cond.signal
- end
- end
-
- end
-
- ##
- # A NotifyTemplateEntry is returned by TupleSpace#notify and is notified of
- # TupleSpace changes. You may receive either your subscribed event or the
- # 'close' event when iterating over notifications.
- #
- # See TupleSpace#notify_event for valid notification types.
- #
- # == Example
- #
- # ts = Rinda::TupleSpace.new
- # observer = ts.notify 'write', [nil]
- #
- # Thread.start do
- # observer.each { |t| p t }
- # end
- #
- # 3.times { |i| ts.write [i] }
- #
- # Outputs:
- #
- # ['write', [0]]
- # ['write', [1]]
- # ['write', [2]]
-
- class NotifyTemplateEntry < TemplateEntry
-
- ##
- # Creates a new NotifyTemplateEntry that watches +place+ for +event+s that
- # match +tuple+.
-
- def initialize(place, event, tuple, expires=nil)
- ary = [event, Rinda::Template.new(tuple)]
- super(ary, expires)
- @queue = Queue.new
- @done = false
- end
-
- ##
- # Called by TupleSpace to notify this NotifyTemplateEntry of a new event.
-
- def notify(ev)
- @queue.push(ev)
- end
-
- ##
- # Retrieves a notification. Raises RequestExpiredError when this
- # NotifyTemplateEntry expires.
-
- def pop
- raise RequestExpiredError if @done
- it = @queue.pop
- @done = true if it[0] == 'close'
- return it
- end
-
- ##
- # Yields event/tuple pairs until this NotifyTemplateEntry expires.
-
- def each # :yields: event, tuple
- while !@done
- it = pop
- yield(it)
- end
- rescue
- ensure
- cancel
- end
-
- end
-
- ##
- # TupleBag is an unordered collection of tuples. It is the basis
- # of Tuplespace.
-
- class TupleBag
- class TupleBin
- extend Forwardable
- def_delegators '@bin', :find_all, :delete_if, :each, :empty?
-
- def initialize
- @bin = []
- end
-
- def add(tuple)
- @bin.push(tuple)
- end
-
- def delete(tuple)
- idx = @bin.rindex(tuple)
- @bin.delete_at(idx) if idx
- end
-
- def find(&blk)
- @bin.reverse_each do |x|
- return x if yield(x)
- end
- nil
- end
- end
-
- def initialize # :nodoc:
- @hash = {}
- @enum = enum_for(:each_entry)
- end
-
- ##
- # +true+ if the TupleBag to see if it has any expired entries.
-
- def has_expires?
- @enum.find do |tuple|
- tuple.expires
- end
- end
-
- ##
- # Add +tuple+ to the TupleBag.
-
- def push(tuple)
- key = bin_key(tuple)
- @hash[key] ||= TupleBin.new
- @hash[key].add(tuple)
- end
-
- ##
- # Removes +tuple+ from the TupleBag.
-
- def delete(tuple)
- key = bin_key(tuple)
- bin = @hash[key]
- return nil unless bin
- bin.delete(tuple)
- @hash.delete(key) if bin.empty?
- tuple
- end
-
- ##
- # Finds all live tuples that match +template+.
- def find_all(template)
- bin_for_find(template).find_all do |tuple|
- tuple.alive? && template.match(tuple)
- end
- end
-
- ##
- # Finds a live tuple that matches +template+.
-
- def find(template)
- bin_for_find(template).find do |tuple|
- tuple.alive? && template.match(tuple)
- end
- end
-
- ##
- # Finds all tuples in the TupleBag which when treated as templates, match
- # +tuple+ and are alive.
-
- def find_all_template(tuple)
- @enum.find_all do |template|
- template.alive? && template.match(tuple)
- end
- end
-
- ##
- # Delete tuples which dead tuples from the TupleBag, returning the deleted
- # tuples.
-
- def delete_unless_alive
- deleted = []
- @hash.each do |key, bin|
- bin.delete_if do |tuple|
- if tuple.alive?
- false
- else
- deleted.push(tuple)
- true
- end
- end
- end
- deleted
- end
-
- private
- def each_entry(&blk)
- @hash.each do |k, v|
- v.each(&blk)
- end
- end
-
- def bin_key(tuple)
- head = tuple[0]
- if head.class == Symbol
- return head
- else
- false
- end
- end
-
- def bin_for_find(template)
- key = bin_key(template)
- key ? @hash.fetch(key, []) : @enum
- end
- end
-
- ##
- # The Tuplespace manages access to the tuples it contains,
- # ensuring mutual exclusion requirements are met.
- #
- # The +sec+ option for the write, take, move, read and notify methods may
- # either be a number of seconds or a Renewer object.
-
- class TupleSpace
-
- include DRbUndumped
- include MonitorMixin
-
- ##
- # Creates a new TupleSpace. +period+ is used to control how often to look
- # for dead tuples after modifications to the TupleSpace.
- #
- # If no dead tuples are found +period+ seconds after the last
- # modification, the TupleSpace will stop looking for dead tuples.
-
- def initialize(period=60)
- super()
- @bag = TupleBag.new
- @read_waiter = TupleBag.new
- @take_waiter = TupleBag.new
- @notify_waiter = TupleBag.new
- @period = period
- @keeper = nil
- end
-
- ##
- # Adds +tuple+
-
- def write(tuple, sec=nil)
- entry = create_entry(tuple, sec)
- synchronize do
- if entry.expired?
- @read_waiter.find_all_template(entry).each do |template|
- template.read(tuple)
- end
- notify_event('write', entry.value)
- notify_event('delete', entry.value)
- else
- @bag.push(entry)
- start_keeper if entry.expires
- @read_waiter.find_all_template(entry).each do |template|
- template.read(tuple)
- end
- @take_waiter.find_all_template(entry).each do |template|
- template.signal
- end
- notify_event('write', entry.value)
- end
- end
- entry
- end
-
- ##
- # Removes +tuple+
-
- def take(tuple, sec=nil, &block)
- move(nil, tuple, sec, &block)
- end
-
- ##
- # Moves +tuple+ to +port+.
-
- def move(port, tuple, sec=nil)
- template = WaitTemplateEntry.new(self, tuple, sec)
- yield(template) if block_given?
- synchronize do
- entry = @bag.find(template)
- if entry
- port.push(entry.value) if port
- @bag.delete(entry)
- notify_event('take', entry.value)
- return entry.value
- end
- raise RequestExpiredError if template.expired?
-
- begin
- @take_waiter.push(template)
- start_keeper if template.expires
- while true
- raise RequestCanceledError if template.canceled?
- raise RequestExpiredError if template.expired?
- entry = @bag.find(template)
- if entry
- port.push(entry.value) if port
- @bag.delete(entry)
- notify_event('take', entry.value)
- return entry.value
- end
- template.wait
- end
- ensure
- @take_waiter.delete(template)
- end
- end
- end
-
- ##
- # Reads +tuple+, but does not remove it.
-
- def read(tuple, sec=nil)
- template = WaitTemplateEntry.new(self, tuple, sec)
- yield(template) if block_given?
- synchronize do
- entry = @bag.find(template)
- return entry.value if entry
- raise RequestExpiredError if template.expired?
-
- begin
- @read_waiter.push(template)
- start_keeper if template.expires
- template.wait
- raise RequestCanceledError if template.canceled?
- raise RequestExpiredError if template.expired?
- return template.found
- ensure
- @read_waiter.delete(template)
- end
- end
- end
-
- ##
- # Returns all tuples matching +tuple+. Does not remove the found tuples.
-
- def read_all(tuple)
- template = WaitTemplateEntry.new(self, tuple, nil)
- synchronize do
- entry = @bag.find_all(template)
- entry.collect do |e|
- e.value
- end
- end
- end
-
- ##
- # Registers for notifications of +event+. Returns a NotifyTemplateEntry.
- # See NotifyTemplateEntry for examples of how to listen for notifications.
- #
- # +event+ can be:
- # 'write':: A tuple was added
- # 'take':: A tuple was taken or moved
- # 'delete':: A tuple was lost after being overwritten or expiring
- #
- # The TupleSpace will also notify you of the 'close' event when the
- # NotifyTemplateEntry has expired.
-
- def notify(event, tuple, sec=nil)
- template = NotifyTemplateEntry.new(self, event, tuple, sec)
- synchronize do
- @notify_waiter.push(template)
- end
- template
- end
-
- private
-
- def create_entry(tuple, sec)
- TupleEntry.new(tuple, sec)
- end
-
- ##
- # Removes dead tuples.
-
- def keep_clean
- synchronize do
- @read_waiter.delete_unless_alive.each do |e|
- e.signal
- end
- @take_waiter.delete_unless_alive.each do |e|
- e.signal
- end
- @notify_waiter.delete_unless_alive.each do |e|
- e.notify(['close'])
- end
- @bag.delete_unless_alive.each do |e|
- notify_event('delete', e.value)
- end
- end
- end
-
- ##
- # Notifies all registered listeners for +event+ of a status change of
- # +tuple+.
-
- def notify_event(event, tuple)
- ev = [event, tuple]
- @notify_waiter.find_all_template(ev).each do |template|
- template.notify(ev)
- end
- end
-
- ##
- # Creates a thread that scans the tuplespace for expired tuples.
-
- def start_keeper
- return if @keeper && @keeper.alive?
- @keeper = Thread.new do
- while true
- sleep(@period)
- synchronize do
- break unless need_keeper?
- keep_clean
- end
- end
- end
- end
-
- ##
- # Checks the tuplespace to see if it needs cleaning.
-
- def need_keeper?
- return true if @bag.has_expires?
- return true if @read_waiter.has_expires?
- return true if @take_waiter.has_expires?
- return true if @notify_waiter.has_expires?
- end
-
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rss.rb b/ruby_1_9_3/lib/rss.rb
deleted file mode 100644
index fd7364645b..0000000000
--- a/ruby_1_9_3/lib/rss.rb
+++ /dev/null
@@ -1,91 +0,0 @@
-##
-# = RSS reading and writing
-#
-# Really Simple Syndication (RSS) is a family of formats that describe 'feeds,'
-# specially constructed XML documents that allow an interested person to
-# subscribe and receive updates from a particular web service. This portion of
-# the standard library provides tooling to read and create these feeds.
-#
-# The standard library supports RSS 0.91, 1.0, 2.0, and Atom, a related format.
-# Here are some links to the standards documents for these formats:
-#
-# * RSS
-# * 0.9.1[http://www.rssboard.org/rss-0-9-1-netscape]
-# * 1.0[http://web.resource.org/rss/1.0/]
-# * 2.0[http://www.rssboard.org/rss-specification]
-# * Atom[http://tools.ietf.org/html/rfc4287]
-#
-# == Consuming RSS
-#
-# If you'd like to read someone's RSS feed with your Ruby code, you've come to
-# the right place. It's really easy to do this, but we'll need the help of
-# open-uri:
-#
-# require 'rss'
-# require 'open-uri'
-#
-# url = 'http://www.ruby-lang.org/en/feeds/news.rss'
-# open(url) do |rss|
-# feed = RSS::Parser.parse(rss)
-# puts "Title: #{feed.channel.title}"
-# feed.items.each do |item|
-# puts "Item: #{item.title}"
-# end
-# end
-#
-# As you can see, the workhorse is RSS::Parser#parse, which takes the source of
-# the feed and a parameter that performs validation on the feed. We get back an
-# object that has all of the data from our feed, accessible through methods.
-# This example shows getting the title out of the channel element, and looping
-# through the list of items.
-#
-# == Producing RSS
-#
-# Producing our own RSS feeds is easy as well. Let's make a very basic feed:
-#
-# require "rss"
-#
-# rss = RSS::Maker.make("atom") do |maker|
-# maker.channel.author = "matz"
-# maker.channel.updated = Time.now.to_s
-# maker.channel.about = "http://www.ruby-lang.org/en/feeds/news.rss"
-# maker.channel.title = "Example Feed"
-#
-# maker.items.new_item do |item|
-# item.link = "http://www.ruby-lang.org/en/news/2010/12/25/ruby-1-9-2-p136-is-released/"
-# item.title = "Ruby 1.9.2-p136 is released"
-# item.updated = Time.now.to_s
-# end
-# end
-#
-# puts rss
-#
-# As you can see, this is a very Builder-like DSL. This code will spit out an
-# Atom feed with one item. If we needed a second item, we'd make another block
-# with maker.items.new_item and build a second one.
-#
-# == Copyright
-#
-# Copyright (c) 2003-2007 Kouhei Sutou <kou@cozmixng.org>
-#
-# You can redistribute it and/or modify it under the same terms as Ruby.
-#
-# There is an additional tutorial by the author of RSS at:
-# http://www.cozmixng.org/~rwiki/?cmd=view;name=RSS+Parser%3A%3ATutorial.en
-
-module RSS
-end
-
-require 'rss/1.0'
-require 'rss/2.0'
-require 'rss/atom'
-require 'rss/content'
-require 'rss/dublincore'
-require 'rss/image'
-require 'rss/itunes'
-require 'rss/slash'
-require 'rss/syndication'
-require 'rss/taxonomy'
-require 'rss/trackback'
-
-require "rss/maker"
diff --git a/ruby_1_9_3/lib/rss/0.9.rb b/ruby_1_9_3/lib/rss/0.9.rb
deleted file mode 100644
index 28ef768274..0000000000
--- a/ruby_1_9_3/lib/rss/0.9.rb
+++ /dev/null
@@ -1,428 +0,0 @@
-require "rss/parser"
-
-module RSS
-
- module RSS09
- NSPOOL = {}
- ELEMENTS = []
-
- def self.append_features(klass)
- super
-
- klass.install_must_call_validator('', "")
- end
- end
-
- class Rss < Element
-
- include RSS09
- include RootElementMixin
-
- %w(channel).each do |name|
- install_have_child_element(name, "", nil)
- end
-
- attr_writer :feed_version
- alias_method(:rss_version, :feed_version)
- alias_method(:rss_version=, :feed_version=)
-
- def initialize(feed_version, version=nil, encoding=nil, standalone=nil)
- super
- @feed_type = "rss"
- end
-
- def items
- if @channel
- @channel.items
- else
- []
- end
- end
-
- def image
- if @channel
- @channel.image
- else
- nil
- end
- end
-
- def textinput
- if @channel
- @channel.textInput
- else
- nil
- end
- end
-
- def setup_maker_elements(maker)
- super
- items.each do |item|
- item.setup_maker(maker.items)
- end
- image.setup_maker(maker) if image
- textinput.setup_maker(maker) if textinput
- end
-
- private
- def _attrs
- [
- ["version", true, "feed_version"],
- ]
- end
-
- class Channel < Element
-
- include RSS09
-
- [
- ["title", nil, :text],
- ["link", nil, :text],
- ["description", nil, :text],
- ["language", nil, :text],
- ["copyright", "?", :text],
- ["managingEditor", "?", :text],
- ["webMaster", "?", :text],
- ["rating", "?", :text],
- ["pubDate", "?", :date, :rfc822],
- ["lastBuildDate", "?", :date, :rfc822],
- ["docs", "?", :text],
- ["cloud", "?", :have_attribute],
- ["skipDays", "?", :have_child],
- ["skipHours", "?", :have_child],
- ["image", nil, :have_child],
- ["item", "*", :have_children],
- ["textInput", "?", :have_child],
- ].each do |name, occurs, type, *args|
- __send__("install_#{type}_element", name, "", occurs, name, *args)
- end
- alias date pubDate
- alias date= pubDate=
-
- private
- def maker_target(maker)
- maker.channel
- end
-
- def setup_maker_elements(channel)
- super
- [
- [skipDays, "day"],
- [skipHours, "hour"],
- ].each do |skip, key|
- if skip
- skip.__send__("#{key}s").each do |val|
- target_skips = channel.__send__("skip#{key.capitalize}s")
- new_target = target_skips.__send__("new_#{key}")
- new_target.content = val.content
- end
- end
- end
- end
-
- def not_need_to_call_setup_maker_variables
- %w(image textInput)
- end
-
- class SkipDays < Element
- include RSS09
-
- [
- ["day", "*"]
- ].each do |name, occurs|
- install_have_children_element(name, "", occurs)
- end
-
- class Day < Element
- include RSS09
-
- content_setup
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.content = args[0]
- end
- end
-
- end
-
- end
-
- class SkipHours < Element
- include RSS09
-
- [
- ["hour", "*"]
- ].each do |name, occurs|
- install_have_children_element(name, "", occurs)
- end
-
- class Hour < Element
- include RSS09
-
- content_setup(:integer)
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.content = args[0]
- end
- end
- end
-
- end
-
- class Image < Element
-
- include RSS09
-
- %w(url title link).each do |name|
- install_text_element(name, "", nil)
- end
- [
- ["width", :integer],
- ["height", :integer],
- ["description"],
- ].each do |name, type|
- install_text_element(name, "", "?", name, type)
- end
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.url = args[0]
- self.title = args[1]
- self.link = args[2]
- self.width = args[3]
- self.height = args[4]
- self.description = args[5]
- end
- end
-
- private
- def maker_target(maker)
- maker.image
- end
- end
-
- class Cloud < Element
-
- include RSS09
-
- [
- ["domain", "", true],
- ["port", "", true, :integer],
- ["path", "", true],
- ["registerProcedure", "", true],
- ["protocol", "", true],
- ].each do |name, uri, required, type|
- install_get_attribute(name, uri, required, type)
- end
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.domain = args[0]
- self.port = args[1]
- self.path = args[2]
- self.registerProcedure = args[3]
- self.protocol = args[4]
- end
- end
- end
-
- class Item < Element
-
- include RSS09
-
- [
- ["title", '?', :text],
- ["link", '?', :text],
- ["description", '?', :text],
- ["category", '*', :have_children, "categories"],
- ["source", '?', :have_child],
- ["enclosure", '?', :have_child],
- ].each do |tag, occurs, type, *args|
- __send__("install_#{type}_element", tag, "", occurs, tag, *args)
- end
-
- private
- def maker_target(items)
- if items.respond_to?("items")
- # For backward compatibility
- items = items.items
- end
- items.new_item
- end
-
- def setup_maker_element(item)
- super
- @enclosure.setup_maker(item) if @enclosure
- @source.setup_maker(item) if @source
- end
-
- class Source < Element
-
- include RSS09
-
- [
- ["url", "", true]
- ].each do |name, uri, required|
- install_get_attribute(name, uri, required)
- end
-
- content_setup
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.url = args[0]
- self.content = args[1]
- end
- end
-
- private
- def maker_target(item)
- item.source
- end
-
- def setup_maker_attributes(source)
- source.url = url
- source.content = content
- end
- end
-
- class Enclosure < Element
-
- include RSS09
-
- [
- ["url", "", true],
- ["length", "", true, :integer],
- ["type", "", true],
- ].each do |name, uri, required, type|
- install_get_attribute(name, uri, required, type)
- end
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.url = args[0]
- self.length = args[1]
- self.type = args[2]
- end
- end
-
- private
- def maker_target(item)
- item.enclosure
- end
-
- def setup_maker_attributes(enclosure)
- enclosure.url = url
- enclosure.length = length
- enclosure.type = type
- end
- end
-
- class Category < Element
-
- include RSS09
-
- [
- ["domain", "", false]
- ].each do |name, uri, required|
- install_get_attribute(name, uri, required)
- end
-
- content_setup
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.domain = args[0]
- self.content = args[1]
- end
- end
-
- private
- def maker_target(item)
- item.new_category
- end
-
- def setup_maker_attributes(category)
- category.domain = domain
- category.content = content
- end
-
- end
-
- end
-
- class TextInput < Element
-
- include RSS09
-
- %w(title description name link).each do |name|
- install_text_element(name, "", nil)
- end
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.title = args[0]
- self.description = args[1]
- self.name = args[2]
- self.link = args[3]
- end
- end
-
- private
- def maker_target(maker)
- maker.textinput
- end
- end
-
- end
-
- end
-
- RSS09::ELEMENTS.each do |name|
- BaseListener.install_get_text_element("", name, name)
- end
-
- module ListenerMixin
- private
- def initial_start_rss(tag_name, prefix, attrs, ns)
- check_ns(tag_name, prefix, ns, "", false)
-
- @rss = Rss.new(attrs['version'], @version, @encoding, @standalone)
- @rss.do_validate = @do_validate
- @rss.xml_stylesheets = @xml_stylesheets
- @last_element = @rss
- pr = Proc.new do |text, tags|
- @rss.validate_for_stream(tags, @ignore_unknown_element) if @do_validate
- end
- @proc_stack.push(pr)
- end
-
- end
-
-end
diff --git a/ruby_1_9_3/lib/rss/1.0.rb b/ruby_1_9_3/lib/rss/1.0.rb
deleted file mode 100644
index 2ff53b4723..0000000000
--- a/ruby_1_9_3/lib/rss/1.0.rb
+++ /dev/null
@@ -1,452 +0,0 @@
-require "rss/parser"
-
-module RSS
-
- module RSS10
- NSPOOL = {}
- ELEMENTS = []
-
- def self.append_features(klass)
- super
-
- klass.install_must_call_validator('', ::RSS::URI)
- end
-
- end
-
- class RDF < Element
-
- include RSS10
- include RootElementMixin
-
- class << self
-
- def required_uri
- URI
- end
-
- end
-
- @tag_name = 'RDF'
-
- PREFIX = 'rdf'
- URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
-
- install_ns('', ::RSS::URI)
- install_ns(PREFIX, URI)
-
- [
- ["channel", nil],
- ["image", "?"],
- ["item", "+", :children],
- ["textinput", "?"],
- ].each do |tag, occurs, type|
- type ||= :child
- __send__("install_have_#{type}_element", tag, ::RSS::URI, occurs)
- end
-
- alias_method(:rss_version, :feed_version)
- def initialize(version=nil, encoding=nil, standalone=nil)
- super('1.0', version, encoding, standalone)
- @feed_type = "rss"
- end
-
- def full_name
- tag_name_with_prefix(PREFIX)
- end
-
- class Li < Element
-
- include RSS10
-
- class << self
- def required_uri
- URI
- end
- end
-
- [
- ["resource", [URI, ""], true]
- ].each do |name, uri, required|
- install_get_attribute(name, uri, required)
- end
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.resource = args[0]
- end
- end
-
- def full_name
- tag_name_with_prefix(PREFIX)
- end
- end
-
- class Seq < Element
-
- include RSS10
-
- Li = ::RSS::RDF::Li
-
- class << self
- def required_uri
- URI
- end
- end
-
- @tag_name = 'Seq'
-
- install_have_children_element("li", URI, "*")
- install_must_call_validator('rdf', ::RSS::RDF::URI)
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- @li = args[0] if args[0]
- end
- end
-
- def full_name
- tag_name_with_prefix(PREFIX)
- end
-
- def setup_maker(target)
- lis.each do |li|
- target << li.resource
- end
- end
- end
-
- class Bag < Element
-
- include RSS10
-
- Li = ::RSS::RDF::Li
-
- class << self
- def required_uri
- URI
- end
- end
-
- @tag_name = 'Bag'
-
- install_have_children_element("li", URI, "*")
- install_must_call_validator('rdf', URI)
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- @li = args[0] if args[0]
- end
- end
-
- def full_name
- tag_name_with_prefix(PREFIX)
- end
-
- def setup_maker(target)
- lis.each do |li|
- target << li.resource
- end
- end
- end
-
- class Channel < Element
-
- include RSS10
-
- class << self
-
- def required_uri
- ::RSS::URI
- end
-
- end
-
- [
- ["about", URI, true]
- ].each do |name, uri, required|
- install_get_attribute(name, uri, required, nil, nil,
- "#{PREFIX}:#{name}")
- end
-
- [
- ['title', nil, :text],
- ['link', nil, :text],
- ['description', nil, :text],
- ['image', '?', :have_child],
- ['items', nil, :have_child],
- ['textinput', '?', :have_child],
- ].each do |tag, occurs, type|
- __send__("install_#{type}_element", tag, ::RSS::URI, occurs)
- end
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.about = args[0]
- end
- end
-
- private
- def maker_target(maker)
- maker.channel
- end
-
- def setup_maker_attributes(channel)
- channel.about = about
- end
-
- class Image < Element
-
- include RSS10
-
- class << self
-
- def required_uri
- ::RSS::URI
- end
-
- end
-
- [
- ["resource", URI, true]
- ].each do |name, uri, required|
- install_get_attribute(name, uri, required, nil, nil,
- "#{PREFIX}:#{name}")
- end
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.resource = args[0]
- end
- end
- end
-
- class Textinput < Element
-
- include RSS10
-
- class << self
-
- def required_uri
- ::RSS::URI
- end
-
- end
-
- [
- ["resource", URI, true]
- ].each do |name, uri, required|
- install_get_attribute(name, uri, required, nil, nil,
- "#{PREFIX}:#{name}")
- end
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.resource = args[0]
- end
- end
- end
-
- class Items < Element
-
- include RSS10
-
- Seq = ::RSS::RDF::Seq
-
- class << self
-
- def required_uri
- ::RSS::URI
- end
-
- end
-
- install_have_child_element("Seq", URI, nil)
- install_must_call_validator('rdf', URI)
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.Seq = args[0]
- end
- self.Seq ||= Seq.new
- end
-
- def resources
- if @Seq
- @Seq.lis.collect do |li|
- li.resource
- end
- else
- []
- end
- end
- end
- end
-
- class Image < Element
-
- include RSS10
-
- class << self
-
- def required_uri
- ::RSS::URI
- end
-
- end
-
- [
- ["about", URI, true]
- ].each do |name, uri, required|
- install_get_attribute(name, uri, required, nil, nil,
- "#{PREFIX}:#{name}")
- end
-
- %w(title url link).each do |name|
- install_text_element(name, ::RSS::URI, nil)
- end
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.about = args[0]
- end
- end
-
- private
- def maker_target(maker)
- maker.image
- end
- end
-
- class Item < Element
-
- include RSS10
-
- class << self
-
- def required_uri
- ::RSS::URI
- end
-
- end
-
-
- [
- ["about", URI, true]
- ].each do |name, uri, required|
- install_get_attribute(name, uri, required, nil, nil,
- "#{PREFIX}:#{name}")
- end
-
- [
- ["title", nil],
- ["link", nil],
- ["description", "?"],
- ].each do |tag, occurs|
- install_text_element(tag, ::RSS::URI, occurs)
- end
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.about = args[0]
- end
- end
-
- private
- def maker_target(items)
- if items.respond_to?("items")
- # For backward compatibility
- items = items.items
- end
- items.new_item
- end
- end
-
- class Textinput < Element
-
- include RSS10
-
- class << self
-
- def required_uri
- ::RSS::URI
- end
-
- end
-
- [
- ["about", URI, true]
- ].each do |name, uri, required|
- install_get_attribute(name, uri, required, nil, nil,
- "#{PREFIX}:#{name}")
- end
-
- %w(title description name link).each do |name|
- install_text_element(name, ::RSS::URI, nil)
- end
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.about = args[0]
- end
- end
-
- private
- def maker_target(maker)
- maker.textinput
- end
- end
-
- end
-
- RSS10::ELEMENTS.each do |name|
- BaseListener.install_get_text_element(URI, name, name)
- end
-
- module ListenerMixin
- private
- def initial_start_RDF(tag_name, prefix, attrs, ns)
- check_ns(tag_name, prefix, ns, RDF::URI, false)
-
- @rss = RDF.new(@version, @encoding, @standalone)
- @rss.do_validate = @do_validate
- @rss.xml_stylesheets = @xml_stylesheets
- @last_element = @rss
- pr = Proc.new do |text, tags|
- @rss.validate_for_stream(tags, @ignore_unknown_element) if @do_validate
- end
- @proc_stack.push(pr)
- end
- end
-
-end
diff --git a/ruby_1_9_3/lib/rss/2.0.rb b/ruby_1_9_3/lib/rss/2.0.rb
deleted file mode 100644
index 9622c598d9..0000000000
--- a/ruby_1_9_3/lib/rss/2.0.rb
+++ /dev/null
@@ -1,111 +0,0 @@
-require "rss/0.9"
-
-module RSS
-
- class Rss
-
- class Channel
-
- [
- ["generator"],
- ["ttl", :integer],
- ].each do |name, type|
- install_text_element(name, "", "?", name, type)
- end
-
- [
- %w(category categories),
- ].each do |name, plural_name|
- install_have_children_element(name, "", "*", name, plural_name)
- end
-
- [
- ["image", "?"],
- ["language", "?"],
- ].each do |name, occurs|
- install_model(name, "", occurs)
- end
-
- Category = Item::Category
-
- class Item
-
- [
- ["comments", "?"],
- ["author", "?"],
- ].each do |name, occurs|
- install_text_element(name, "", occurs)
- end
-
- [
- ["pubDate", '?'],
- ].each do |name, occurs|
- install_date_element(name, "", occurs, name, 'rfc822')
- end
- alias date pubDate
- alias date= pubDate=
-
- [
- ["guid", '?'],
- ].each do |name, occurs|
- install_have_child_element(name, "", occurs)
- end
-
- private
- alias _setup_maker_element setup_maker_element
- def setup_maker_element(item)
- _setup_maker_element(item)
- @guid.setup_maker(item) if @guid
- end
-
- class Guid < Element
-
- include RSS09
-
- [
- ["isPermaLink", "", false, :boolean]
- ].each do |name, uri, required, type|
- install_get_attribute(name, uri, required, type)
- end
-
- content_setup
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.isPermaLink = args[0]
- self.content = args[1]
- end
- end
-
- alias_method :_PermaLink?, :PermaLink?
- private :_PermaLink?
- def PermaLink?
- perma = _PermaLink?
- perma or perma.nil?
- end
-
- private
- def maker_target(item)
- item.guid
- end
-
- def setup_maker_attributes(guid)
- guid.isPermaLink = isPermaLink
- guid.content = content
- end
- end
-
- end
-
- end
-
- end
-
- RSS09::ELEMENTS.each do |name|
- BaseListener.install_get_text_element("", name, name)
- end
-
-end
diff --git a/ruby_1_9_3/lib/rss/atom.rb b/ruby_1_9_3/lib/rss/atom.rb
deleted file mode 100644
index f6fea386ba..0000000000
--- a/ruby_1_9_3/lib/rss/atom.rb
+++ /dev/null
@@ -1,756 +0,0 @@
-require 'rss/parser'
-
-module RSS
- module Atom
-
- ##
- # The Atom URI W3C Namespace
-
- URI = "http://www.w3.org/2005/Atom"
-
- ##
- # The XHTML URI W3C Namespace
-
- XHTML_URI = "http://www.w3.org/1999/xhtml"
-
- module CommonModel
- NSPOOL = {}
- ELEMENTS = []
-
- def self.append_features(klass)
- super
- klass.install_must_call_validator("atom", URI)
- [
- ["lang", :xml],
- ["base", :xml],
- ].each do |name, uri, required|
- klass.install_get_attribute(name, uri, required, [nil, :inherit])
- end
- klass.class_eval do
- class << self
- def required_uri
- URI
- end
-
- def need_parent?
- true
- end
- end
- end
- end
- end
-
- module ContentModel
- module ClassMethods
- def content_type
- @content_type ||= nil
- end
- end
-
- class << self
- def append_features(klass)
- super
- klass.extend(ClassMethods)
- klass.content_setup(klass.content_type, klass.tag_name)
- end
- end
-
- def maker_target(target)
- target
- end
-
- private
- def setup_maker_element_writer
- "#{self.class.name.split(/::/).last.downcase}="
- end
-
- def setup_maker_element(target)
- target.__send__(setup_maker_element_writer, content)
- super
- end
- end
-
- module URIContentModel
- class << self
- def append_features(klass)
- super
- klass.class_eval do
- @content_type = [nil, :uri]
- include(ContentModel)
- end
- end
- end
- end
-
- module TextConstruct
- def self.append_features(klass)
- super
- klass.class_eval do
- [
- ["type", ""],
- ].each do |name, uri, required|
- install_get_attribute(name, uri, required, :text_type)
- end
-
- content_setup
- add_need_initialize_variable("xhtml")
-
- class << self
- def xml_getter
- "xhtml"
- end
-
- def xml_setter
- "xhtml="
- end
- end
- end
- end
-
- attr_writer :xhtml
- def xhtml
- return @xhtml if @xhtml.nil?
- if @xhtml.is_a?(XML::Element) and
- [@xhtml.name, @xhtml.uri] == ["div", XHTML_URI]
- return @xhtml
- end
-
- children = @xhtml
- children = [children] unless children.is_a?(Array)
- XML::Element.new("div", nil, XHTML_URI,
- {"xmlns" => XHTML_URI}, children)
- end
-
- def have_xml_content?
- @type == "xhtml"
- end
-
- def atom_validate(ignore_unknown_element, tags, uri)
- if have_xml_content?
- if @xhtml.nil?
- raise MissingTagError.new("div", tag_name)
- end
- unless [@xhtml.name, @xhtml.uri] == ["div", XHTML_URI]
- raise NotExpectedTagError.new(@xhtml.name, @xhtml.uri, tag_name)
- end
- end
- end
-
- private
- def maker_target(target)
- target.__send__(self.class.name.split(/::/).last.downcase) {|x| x}
- end
-
- def setup_maker_attributes(target)
- target.type = type
- target.content = content
- target.xml_content = @xhtml
- end
- end
-
- module PersonConstruct
- def self.append_features(klass)
- super
- klass.class_eval do
- [
- ["name", nil],
- ["uri", "?"],
- ["email", "?"],
- ].each do |tag, occurs|
- install_have_attribute_element(tag, URI, occurs, nil, :content)
- end
- end
- end
-
- def maker_target(target)
- target.__send__("new_#{self.class.name.split(/::/).last.downcase}")
- end
-
- class Name < RSS::Element
- include CommonModel
- include ContentModel
- end
-
- class Uri < RSS::Element
- include CommonModel
- include URIContentModel
- end
-
- class Email < RSS::Element
- include CommonModel
- include ContentModel
- end
- end
-
- module DateConstruct
- def self.append_features(klass)
- super
- klass.class_eval do
- @content_type = :w3cdtf
- include(ContentModel)
- end
- end
-
- def atom_validate(ignore_unknown_element, tags, uri)
- raise NotAvailableValueError.new(tag_name, "") if content.nil?
- end
- end
-
- module DuplicateLinkChecker
- def validate_duplicate_links(links)
- link_infos = {}
- links.each do |link|
- rel = link.rel || "alternate"
- next unless rel == "alternate"
- key = [link.hreflang, link.type]
- if link_infos.has_key?(key)
- raise TooMuchTagError.new("link", tag_name)
- end
- link_infos[key] = true
- end
- end
- end
-
- class Feed < RSS::Element
- include RootElementMixin
- include CommonModel
- include DuplicateLinkChecker
-
- install_ns('', URI)
-
- [
- ["author", "*", :children],
- ["category", "*", :children, "categories"],
- ["contributor", "*", :children],
- ["generator", "?"],
- ["icon", "?", nil, :content],
- ["id", nil, nil, :content],
- ["link", "*", :children],
- ["logo", "?"],
- ["rights", "?"],
- ["subtitle", "?", nil, :content],
- ["title", nil, nil, :content],
- ["updated", nil, nil, :content],
- ["entry", "*", :children, "entries"],
- ].each do |tag, occurs, type, *args|
- type ||= :child
- __send__("install_have_#{type}_element",
- tag, URI, occurs, tag, *args)
- end
-
- def initialize(version=nil, encoding=nil, standalone=nil)
- super("1.0", version, encoding, standalone)
- @feed_type = "atom"
- @feed_subtype = "feed"
- end
-
- alias_method :items, :entries
-
- def have_author?
- authors.any? {|author| !author.to_s.empty?} or
- entries.any? {|entry| entry.have_author?(false)}
- end
-
- private
- def atom_validate(ignore_unknown_element, tags, uri)
- unless have_author?
- raise MissingTagError.new("author", tag_name)
- end
- validate_duplicate_links(links)
- end
-
- def have_required_elements?
- super and have_author?
- end
-
- def maker_target(maker)
- maker.channel
- end
-
- def setup_maker_element(channel)
- prev_dc_dates = channel.dc_dates.to_a.dup
- super
- channel.about = id.content if id
- channel.dc_dates.replace(prev_dc_dates)
- end
-
- def setup_maker_elements(channel)
- super
- items = channel.maker.items
- entries.each do |entry|
- entry.setup_maker(items)
- end
- end
-
- class Author < RSS::Element
- include CommonModel
- include PersonConstruct
- end
-
- class Category < RSS::Element
- include CommonModel
-
- [
- ["term", "", true],
- ["scheme", "", false, [nil, :uri]],
- ["label", ""],
- ].each do |name, uri, required, type|
- install_get_attribute(name, uri, required, type)
- end
-
- private
- def maker_target(target)
- target.new_category
- end
- end
-
- class Contributor < RSS::Element
- include CommonModel
- include PersonConstruct
- end
-
- class Generator < RSS::Element
- include CommonModel
- include ContentModel
-
- [
- ["uri", "", false, [nil, :uri]],
- ["version", ""],
- ].each do |name, uri, required, type|
- install_get_attribute(name, uri, required, type)
- end
-
- private
- def setup_maker_attributes(target)
- target.generator do |generator|
- generator.uri = uri if uri
- generator.version = version if version
- end
- end
- end
-
- class Icon < RSS::Element
- include CommonModel
- include URIContentModel
- end
-
- class Id < RSS::Element
- include CommonModel
- include URIContentModel
- end
-
- class Link < RSS::Element
- include CommonModel
-
- [
- ["href", "", true, [nil, :uri]],
- ["rel", ""],
- ["type", ""],
- ["hreflang", ""],
- ["title", ""],
- ["length", ""],
- ].each do |name, uri, required, type|
- install_get_attribute(name, uri, required, type)
- end
-
- private
- def maker_target(target)
- target.new_link
- end
- end
-
- class Logo < RSS::Element
- include CommonModel
- include URIContentModel
-
- def maker_target(target)
- target.maker.image
- end
-
- private
- def setup_maker_element_writer
- "url="
- end
- end
-
- class Rights < RSS::Element
- include CommonModel
- include TextConstruct
- end
-
- class Subtitle < RSS::Element
- include CommonModel
- include TextConstruct
- end
-
- class Title < RSS::Element
- include CommonModel
- include TextConstruct
- end
-
- class Updated < RSS::Element
- include CommonModel
- include DateConstruct
- end
-
- class Entry < RSS::Element
- include CommonModel
- include DuplicateLinkChecker
-
- [
- ["author", "*", :children],
- ["category", "*", :children, "categories"],
- ["content", "?", :child],
- ["contributor", "*", :children],
- ["id", nil, nil, :content],
- ["link", "*", :children],
- ["published", "?", :child, :content],
- ["rights", "?", :child],
- ["source", "?"],
- ["summary", "?", :child],
- ["title", nil],
- ["updated", nil, :child, :content],
- ].each do |tag, occurs, type, *args|
- type ||= :attribute
- __send__("install_have_#{type}_element",
- tag, URI, occurs, tag, *args)
- end
-
- def have_author?(check_parent=true)
- authors.any? {|author| !author.to_s.empty?} or
- (check_parent and @parent and @parent.have_author?) or
- (source and source.have_author?)
- end
-
- private
- def atom_validate(ignore_unknown_element, tags, uri)
- unless have_author?
- raise MissingTagError.new("author", tag_name)
- end
- validate_duplicate_links(links)
- end
-
- def have_required_elements?
- super and have_author?
- end
-
- def maker_target(items)
- if items.respond_to?("items")
- # For backward compatibility
- items = items.items
- end
- items.new_item
- end
-
- Author = Feed::Author
- Category = Feed::Category
-
- class Content < RSS::Element
- include CommonModel
-
- class << self
- def xml_setter
- "xml="
- end
-
- def xml_getter
- "xml"
- end
- end
-
- [
- ["type", ""],
- ["src", "", false, [nil, :uri]],
- ].each do |name, uri, required, type|
- install_get_attribute(name, uri, required, type)
- end
-
- content_setup
- add_need_initialize_variable("xml")
-
- attr_writer :xml
- def have_xml_content?
- inline_xhtml? or inline_other_xml?
- end
-
- def xml
- return @xml unless inline_xhtml?
- return @xml if @xml.nil?
- if @xml.is_a?(XML::Element) and
- [@xml.name, @xml.uri] == ["div", XHTML_URI]
- return @xml
- end
-
- children = @xml
- children = [children] unless children.is_a?(Array)
- XML::Element.new("div", nil, XHTML_URI,
- {"xmlns" => XHTML_URI}, children)
- end
-
- def xhtml
- if inline_xhtml?
- xml
- else
- nil
- end
- end
-
- def atom_validate(ignore_unknown_element, tags, uri)
- if out_of_line?
- raise MissingAttributeError.new(tag_name, "type") if @type.nil?
- unless (content.nil? or content.empty?)
- raise NotAvailableValueError.new(tag_name, content)
- end
- elsif inline_xhtml?
- if @xml.nil?
- raise MissingTagError.new("div", tag_name)
- end
- unless @xml.name == "div" and @xml.uri == XHTML_URI
- raise NotExpectedTagError.new(@xml.name, @xml.uri, tag_name)
- end
- end
- end
-
- def inline_text?
- !out_of_line? and [nil, "text", "html"].include?(@type)
- end
-
- def inline_html?
- return false if out_of_line?
- @type == "html" or mime_split == ["text", "html"]
- end
-
- def inline_xhtml?
- !out_of_line? and @type == "xhtml"
- end
-
- def inline_other?
- return false if out_of_line?
- media_type, subtype = mime_split
- return false if media_type.nil? or subtype.nil?
- true
- end
-
- def inline_other_text?
- return false unless inline_other?
- return false if inline_other_xml?
-
- media_type, = mime_split
- return true if "text" == media_type.downcase
- false
- end
-
- def inline_other_xml?
- return false unless inline_other?
-
- media_type, subtype = mime_split
- normalized_mime_type = "#{media_type}/#{subtype}".downcase
- if /(?:\+xml|^xml)$/ =~ subtype or
- %w(text/xml-external-parsed-entity
- application/xml-external-parsed-entity
- application/xml-dtd).find {|x| x == normalized_mime_type}
- return true
- end
- false
- end
-
- def inline_other_base64?
- inline_other? and !inline_other_text? and !inline_other_xml?
- end
-
- def out_of_line?
- not @src.nil?
- end
-
- def mime_split
- media_type = subtype = nil
- if /\A\s*([a-z]+)\/([a-z\+]+)\s*(?:;.*)?\z/i =~ @type.to_s
- media_type = $1.downcase
- subtype = $2.downcase
- end
- [media_type, subtype]
- end
-
- def need_base64_encode?
- inline_other_base64?
- end
-
- private
- def empty_content?
- out_of_line? or super
- end
- end
-
- Contributor = Feed::Contributor
- Id = Feed::Id
- Link = Feed::Link
-
- class Published < RSS::Element
- include CommonModel
- include DateConstruct
- end
-
- Rights = Feed::Rights
-
- class Source < RSS::Element
- include CommonModel
-
- [
- ["author", "*", :children],
- ["category", "*", :children, "categories"],
- ["contributor", "*", :children],
- ["generator", "?"],
- ["icon", "?"],
- ["id", "?", nil, :content],
- ["link", "*", :children],
- ["logo", "?"],
- ["rights", "?"],
- ["subtitle", "?"],
- ["title", "?"],
- ["updated", "?", nil, :content],
- ].each do |tag, occurs, type, *args|
- type ||= :attribute
- __send__("install_have_#{type}_element",
- tag, URI, occurs, tag, *args)
- end
-
- def have_author?
- !author.to_s.empty?
- end
-
- Author = Feed::Author
- Category = Feed::Category
- Contributor = Feed::Contributor
- Generator = Feed::Generator
- Icon = Feed::Icon
- Id = Feed::Id
- Link = Feed::Link
- Logo = Feed::Logo
- Rights = Feed::Rights
- Subtitle = Feed::Subtitle
- Title = Feed::Title
- Updated = Feed::Updated
- end
-
- class Summary < RSS::Element
- include CommonModel
- include TextConstruct
- end
-
- Title = Feed::Title
- Updated = Feed::Updated
- end
- end
-
- class Entry < RSS::Element
- include RootElementMixin
- include CommonModel
- include DuplicateLinkChecker
-
- [
- ["author", "*", :children],
- ["category", "*", :children, "categories"],
- ["content", "?"],
- ["contributor", "*", :children],
- ["id", nil, nil, :content],
- ["link", "*", :children],
- ["published", "?", :child, :content],
- ["rights", "?"],
- ["source", "?"],
- ["summary", "?"],
- ["title", nil],
- ["updated", nil, nil, :content],
- ].each do |tag, occurs, type, *args|
- type ||= :attribute
- __send__("install_have_#{type}_element",
- tag, URI, occurs, tag, *args)
- end
-
- def initialize(version=nil, encoding=nil, standalone=nil)
- super("1.0", version, encoding, standalone)
- @feed_type = "atom"
- @feed_subtype = "entry"
- end
-
- def items
- [self]
- end
-
- def setup_maker(maker)
- maker = maker.maker if maker.respond_to?("maker")
- super(maker)
- end
-
- def have_author?
- authors.any? {|author| !author.to_s.empty?} or
- (source and source.have_author?)
- end
-
- private
- def atom_validate(ignore_unknown_element, tags, uri)
- unless have_author?
- raise MissingTagError.new("author", tag_name)
- end
- validate_duplicate_links(links)
- end
-
- def have_required_elements?
- super and have_author?
- end
-
- def maker_target(maker)
- maker.items.new_item
- end
-
- Author = Feed::Entry::Author
- Category = Feed::Entry::Category
- Content = Feed::Entry::Content
- Contributor = Feed::Entry::Contributor
- Id = Feed::Entry::Id
- Link = Feed::Entry::Link
- Published = Feed::Entry::Published
- Rights = Feed::Entry::Rights
- Source = Feed::Entry::Source
- Summary = Feed::Entry::Summary
- Title = Feed::Entry::Title
- Updated = Feed::Entry::Updated
- end
- end
-
- Atom::CommonModel::ELEMENTS.each do |name|
- BaseListener.install_get_text_element(Atom::URI, name, "#{name}=")
- end
-
- module ListenerMixin
- private
- def initial_start_feed(tag_name, prefix, attrs, ns)
- check_ns(tag_name, prefix, ns, Atom::URI, false)
-
- @rss = Atom::Feed.new(@version, @encoding, @standalone)
- @rss.do_validate = @do_validate
- @rss.xml_stylesheets = @xml_stylesheets
- @rss.lang = attrs["xml:lang"]
- @rss.base = attrs["xml:base"]
- @last_element = @rss
- pr = Proc.new do |text, tags|
- @rss.validate_for_stream(tags) if @do_validate
- end
- @proc_stack.push(pr)
- end
-
- def initial_start_entry(tag_name, prefix, attrs, ns)
- check_ns(tag_name, prefix, ns, Atom::URI, false)
-
- @rss = Atom::Entry.new(@version, @encoding, @standalone)
- @rss.do_validate = @do_validate
- @rss.xml_stylesheets = @xml_stylesheets
- @rss.lang = attrs["xml:lang"]
- @rss.base = attrs["xml:base"]
- @last_element = @rss
- pr = Proc.new do |text, tags|
- @rss.validate_for_stream(tags) if @do_validate
- end
- @proc_stack.push(pr)
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rss/content.rb b/ruby_1_9_3/lib/rss/content.rb
deleted file mode 100644
index b12ee918aa..0000000000
--- a/ruby_1_9_3/lib/rss/content.rb
+++ /dev/null
@@ -1,31 +0,0 @@
-require "rss/rss"
-
-module RSS
- CONTENT_PREFIX = 'content'
- CONTENT_URI = "http://purl.org/rss/1.0/modules/content/"
-
- module ContentModel
- extend BaseModel
-
- ELEMENTS = ["#{CONTENT_PREFIX}_encoded"]
-
- def self.append_features(klass)
- super
-
- klass.install_must_call_validator(CONTENT_PREFIX, CONTENT_URI)
- ELEMENTS.each do |full_name|
- name = full_name[(CONTENT_PREFIX.size + 1)..-1]
- klass.install_text_element(name, CONTENT_URI, "?", full_name)
- end
- end
- end
-
- prefix_size = CONTENT_PREFIX.size + 1
- ContentModel::ELEMENTS.each do |full_name|
- name = full_name[prefix_size..-1]
- BaseListener.install_get_text_element(CONTENT_URI, name, full_name)
- end
-end
-
-require 'rss/content/1.0'
-require 'rss/content/2.0'
diff --git a/ruby_1_9_3/lib/rss/content/1.0.rb b/ruby_1_9_3/lib/rss/content/1.0.rb
deleted file mode 100644
index e5dc857930..0000000000
--- a/ruby_1_9_3/lib/rss/content/1.0.rb
+++ /dev/null
@@ -1,9 +0,0 @@
-require 'rss/1.0'
-
-module RSS
- RDF.install_ns(CONTENT_PREFIX, CONTENT_URI)
-
- class RDF
- class Item; include ContentModel; end
- end
-end
diff --git a/ruby_1_9_3/lib/rss/content/2.0.rb b/ruby_1_9_3/lib/rss/content/2.0.rb
deleted file mode 100644
index 8491a99937..0000000000
--- a/ruby_1_9_3/lib/rss/content/2.0.rb
+++ /dev/null
@@ -1,11 +0,0 @@
-require "rss/2.0"
-
-module RSS
- Rss.install_ns(CONTENT_PREFIX, CONTENT_URI)
-
- class Rss
- class Channel
- class Item; include ContentModel; end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rss/converter.rb b/ruby_1_9_3/lib/rss/converter.rb
deleted file mode 100644
index 3e79eba4fb..0000000000
--- a/ruby_1_9_3/lib/rss/converter.rb
+++ /dev/null
@@ -1,170 +0,0 @@
-require "rss/utils"
-
-module RSS
-
- class Converter
-
- include Utils
-
- def initialize(to_enc, from_enc=nil)
- if "".respond_to?(:encode)
- @to_encoding = to_enc
- return
- end
- normalized_to_enc = to_enc.downcase.gsub(/-/, '_')
- from_enc ||= 'utf-8'
- normalized_from_enc = from_enc.downcase.gsub(/-/, '_')
- if normalized_to_enc == normalized_from_enc
- def_same_enc()
- else
- def_diff_enc = "def_to_#{normalized_to_enc}_from_#{normalized_from_enc}"
- if respond_to?(def_diff_enc)
- __send__(def_diff_enc)
- else
- def_else_enc(to_enc, from_enc)
- end
- end
- end
-
- def convert(value)
- if value.is_a?(String) and value.respond_to?(:encode)
- value.encode(@to_encoding)
- else
- value
- end
- end
-
- def def_convert(depth=0)
- instance_eval(<<-EOC, *get_file_and_line_from_caller(depth))
- def convert(value)
- if value.kind_of?(String)
- #{yield('value')}
- else
- value
- end
- end
- EOC
- end
-
- def def_iconv_convert(to_enc, from_enc, depth=0)
- begin
- require "iconv"
- @iconv = Iconv.new(to_enc, from_enc)
- def_convert(depth+1) do |value|
- <<-EOC
- begin
- @iconv.iconv(#{value})
- rescue Iconv::Failure
- raise ConversionError.new(#{value}, "#{to_enc}", "#{from_enc}")
- end
- EOC
- end
- rescue LoadError, ArgumentError, SystemCallError
- raise UnknownConversionMethodError.new(to_enc, from_enc)
- end
- end
-
- def def_else_enc(to_enc, from_enc)
- def_iconv_convert(to_enc, from_enc, 0)
- end
-
- def def_same_enc()
- def_convert do |value|
- value
- end
- end
-
- def def_uconv_convert_if_can(meth, to_enc, from_enc, nkf_arg)
- begin
- require "uconv"
- def_convert(1) do |value|
- <<-EOC
- begin
- Uconv.#{meth}(#{value})
- rescue Uconv::Error
- raise ConversionError.new(#{value}, "#{to_enc}", "#{from_enc}")
- end
- EOC
- end
- rescue LoadError
- require 'nkf'
- if NKF.const_defined?(:UTF8)
- def_convert(1) do |value|
- "NKF.nkf(#{nkf_arg.dump}, #{value})"
- end
- else
- def_iconv_convert(to_enc, from_enc, 1)
- end
- end
- end
-
- def def_to_euc_jp_from_utf_8
- def_uconv_convert_if_can('u8toeuc', 'EUC-JP', 'UTF-8', '-We')
- end
-
- def def_to_utf_8_from_euc_jp
- def_uconv_convert_if_can('euctou8', 'UTF-8', 'EUC-JP', '-Ew')
- end
-
- def def_to_shift_jis_from_utf_8
- def_uconv_convert_if_can('u8tosjis', 'Shift_JIS', 'UTF-8', '-Ws')
- end
-
- def def_to_utf_8_from_shift_jis
- def_uconv_convert_if_can('sjistou8', 'UTF-8', 'Shift_JIS', '-Sw')
- end
-
- def def_to_euc_jp_from_shift_jis
- require "nkf"
- def_convert do |value|
- "NKF.nkf('-Se', #{value})"
- end
- end
-
- def def_to_shift_jis_from_euc_jp
- require "nkf"
- def_convert do |value|
- "NKF.nkf('-Es', #{value})"
- end
- end
-
- def def_to_euc_jp_from_iso_2022_jp
- require "nkf"
- def_convert do |value|
- "NKF.nkf('-Je', #{value})"
- end
- end
-
- def def_to_iso_2022_jp_from_euc_jp
- require "nkf"
- def_convert do |value|
- "NKF.nkf('-Ej', #{value})"
- end
- end
-
- def def_to_utf_8_from_iso_8859_1
- def_convert do |value|
- "#{value}.unpack('C*').pack('U*')"
- end
- end
-
- def def_to_iso_8859_1_from_utf_8
- def_convert do |value|
- <<-EOC
- array_utf8 = #{value}.unpack('U*')
- array_enc = []
- array_utf8.each do |num|
- if num <= 0xFF
- array_enc << num
- else
- array_enc.concat "&\#\#{num};".unpack('C*')
- end
- end
- array_enc.pack('C*')
- EOC
- end
- end
-
- end
-
-end
diff --git a/ruby_1_9_3/lib/rss/dublincore.rb b/ruby_1_9_3/lib/rss/dublincore.rb
deleted file mode 100644
index 53a4ca70d6..0000000000
--- a/ruby_1_9_3/lib/rss/dublincore.rb
+++ /dev/null
@@ -1,161 +0,0 @@
-require "rss/rss"
-
-module RSS
- DC_PREFIX = 'dc'
- DC_URI = "http://purl.org/dc/elements/1.1/"
-
- module BaseDublinCoreModel
- def append_features(klass)
- super
-
- return if klass.instance_of?(Module)
- DublinCoreModel::ELEMENT_NAME_INFOS.each do |name, plural_name|
- plural = plural_name || "#{name}s"
- full_name = "#{DC_PREFIX}_#{name}"
- full_plural_name = "#{DC_PREFIX}_#{plural}"
- klass_name = "DublinCore#{Utils.to_class_name(name)}"
- klass.install_must_call_validator(DC_PREFIX, DC_URI)
- klass.install_have_children_element(name, DC_URI, "*",
- full_name, full_plural_name)
- klass.module_eval(<<-EOC, *get_file_and_line_from_caller(0))
- remove_method :#{full_name}
- remove_method :#{full_name}=
- remove_method :set_#{full_name}
-
- def #{full_name}
- @#{full_name}.first and @#{full_name}.first.value
- end
-
- def #{full_name}=(new_value)
- @#{full_name}[0] = Utils.new_with_value_if_need(#{klass_name}, new_value)
- end
- alias set_#{full_name} #{full_name}=
- EOC
- end
- klass.module_eval(<<-EOC, *get_file_and_line_from_caller(0))
- if method_defined?(:date)
- alias date_without_#{DC_PREFIX}_date= date=
-
- def date=(value)
- self.date_without_#{DC_PREFIX}_date = value
- self.#{DC_PREFIX}_date = value
- end
- else
- alias date #{DC_PREFIX}_date
- alias date= #{DC_PREFIX}_date=
- end
-
- # For backward compatibility
- alias #{DC_PREFIX}_rightses #{DC_PREFIX}_rights_list
- EOC
- end
- end
-
- module DublinCoreModel
-
- extend BaseModel
- extend BaseDublinCoreModel
-
- TEXT_ELEMENTS = {
- "title" => nil,
- "description" => nil,
- "creator" => nil,
- "subject" => nil,
- "publisher" => nil,
- "contributor" => nil,
- "type" => nil,
- "format" => nil,
- "identifier" => nil,
- "source" => nil,
- "language" => nil,
- "relation" => nil,
- "coverage" => nil,
- "rights" => "rights_list"
- }
-
- DATE_ELEMENTS = {
- "date" => "w3cdtf",
- }
-
- ELEMENT_NAME_INFOS = DublinCoreModel::TEXT_ELEMENTS.to_a
- DublinCoreModel::DATE_ELEMENTS.each do |name, |
- ELEMENT_NAME_INFOS << [name, nil]
- end
-
- ELEMENTS = TEXT_ELEMENTS.keys + DATE_ELEMENTS.keys
-
- ELEMENTS.each do |name, plural_name|
- module_eval(<<-EOC, *get_file_and_line_from_caller(0))
- class DublinCore#{Utils.to_class_name(name)} < Element
- include RSS10
-
- content_setup
-
- class << self
- def required_prefix
- DC_PREFIX
- end
-
- def required_uri
- DC_URI
- end
- end
-
- @tag_name = #{name.dump}
-
- alias_method(:value, :content)
- alias_method(:value=, :content=)
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.content = args[0]
- end
- end
-
- def full_name
- tag_name_with_prefix(DC_PREFIX)
- end
-
- def maker_target(target)
- target.new_#{name}
- end
-
- def setup_maker_attributes(#{name})
- #{name}.content = content
- end
- end
- EOC
- end
-
- DATE_ELEMENTS.each do |name, type|
- tag_name = "#{DC_PREFIX}:#{name}"
- module_eval(<<-EOC, *get_file_and_line_from_caller(0))
- class DublinCore#{Utils.to_class_name(name)} < Element
- remove_method(:content=)
- remove_method(:value=)
-
- date_writer("content", #{type.dump}, #{tag_name.dump})
-
- alias_method(:value=, :content=)
- end
- EOC
- end
- end
-
- # For backward compatibility
- DublincoreModel = DublinCoreModel
-
- DublinCoreModel::ELEMENTS.each do |name|
- class_name = Utils.to_class_name(name)
- BaseListener.install_class_name(DC_URI, name, "DublinCore#{class_name}")
- end
-
- DublinCoreModel::ELEMENTS.collect! {|name| "#{DC_PREFIX}_#{name}"}
-end
-
-require 'rss/dublincore/1.0'
-require 'rss/dublincore/2.0'
-require 'rss/dublincore/atom'
diff --git a/ruby_1_9_3/lib/rss/dublincore/1.0.rb b/ruby_1_9_3/lib/rss/dublincore/1.0.rb
deleted file mode 100644
index efe2f5dad4..0000000000
--- a/ruby_1_9_3/lib/rss/dublincore/1.0.rb
+++ /dev/null
@@ -1,12 +0,0 @@
-require "rss/1.0"
-
-module RSS
- RDF.install_ns(DC_PREFIX, DC_URI)
-
- class RDF
- class Channel; include DublinCoreModel; end
- class Image; include DublinCoreModel; end
- class Item; include DublinCoreModel; end
- class Textinput; include DublinCoreModel; end
- end
-end
diff --git a/ruby_1_9_3/lib/rss/dublincore/2.0.rb b/ruby_1_9_3/lib/rss/dublincore/2.0.rb
deleted file mode 100644
index a79c1e84a4..0000000000
--- a/ruby_1_9_3/lib/rss/dublincore/2.0.rb
+++ /dev/null
@@ -1,12 +0,0 @@
-require "rss/2.0"
-
-module RSS
- Rss.install_ns(DC_PREFIX, DC_URI)
-
- class Rss
- class Channel
- include DublinCoreModel
- class Item; include DublinCoreModel; end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rss/dublincore/atom.rb b/ruby_1_9_3/lib/rss/dublincore/atom.rb
deleted file mode 100644
index 8db9066bb8..0000000000
--- a/ruby_1_9_3/lib/rss/dublincore/atom.rb
+++ /dev/null
@@ -1,16 +0,0 @@
-require "rss/atom"
-
-module RSS
- module Atom
- Feed.install_ns(DC_PREFIX, DC_URI)
-
- class Feed
- include DublinCoreModel
- class Entry; include DublinCoreModel; end
- end
-
- class Entry
- include DublinCoreModel
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rss/image.rb b/ruby_1_9_3/lib/rss/image.rb
deleted file mode 100644
index e79e9f5e65..0000000000
--- a/ruby_1_9_3/lib/rss/image.rb
+++ /dev/null
@@ -1,193 +0,0 @@
-require 'rss/1.0'
-require 'rss/dublincore'
-
-module RSS
-
- IMAGE_PREFIX = 'image'
- IMAGE_URI = 'http://purl.org/rss/1.0/modules/image/'
-
- RDF.install_ns(IMAGE_PREFIX, IMAGE_URI)
-
- IMAGE_ELEMENTS = []
-
- %w(item favicon).each do |name|
- class_name = Utils.to_class_name(name)
- BaseListener.install_class_name(IMAGE_URI, name, "Image#{class_name}")
- IMAGE_ELEMENTS << "#{IMAGE_PREFIX}_#{name}"
- end
-
- module ImageModelUtils
- def validate_one_tag_name(ignore_unknown_element, name, tags)
- if !ignore_unknown_element
- invalid = tags.find {|tag| tag != name}
- raise UnknownTagError.new(invalid, IMAGE_URI) if invalid
- end
- raise TooMuchTagError.new(name, tag_name) if tags.size > 1
- end
- end
-
- module ImageItemModel
- include ImageModelUtils
- extend BaseModel
-
- def self.append_features(klass)
- super
-
- klass.install_have_child_element("item", IMAGE_URI, "?",
- "#{IMAGE_PREFIX}_item")
- klass.install_must_call_validator(IMAGE_PREFIX, IMAGE_URI)
- end
-
- class ImageItem < Element
- include RSS10
- include DublinCoreModel
-
- @tag_name = "item"
-
- class << self
- def required_prefix
- IMAGE_PREFIX
- end
-
- def required_uri
- IMAGE_URI
- end
- end
-
- install_must_call_validator(IMAGE_PREFIX, IMAGE_URI)
-
- [
- ["about", ::RSS::RDF::URI, true],
- ["resource", ::RSS::RDF::URI, false],
- ].each do |name, uri, required|
- install_get_attribute(name, uri, required, nil, nil,
- "#{::RSS::RDF::PREFIX}:#{name}")
- end
-
- %w(width height).each do |tag|
- full_name = "#{IMAGE_PREFIX}_#{tag}"
- disp_name = "#{IMAGE_PREFIX}:#{tag}"
- install_text_element(tag, IMAGE_URI, "?",
- full_name, :integer, disp_name)
- BaseListener.install_get_text_element(IMAGE_URI, tag, full_name)
- end
-
- alias width= image_width=
- alias width image_width
- alias height= image_height=
- alias height image_height
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.about = args[0]
- self.resource = args[1]
- end
- end
-
- def full_name
- tag_name_with_prefix(IMAGE_PREFIX)
- end
-
- private
- def maker_target(target)
- target.image_item
- end
-
- def setup_maker_attributes(item)
- item.about = self.about
- item.resource = self.resource
- end
- end
- end
-
- module ImageFaviconModel
- include ImageModelUtils
- extend BaseModel
-
- def self.append_features(klass)
- super
-
- unless klass.class == Module
- klass.install_have_child_element("favicon", IMAGE_URI, "?",
- "#{IMAGE_PREFIX}_favicon")
- klass.install_must_call_validator(IMAGE_PREFIX, IMAGE_URI)
- end
- end
-
- class ImageFavicon < Element
- include RSS10
- include DublinCoreModel
-
- @tag_name = "favicon"
-
- class << self
- def required_prefix
- IMAGE_PREFIX
- end
-
- def required_uri
- IMAGE_URI
- end
- end
-
- [
- ["about", ::RSS::RDF::URI, true, ::RSS::RDF::PREFIX],
- ["size", IMAGE_URI, true, IMAGE_PREFIX],
- ].each do |name, uri, required, prefix|
- install_get_attribute(name, uri, required, nil, nil,
- "#{prefix}:#{name}")
- end
-
- AVAILABLE_SIZES = %w(small medium large)
- alias_method :set_size, :size=
- private :set_size
- def size=(new_value)
- if @do_validate and !new_value.nil?
- new_value = new_value.strip
- unless AVAILABLE_SIZES.include?(new_value)
- attr_name = "#{IMAGE_PREFIX}:size"
- raise NotAvailableValueError.new(full_name, new_value, attr_name)
- end
- end
- set_size(new_value)
- end
-
- alias image_size= size=
- alias image_size size
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.about = args[0]
- self.size = args[1]
- end
- end
-
- def full_name
- tag_name_with_prefix(IMAGE_PREFIX)
- end
-
- private
- def maker_target(target)
- target.image_favicon
- end
-
- def setup_maker_attributes(favicon)
- favicon.about = self.about
- favicon.size = self.size
- end
- end
-
- end
-
- class RDF
- class Channel; include ImageFaviconModel; end
- class Item; include ImageItemModel; end
- end
-
-end
diff --git a/ruby_1_9_3/lib/rss/itunes.rb b/ruby_1_9_3/lib/rss/itunes.rb
deleted file mode 100644
index f95ca7aa2e..0000000000
--- a/ruby_1_9_3/lib/rss/itunes.rb
+++ /dev/null
@@ -1,410 +0,0 @@
-require 'rss/2.0'
-
-module RSS
- ITUNES_PREFIX = 'itunes'
- ITUNES_URI = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
-
- Rss.install_ns(ITUNES_PREFIX, ITUNES_URI)
-
- module ITunesModelUtils
- include Utils
-
- def def_class_accessor(klass, name, type, *args)
- normalized_name = name.gsub(/-/, "_")
- full_name = "#{ITUNES_PREFIX}_#{normalized_name}"
- klass_name = "ITunes#{Utils.to_class_name(normalized_name)}"
-
- case type
- when :element, :attribute
- klass::ELEMENTS << full_name
- def_element_class_accessor(klass, name, full_name, klass_name, *args)
- when :elements
- klass::ELEMENTS << full_name
- def_elements_class_accessor(klass, name, full_name, klass_name, *args)
- else
- klass.install_must_call_validator(ITUNES_PREFIX, ITUNES_URI)
- klass.install_text_element(normalized_name, ITUNES_URI, "?",
- full_name, type, name)
- end
- end
-
- def def_element_class_accessor(klass, name, full_name, klass_name,
- recommended_attribute_name=nil)
- klass.install_have_child_element(name, ITUNES_PREFIX, "?", full_name)
- end
-
- def def_elements_class_accessor(klass, name, full_name, klass_name,
- plural_name, recommended_attribute_name=nil)
- full_plural_name = "#{ITUNES_PREFIX}_#{plural_name}"
- klass.install_have_children_element(name, ITUNES_PREFIX, "*",
- full_name, full_plural_name)
- end
- end
-
- module ITunesBaseModel
- extend ITunesModelUtils
-
- ELEMENTS = []
-
- ELEMENT_INFOS = [["author"],
- ["block", :yes_other],
- ["explicit", :yes_clean_other],
- ["keywords", :csv],
- ["subtitle"],
- ["summary"]]
- end
-
- module ITunesChannelModel
- extend BaseModel
- extend ITunesModelUtils
- include ITunesBaseModel
-
- ELEMENTS = []
-
- class << self
- def append_features(klass)
- super
-
- return if klass.instance_of?(Module)
- ELEMENT_INFOS.each do |name, type, *additional_infos|
- def_class_accessor(klass, name, type, *additional_infos)
- end
- end
- end
-
- ELEMENT_INFOS = [
- ["category", :elements, "categories", "text"],
- ["image", :attribute, "href"],
- ["owner", :element],
- ["new-feed-url"],
- ] + ITunesBaseModel::ELEMENT_INFOS
-
- class ITunesCategory < Element
- include RSS09
-
- @tag_name = "category"
-
- class << self
- def required_prefix
- ITUNES_PREFIX
- end
-
- def required_uri
- ITUNES_URI
- end
- end
-
- [
- ["text", "", true]
- ].each do |name, uri, required|
- install_get_attribute(name, uri, required)
- end
-
- ITunesCategory = self
- install_have_children_element("category", ITUNES_URI, "*",
- "#{ITUNES_PREFIX}_category",
- "#{ITUNES_PREFIX}_categories")
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.text = args[0]
- end
- end
-
- def full_name
- tag_name_with_prefix(ITUNES_PREFIX)
- end
-
- private
- def maker_target(categories)
- if text or !itunes_categories.empty?
- categories.new_category
- else
- nil
- end
- end
-
- def setup_maker_attributes(category)
- category.text = text if text
- end
-
- def setup_maker_elements(category)
- super(category)
- itunes_categories.each do |sub_category|
- sub_category.setup_maker(category)
- end
- end
- end
-
- class ITunesImage < Element
- include RSS09
-
- @tag_name = "image"
-
- class << self
- def required_prefix
- ITUNES_PREFIX
- end
-
- def required_uri
- ITUNES_URI
- end
- end
-
- [
- ["href", "", true]
- ].each do |name, uri, required|
- install_get_attribute(name, uri, required)
- end
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.href = args[0]
- end
- end
-
- def full_name
- tag_name_with_prefix(ITUNES_PREFIX)
- end
-
- private
- def maker_target(target)
- if href
- target.itunes_image {|image| image}
- else
- nil
- end
- end
-
- def setup_maker_attributes(image)
- image.href = href
- end
- end
-
- class ITunesOwner < Element
- include RSS09
-
- @tag_name = "owner"
-
- class << self
- def required_prefix
- ITUNES_PREFIX
- end
-
- def required_uri
- ITUNES_URI
- end
- end
-
- install_must_call_validator(ITUNES_PREFIX, ITUNES_URI)
- [
- ["name"],
- ["email"],
- ].each do |name,|
- ITunesBaseModel::ELEMENT_INFOS << name
- install_text_element(name, ITUNES_URI, nil, "#{ITUNES_PREFIX}_#{name}")
- end
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.itunes_name = args[0]
- self.itunes_email = args[1]
- end
- end
-
- def full_name
- tag_name_with_prefix(ITUNES_PREFIX)
- end
-
- private
- def maker_target(target)
- target.itunes_owner
- end
-
- def setup_maker_element(owner)
- super(owner)
- owner.itunes_name = itunes_name
- owner.itunes_email = itunes_email
- end
- end
- end
-
- module ITunesItemModel
- extend BaseModel
- extend ITunesModelUtils
- include ITunesBaseModel
-
- class << self
- def append_features(klass)
- super
-
- return if klass.instance_of?(Module)
- ELEMENT_INFOS.each do |name, type|
- def_class_accessor(klass, name, type)
- end
- end
- end
-
- ELEMENT_INFOS = ITunesBaseModel::ELEMENT_INFOS +
- [["duration", :element, "content"]]
-
- class ITunesDuration < Element
- include RSS09
-
- @tag_name = "duration"
-
- class << self
- def required_prefix
- ITUNES_PREFIX
- end
-
- def required_uri
- ITUNES_URI
- end
-
- def parse(duration, do_validate=true)
- if do_validate and /\A(?:
- \d?\d:[0-5]\d:[0-5]\d|
- [0-5]?\d:[0-5]\d
- )\z/x !~ duration
- raise ArgumentError,
- "must be one of HH:MM:SS, H:MM:SS, MM::SS, M:SS: " +
- duration.inspect
- end
-
- components = duration.split(':')
- components[3..-1] = nil if components.size > 3
-
- components.unshift("00") until components.size == 3
-
- components.collect do |component|
- component.to_i
- end
- end
-
- def construct(hour, minute, second)
- components = [minute, second]
- if components.include?(nil)
- nil
- else
- components.unshift(hour) if hour and hour > 0
- components.collect do |component|
- "%02d" % component
- end.join(":")
- end
- end
- end
-
- content_setup
- alias_method(:value, :content)
- remove_method(:content=)
-
- attr_reader :hour, :minute, :second
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- args = args[0] if args.size == 1 and args[0].is_a?(Array)
- if args.size == 1
- self.content = args[0]
- elsif args.size > 3
- raise ArgumentError,
- "must be (do_validate, params), (content), " +
- "(minute, second), ([minute, second]), " +
- "(hour, minute, second) or ([hour, minute, second]): " +
- args.inspect
- else
- @second, @minute, @hour = args.reverse
- update_content
- end
- end
- end
-
- def content=(value)
- if value.nil?
- @content = nil
- elsif value.is_a?(self.class)
- self.content = value.content
- else
- begin
- @hour, @minute, @second = self.class.parse(value, @do_validate)
- rescue ArgumentError
- raise NotAvailableValueError.new(tag_name, value)
- end
- @content = value
- end
- end
- alias_method(:value=, :content=)
-
- def hour=(hour)
- @hour = @do_validate ? Integer(hour) : hour.to_i
- update_content
- hour
- end
-
- def minute=(minute)
- @minute = @do_validate ? Integer(minute) : minute.to_i
- update_content
- minute
- end
-
- def second=(second)
- @second = @do_validate ? Integer(second) : second.to_i
- update_content
- second
- end
-
- def full_name
- tag_name_with_prefix(ITUNES_PREFIX)
- end
-
- private
- def update_content
- @content = self.class.construct(hour, minute, second)
- end
-
- def maker_target(target)
- if @content
- target.itunes_duration {|duration| duration}
- else
- nil
- end
- end
-
- def setup_maker_element(duration)
- super(duration)
- duration.content = @content
- end
- end
- end
-
- class Rss
- class Channel
- include ITunesChannelModel
- class Item; include ITunesItemModel; end
- end
- end
-
- element_infos =
- ITunesChannelModel::ELEMENT_INFOS + ITunesItemModel::ELEMENT_INFOS
- element_infos.each do |name, type|
- case type
- when :element, :elements, :attribute
- class_name = Utils.to_class_name(name)
- BaseListener.install_class_name(ITUNES_URI, name, "ITunes#{class_name}")
- else
- accessor_base = "#{ITUNES_PREFIX}_#{name.gsub(/-/, '_')}"
- BaseListener.install_get_text_element(ITUNES_URI, name, accessor_base)
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rss/maker.rb b/ruby_1_9_3/lib/rss/maker.rb
deleted file mode 100644
index a7ee200b32..0000000000
--- a/ruby_1_9_3/lib/rss/maker.rb
+++ /dev/null
@@ -1,54 +0,0 @@
-require "rss/rss"
-
-module RSS
- module Maker
- MAKERS = {}
-
- class << self
- def make(version, &block)
- self[version].make(&block)
- end
-
- def [](version)
- maker_info = maker(version)
- raise UnsupportedMakerVersionError.new(version) if maker_info.nil?
- maker_info[:maker]
- end
-
- def add_maker(version, normalized_version, maker)
- MAKERS[version] = {:maker => maker, :version => normalized_version}
- end
-
- def versions
- MAKERS.keys.uniq.sort
- end
-
- def makers
- MAKERS.values.collect {|info| info[:maker]}.uniq
- end
-
- def supported?(version)
- versions.include?(version)
- end
-
- private
- # Can I remove this method?
- def maker(version)
- MAKERS[version]
- end
- end
- end
-end
-
-require "rss/maker/1.0"
-require "rss/maker/2.0"
-require "rss/maker/feed"
-require "rss/maker/entry"
-require "rss/maker/content"
-require "rss/maker/dublincore"
-require "rss/maker/slash"
-require "rss/maker/syndication"
-require "rss/maker/taxonomy"
-require "rss/maker/trackback"
-require "rss/maker/image"
-require "rss/maker/itunes"
diff --git a/ruby_1_9_3/lib/rss/maker/0.9.rb b/ruby_1_9_3/lib/rss/maker/0.9.rb
deleted file mode 100644
index c398343ec4..0000000000
--- a/ruby_1_9_3/lib/rss/maker/0.9.rb
+++ /dev/null
@@ -1,508 +0,0 @@
-require "rss/0.9"
-
-require "rss/maker/base"
-
-module RSS
- module Maker
-
- class RSS09 < RSSBase
-
- def initialize(feed_version)
- super
- @feed_type = "rss"
- end
-
- private
- def make_feed
- Rss.new(@feed_version, @version, @encoding, @standalone)
- end
-
- def setup_elements(rss)
- setup_channel(rss)
- end
-
- class Channel < ChannelBase
- def to_feed(rss)
- channel = Rss::Channel.new
- setup_values(channel)
- _not_set_required_variables = not_set_required_variables
- if _not_set_required_variables.empty?
- rss.channel = channel
- set_parent(channel, rss)
- setup_items(rss)
- setup_image(rss)
- setup_textinput(rss)
- setup_other_elements(rss, channel)
- rss
- else
- raise NotSetError.new("maker.channel", _not_set_required_variables)
- end
- end
-
- private
- def setup_items(rss)
- @maker.items.to_feed(rss)
- end
-
- def setup_image(rss)
- @maker.image.to_feed(rss)
- end
-
- def setup_textinput(rss)
- @maker.textinput.to_feed(rss)
- end
-
- def variables
- super + ["pubDate"]
- end
-
- def required_variable_names
- %w(link language)
- end
-
- def not_set_required_variables
- vars = super
- vars << "description" unless description {|d| d.have_required_values?}
- vars << "title" unless title {|t| t.have_required_values?}
- vars
- end
-
- class SkipDays < SkipDaysBase
- def to_feed(rss, channel)
- unless @days.empty?
- skipDays = Rss::Channel::SkipDays.new
- channel.skipDays = skipDays
- set_parent(skipDays, channel)
- @days.each do |day|
- day.to_feed(rss, skipDays.days)
- end
- end
- end
-
- class Day < DayBase
- def to_feed(rss, days)
- day = Rss::Channel::SkipDays::Day.new
- set = setup_values(day)
- if set
- days << day
- set_parent(day, days)
- setup_other_elements(rss, day)
- end
- end
-
- private
- def required_variable_names
- %w(content)
- end
- end
- end
-
- class SkipHours < SkipHoursBase
- def to_feed(rss, channel)
- unless @hours.empty?
- skipHours = Rss::Channel::SkipHours.new
- channel.skipHours = skipHours
- set_parent(skipHours, channel)
- @hours.each do |hour|
- hour.to_feed(rss, skipHours.hours)
- end
- end
- end
-
- class Hour < HourBase
- def to_feed(rss, hours)
- hour = Rss::Channel::SkipHours::Hour.new
- set = setup_values(hour)
- if set
- hours << hour
- set_parent(hour, hours)
- setup_other_elements(rss, hour)
- end
- end
-
- private
- def required_variable_names
- %w(content)
- end
- end
- end
-
- class Cloud < CloudBase
- def to_feed(*args)
- end
- end
-
- class Categories < CategoriesBase
- def to_feed(*args)
- end
-
- class Category < CategoryBase
- end
- end
-
- class Links < LinksBase
- def to_feed(rss, channel)
- return if @links.empty?
- @links.first.to_feed(rss, channel)
- end
-
- class Link < LinkBase
- def to_feed(rss, channel)
- if have_required_values?
- channel.link = href
- else
- raise NotSetError.new("maker.channel.link",
- not_set_required_variables)
- end
- end
-
- private
- def required_variable_names
- %w(href)
- end
- end
- end
-
- class Authors < AuthorsBase
- def to_feed(rss, channel)
- end
-
- class Author < AuthorBase
- def to_feed(rss, channel)
- end
- end
- end
-
- class Contributors < ContributorsBase
- def to_feed(rss, channel)
- end
-
- class Contributor < ContributorBase
- end
- end
-
- class Generator < GeneratorBase
- def to_feed(rss, channel)
- end
- end
-
- class Copyright < CopyrightBase
- def to_feed(rss, channel)
- channel.copyright = content if have_required_values?
- end
-
- private
- def required_variable_names
- %w(content)
- end
- end
-
- class Description < DescriptionBase
- def to_feed(rss, channel)
- channel.description = content if have_required_values?
- end
-
- private
- def required_variable_names
- %w(content)
- end
- end
-
- class Title < TitleBase
- def to_feed(rss, channel)
- channel.title = content if have_required_values?
- end
-
- private
- def required_variable_names
- %w(content)
- end
- end
- end
-
- class Image < ImageBase
- def to_feed(rss)
- image = Rss::Channel::Image.new
- set = setup_values(image)
- if set
- image.link = link
- rss.channel.image = image
- set_parent(image, rss.channel)
- setup_other_elements(rss, image)
- elsif required_element?
- raise NotSetError.new("maker.image", not_set_required_variables)
- end
- end
-
- private
- def required_variable_names
- %w(url title link)
- end
-
- def required_element?
- true
- end
- end
-
- class Items < ItemsBase
- def to_feed(rss)
- if rss.channel
- normalize.each do |item|
- item.to_feed(rss)
- end
- setup_other_elements(rss, rss.items)
- end
- end
-
- class Item < ItemBase
- def to_feed(rss)
- item = Rss::Channel::Item.new
- setup_values(item)
- _not_set_required_variables = not_set_required_variables
- if _not_set_required_variables.empty?
- rss.items << item
- set_parent(item, rss.channel)
- setup_other_elements(rss, item)
- elsif variable_is_set?
- raise NotSetError.new("maker.items", _not_set_required_variables)
- end
- end
-
- private
- def required_variable_names
- []
- end
-
- def not_set_required_variables
- vars = super
- if @maker.feed_version == "0.91"
- vars << "title" unless title {|t| t.have_required_values?}
- vars << "link" unless link {|l| l.have_required_values?}
- end
- vars
- end
-
- class Guid < GuidBase
- def to_feed(*args)
- end
- end
-
- class Enclosure < EnclosureBase
- def to_feed(*args)
- end
- end
-
- class Source < SourceBase
- def to_feed(*args)
- end
-
- class Authors < AuthorsBase
- def to_feed(*args)
- end
-
- class Author < AuthorBase
- end
- end
-
- class Categories < CategoriesBase
- def to_feed(*args)
- end
-
- class Category < CategoryBase
- end
- end
-
- class Contributors < ContributorsBase
- def to_feed(*args)
- end
-
- class Contributor < ContributorBase
- end
- end
-
- class Generator < GeneratorBase
- def to_feed(*args)
- end
- end
-
- class Icon < IconBase
- def to_feed(*args)
- end
- end
-
- class Links < LinksBase
- def to_feed(*args)
- end
-
- class Link < LinkBase
- end
- end
-
- class Logo < LogoBase
- def to_feed(*args)
- end
- end
-
- class Rights < RightsBase
- def to_feed(*args)
- end
- end
-
- class Subtitle < SubtitleBase
- def to_feed(*args)
- end
- end
-
- class Title < TitleBase
- def to_feed(*args)
- end
- end
- end
-
- class Categories < CategoriesBase
- def to_feed(*args)
- end
-
- class Category < CategoryBase
- end
- end
-
- class Authors < AuthorsBase
- def to_feed(*args)
- end
-
- class Author < AuthorBase
- end
- end
-
- class Links < LinksBase
- def to_feed(rss, item)
- return if @links.empty?
- @links.first.to_feed(rss, item)
- end
-
- class Link < LinkBase
- def to_feed(rss, item)
- if have_required_values?
- item.link = href
- else
- raise NotSetError.new("maker.link",
- not_set_required_variables)
- end
- end
-
- private
- def required_variable_names
- %w(href)
- end
- end
- end
-
- class Contributors < ContributorsBase
- def to_feed(rss, item)
- end
-
- class Contributor < ContributorBase
- end
- end
-
- class Rights < RightsBase
- def to_feed(rss, item)
- end
- end
-
- class Description < DescriptionBase
- def to_feed(rss, item)
- item.description = content if have_required_values?
- end
-
- private
- def required_variable_names
- %w(content)
- end
- end
-
- class Content < ContentBase
- def to_feed(rss, item)
- end
- end
-
- class Title < TitleBase
- def to_feed(rss, item)
- item.title = content if have_required_values?
- end
-
- private
- def required_variable_names
- %w(content)
- end
- end
- end
- end
-
- class Textinput < TextinputBase
- def to_feed(rss)
- textInput = Rss::Channel::TextInput.new
- set = setup_values(textInput)
- if set
- rss.channel.textInput = textInput
- set_parent(textInput, rss.channel)
- setup_other_elements(rss, textInput)
- end
- end
-
- private
- def required_variable_names
- %w(title description name link)
- end
- end
- end
-
- class RSS091 < RSS09
- def initialize(feed_version="0.91")
- super
- end
-
- class Channel < RSS09::Channel
- end
-
- class Items < RSS09::Items
- class Item < RSS09::Items::Item
- end
- end
-
- class Image < RSS09::Image
- end
-
- class Textinput < RSS09::Textinput
- end
- end
-
- class RSS092 < RSS09
- def initialize(feed_version="0.92")
- super
- end
-
- class Channel < RSS09::Channel
- end
-
- class Items < RSS09::Items
- class Item < RSS09::Items::Item
- end
- end
-
- class Image < RSS09::Image
- end
-
- class Textinput < RSS09::Textinput
- end
- end
-
- add_maker("0.9", "0.92", RSS092)
- add_maker("0.91", "0.91", RSS091)
- add_maker("0.92", "0.92", RSS092)
- add_maker("rss0.9", "0.92", RSS092)
- add_maker("rss0.91", "0.91", RSS091)
- add_maker("rss0.92", "0.92", RSS092)
- end
-end
diff --git a/ruby_1_9_3/lib/rss/maker/1.0.rb b/ruby_1_9_3/lib/rss/maker/1.0.rb
deleted file mode 100644
index 1b9f7c3b79..0000000000
--- a/ruby_1_9_3/lib/rss/maker/1.0.rb
+++ /dev/null
@@ -1,435 +0,0 @@
-require "rss/1.0"
-
-require "rss/maker/base"
-
-module RSS
- module Maker
-
- class RSS10 < RSSBase
-
- def initialize(feed_version="1.0")
- super
- @feed_type = "rss"
- end
-
- private
- def make_feed
- RDF.new(@version, @encoding, @standalone)
- end
-
- def setup_elements(rss)
- setup_channel(rss)
- setup_image(rss)
- setup_items(rss)
- setup_textinput(rss)
- end
-
- class Channel < ChannelBase
- include SetupDefaultLanguage
-
- def to_feed(rss)
- set_default_values do
- _not_set_required_variables = not_set_required_variables
- if _not_set_required_variables.empty?
- channel = RDF::Channel.new(@about)
- setup_values(channel)
- channel.dc_dates.clear
- rss.channel = channel
- set_parent(channel, rss)
- setup_items(rss)
- setup_image(rss)
- setup_textinput(rss)
- setup_other_elements(rss, channel)
- else
- raise NotSetError.new("maker.channel", _not_set_required_variables)
- end
- end
- end
-
- private
- def setup_items(rss)
- items = RDF::Channel::Items.new
- seq = items.Seq
- set_parent(items, seq)
- target_items = @maker.items.normalize
- raise NotSetError.new("maker", ["items"]) if target_items.empty?
- target_items.each do |item|
- li = RDF::Channel::Items::Seq::Li.new(item.link)
- seq.lis << li
- set_parent(li, seq)
- end
- rss.channel.items = items
- set_parent(rss.channel, items)
- end
-
- def setup_image(rss)
- if @maker.image.have_required_values?
- image = RDF::Channel::Image.new(@maker.image.url)
- rss.channel.image = image
- set_parent(image, rss.channel)
- end
- end
-
- def setup_textinput(rss)
- if @maker.textinput.have_required_values?
- textinput = RDF::Channel::Textinput.new(@maker.textinput.link)
- rss.channel.textinput = textinput
- set_parent(textinput, rss.channel)
- end
- end
-
- def required_variable_names
- %w(about link)
- end
-
- def not_set_required_variables
- vars = super
- vars << "description" unless description {|d| d.have_required_values?}
- vars << "title" unless title {|t| t.have_required_values?}
- vars
- end
-
- class SkipDays < SkipDaysBase
- def to_feed(*args)
- end
-
- class Day < DayBase
- end
- end
-
- class SkipHours < SkipHoursBase
- def to_feed(*args)
- end
-
- class Hour < HourBase
- end
- end
-
- class Cloud < CloudBase
- def to_feed(*args)
- end
- end
-
- class Categories < CategoriesBase
- def to_feed(*args)
- end
-
- class Category < CategoryBase
- end
- end
-
- class Links < LinksBase
- def to_feed(rss, channel)
- return if @links.empty?
- @links.first.to_feed(rss, channel)
- end
-
- class Link < LinkBase
- def to_feed(rss, channel)
- if have_required_values?
- channel.link = href
- else
- raise NotSetError.new("maker.channel.link",
- not_set_required_variables)
- end
- end
-
- private
- def required_variable_names
- %w(href)
- end
- end
- end
-
- class Authors < AuthorsBase
- def to_feed(rss, channel)
- end
-
- class Author < AuthorBase
- def to_feed(rss, channel)
- end
- end
- end
-
- class Contributors < ContributorsBase
- def to_feed(rss, channel)
- end
-
- class Contributor < ContributorBase
- end
- end
-
- class Generator < GeneratorBase
- def to_feed(rss, channel)
- end
- end
-
- class Copyright < CopyrightBase
- def to_feed(rss, channel)
- end
- end
-
- class Description < DescriptionBase
- def to_feed(rss, channel)
- channel.description = content if have_required_values?
- end
-
- private
- def required_variable_names
- %w(content)
- end
- end
-
- class Title < TitleBase
- def to_feed(rss, channel)
- channel.title = content if have_required_values?
- end
-
- private
- def required_variable_names
- %w(content)
- end
- end
- end
-
- class Image < ImageBase
- def to_feed(rss)
- if @url
- image = RDF::Image.new(@url)
- set = setup_values(image)
- if set
- rss.image = image
- set_parent(image, rss)
- setup_other_elements(rss, image)
- end
- end
- end
-
- def have_required_values?
- super and @maker.channel.have_required_values?
- end
-
- private
- def variables
- super + ["link"]
- end
-
- def required_variable_names
- %w(url title link)
- end
- end
-
- class Items < ItemsBase
- def to_feed(rss)
- if rss.channel
- normalize.each do |item|
- item.to_feed(rss)
- end
- setup_other_elements(rss, rss.items)
- end
- end
-
- class Item < ItemBase
- def to_feed(rss)
- set_default_values do
- item = RDF::Item.new(link)
- set = setup_values(item)
- if set
- item.dc_dates.clear
- rss.items << item
- set_parent(item, rss)
- setup_other_elements(rss, item)
- elsif !have_required_values?
- raise NotSetError.new("maker.item", not_set_required_variables)
- end
- end
- end
-
- private
- def required_variable_names
- %w(link)
- end
-
- def variables
- super + %w(link)
- end
-
- def not_set_required_variables
- set_default_values do
- vars = super
- vars << "title" unless title {|t| t.have_required_values?}
- vars
- end
- end
-
- class Guid < GuidBase
- def to_feed(*args)
- end
- end
-
- class Enclosure < EnclosureBase
- def to_feed(*args)
- end
- end
-
- class Source < SourceBase
- def to_feed(*args)
- end
-
- class Authors < AuthorsBase
- def to_feed(*args)
- end
-
- class Author < AuthorBase
- end
- end
-
- class Categories < CategoriesBase
- def to_feed(*args)
- end
-
- class Category < CategoryBase
- end
- end
-
- class Contributors < ContributorsBase
- def to_feed(*args)
- end
-
- class Contributor < ContributorBase
- end
- end
-
- class Generator < GeneratorBase
- def to_feed(*args)
- end
- end
-
- class Icon < IconBase
- def to_feed(*args)
- end
- end
-
- class Links < LinksBase
- def to_feed(*args)
- end
-
- class Link < LinkBase
- end
- end
-
- class Logo < LogoBase
- def to_feed(*args)
- end
- end
-
- class Rights < RightsBase
- def to_feed(*args)
- end
- end
-
- class Subtitle < SubtitleBase
- def to_feed(*args)
- end
- end
-
- class Title < TitleBase
- def to_feed(*args)
- end
- end
- end
-
- class Categories < CategoriesBase
- def to_feed(*args)
- end
-
- class Category < CategoryBase
- end
- end
-
- class Authors < AuthorsBase
- def to_feed(*args)
- end
-
- class Author < AuthorBase
- end
- end
-
- class Links < LinksBase
- def to_feed(*args)
- end
-
- class Link < LinkBase
- end
- end
-
- class Contributors < ContributorsBase
- def to_feed(rss, item)
- end
-
- class Contributor < ContributorBase
- end
- end
-
- class Rights < RightsBase
- def to_feed(rss, item)
- end
- end
-
- class Description < DescriptionBase
- def to_feed(rss, item)
- item.description = content if have_required_values?
- end
-
- private
- def required_variable_names
- %w(content)
- end
- end
-
- class Content < ContentBase
- def to_feed(rss, item)
- end
- end
-
- class Title < TitleBase
- def to_feed(rss, item)
- item.title = content if have_required_values?
- end
-
- private
- def required_variable_names
- %w(content)
- end
- end
- end
- end
-
- class Textinput < TextinputBase
- def to_feed(rss)
- if @link
- textinput = RDF::Textinput.new(@link)
- set = setup_values(textinput)
- if set
- rss.textinput = textinput
- set_parent(textinput, rss)
- setup_other_elements(rss, textinput)
- end
- end
- end
-
- def have_required_values?
- super and @maker.channel.have_required_values?
- end
-
- private
- def required_variable_names
- %w(title description name link)
- end
- end
- end
-
- add_maker("1.0", "1.0", RSS10)
- add_maker("rss1.0", "1.0", RSS10)
- end
-end
diff --git a/ruby_1_9_3/lib/rss/maker/2.0.rb b/ruby_1_9_3/lib/rss/maker/2.0.rb
deleted file mode 100644
index 15b1349c2a..0000000000
--- a/ruby_1_9_3/lib/rss/maker/2.0.rb
+++ /dev/null
@@ -1,223 +0,0 @@
-require "rss/2.0"
-
-require "rss/maker/0.9"
-
-module RSS
- module Maker
-
- class RSS20 < RSS09
-
- def initialize(feed_version="2.0")
- super
- end
-
- class Channel < RSS09::Channel
-
- private
- def required_variable_names
- %w(link)
- end
-
- class SkipDays < RSS09::Channel::SkipDays
- class Day < RSS09::Channel::SkipDays::Day
- end
- end
-
- class SkipHours < RSS09::Channel::SkipHours
- class Hour < RSS09::Channel::SkipHours::Hour
- end
- end
-
- class Cloud < RSS09::Channel::Cloud
- def to_feed(rss, channel)
- cloud = Rss::Channel::Cloud.new
- set = setup_values(cloud)
- if set
- channel.cloud = cloud
- set_parent(cloud, channel)
- setup_other_elements(rss, cloud)
- end
- end
-
- private
- def required_variable_names
- %w(domain port path registerProcedure protocol)
- end
- end
-
- class Categories < RSS09::Channel::Categories
- def to_feed(rss, channel)
- @categories.each do |category|
- category.to_feed(rss, channel)
- end
- end
-
- class Category < RSS09::Channel::Categories::Category
- def to_feed(rss, channel)
- category = Rss::Channel::Category.new
- set = setup_values(category)
- if set
- channel.categories << category
- set_parent(category, channel)
- setup_other_elements(rss, category)
- end
- end
-
- private
- def required_variable_names
- %w(content)
- end
- end
- end
-
- class Generator < GeneratorBase
- def to_feed(rss, channel)
- channel.generator = content
- end
-
- private
- def required_variable_names
- %w(content)
- end
- end
- end
-
- class Image < RSS09::Image
- private
- def required_element?
- false
- end
- end
-
- class Items < RSS09::Items
- class Item < RSS09::Items::Item
- private
- def required_variable_names
- []
- end
-
- def not_set_required_variables
- vars = super
- if !title {|t| t.have_required_values?} and
- !description {|d| d.have_required_values?}
- vars << "title or description"
- end
- vars
- end
-
- def variables
- super + ["pubDate"]
- end
-
- class Guid < RSS09::Items::Item::Guid
- def to_feed(rss, item)
- guid = Rss::Channel::Item::Guid.new
- set = setup_values(guid)
- if set
- item.guid = guid
- set_parent(guid, item)
- setup_other_elements(rss, guid)
- end
- end
-
- private
- def required_variable_names
- %w(content)
- end
- end
-
- class Enclosure < RSS09::Items::Item::Enclosure
- def to_feed(rss, item)
- enclosure = Rss::Channel::Item::Enclosure.new
- set = setup_values(enclosure)
- if set
- item.enclosure = enclosure
- set_parent(enclosure, item)
- setup_other_elements(rss, enclosure)
- end
- end
-
- private
- def required_variable_names
- %w(url length type)
- end
- end
-
- class Source < RSS09::Items::Item::Source
- def to_feed(rss, item)
- source = Rss::Channel::Item::Source.new
- set = setup_values(source)
- if set
- item.source = source
- set_parent(source, item)
- setup_other_elements(rss, source)
- end
- end
-
- private
- def required_variable_names
- %w(url content)
- end
-
- class Links < RSS09::Items::Item::Source::Links
- def to_feed(rss, source)
- return if @links.empty?
- @links.first.to_feed(rss, source)
- end
-
- class Link < RSS09::Items::Item::Source::Links::Link
- def to_feed(rss, source)
- source.url = href
- end
- end
- end
- end
-
- class Categories < RSS09::Items::Item::Categories
- def to_feed(rss, item)
- @categories.each do |category|
- category.to_feed(rss, item)
- end
- end
-
- class Category < RSS09::Items::Item::Categories::Category
- def to_feed(rss, item)
- category = Rss::Channel::Item::Category.new
- set = setup_values(category)
- if set
- item.categories << category
- set_parent(category, item)
- setup_other_elements(rss)
- end
- end
-
- private
- def required_variable_names
- %w(content)
- end
- end
- end
-
- class Authors < RSS09::Items::Item::Authors
- def to_feed(rss, item)
- return if @authors.empty?
- @authors.first.to_feed(rss, item)
- end
-
- class Author < RSS09::Items::Item::Authors::Author
- def to_feed(rss, item)
- item.author = name
- end
- end
- end
- end
- end
-
- class Textinput < RSS09::Textinput
- end
- end
-
- add_maker("2.0", "2.0", RSS20)
- add_maker("rss2.0", "2.0", RSS20)
- end
-end
diff --git a/ruby_1_9_3/lib/rss/maker/atom.rb b/ruby_1_9_3/lib/rss/maker/atom.rb
deleted file mode 100644
index fd3198cd9e..0000000000
--- a/ruby_1_9_3/lib/rss/maker/atom.rb
+++ /dev/null
@@ -1,172 +0,0 @@
-require "rss/atom"
-
-require "rss/maker/base"
-
-module RSS
- module Maker
- module AtomPersons
- module_function
- def def_atom_persons(klass, name, maker_name, plural=nil)
- plural ||= "#{name}s"
- klass_name = Utils.to_class_name(name)
- plural_klass_name = Utils.to_class_name(plural)
-
- klass.class_eval(<<-EOC, __FILE__, __LINE__ + 1)
- class #{plural_klass_name} < #{plural_klass_name}Base
- class #{klass_name} < #{klass_name}Base
- def to_feed(feed, current)
- #{name} = feed.class::#{klass_name}.new
- set = setup_values(#{name})
- unless set
- raise NotSetError.new(#{maker_name.dump},
- not_set_required_variables)
- end
- current.#{plural} << #{name}
- set_parent(#{name}, current)
- setup_other_elements(#{name})
- end
-
- private
- def required_variable_names
- %w(name)
- end
- end
- end
-EOC
- end
- end
-
- module AtomTextConstruct
- class << self
- def def_atom_text_construct(klass, name, maker_name, klass_name=nil,
- atom_klass_name=nil)
- klass_name ||= Utils.to_class_name(name)
- atom_klass_name ||= Utils.to_class_name(name)
-
- klass.class_eval(<<-EOC, __FILE__, __LINE__ + 1)
- class #{klass_name} < #{klass_name}Base
- include #{self.name}
- def to_feed(feed, current)
- #{name} = current.class::#{atom_klass_name}.new
- if setup_values(#{name})
- current.#{name} = #{name}
- set_parent(#{name}, current)
- setup_other_elements(feed)
- elsif variable_is_set?
- raise NotSetError.new(#{maker_name.dump},
- not_set_required_variables)
- end
- end
- end
- EOC
- end
- end
-
- private
- def required_variable_names
- if type == "xhtml"
- %w(xml_content)
- else
- %w(content)
- end
- end
-
- def variables
- if type == "xhtml"
- super + %w(xhtml)
- else
- super
- end
- end
- end
-
- module AtomCategory
- def to_feed(feed, current)
- category = feed.class::Category.new
- set = setup_values(category)
- if set
- current.categories << category
- set_parent(category, current)
- setup_other_elements(feed)
- else
- raise NotSetError.new(self.class.not_set_name,
- not_set_required_variables)
- end
- end
-
- private
- def required_variable_names
- %w(term)
- end
-
- def variables
- super + ["term", "scheme"]
- end
- end
-
- module AtomLink
- def to_feed(feed, current)
- link = feed.class::Link.new
- set = setup_values(link)
- if set
- current.links << link
- set_parent(link, current)
- setup_other_elements(feed)
- else
- raise NotSetError.new(self.class.not_set_name,
- not_set_required_variables)
- end
- end
-
- private
- def required_variable_names
- %w(href)
- end
- end
-
- module AtomGenerator
- def to_feed(feed, current)
- generator = current.class::Generator.new
- if setup_values(generator)
- current.generator = generator
- set_parent(generator, current)
- setup_other_elements(feed)
- elsif variable_is_set?
- raise NotSetError.new(self.class.not_set_name,
- not_set_required_variables)
- end
- end
-
- private
- def required_variable_names
- %w(content)
- end
- end
-
- module AtomLogo
- def to_feed(feed, current)
- logo = current.class::Logo.new
- class << logo
- alias_method(:uri=, :content=)
- end
- set = setup_values(logo)
- class << logo
- remove_method(:uri=)
- end
- if set
- current.logo = logo
- set_parent(logo, current)
- setup_other_elements(feed)
- elsif variable_is_set?
- raise NotSetError.new(self.class.not_set_name,
- not_set_required_variables)
- end
- end
-
- private
- def required_variable_names
- %w(uri)
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rss/maker/base.rb b/ruby_1_9_3/lib/rss/maker/base.rb
deleted file mode 100644
index fa2b02d101..0000000000
--- a/ruby_1_9_3/lib/rss/maker/base.rb
+++ /dev/null
@@ -1,944 +0,0 @@
-require 'forwardable'
-
-require 'rss/rss'
-
-module RSS
- module Maker
- class Base
- extend Utils::InheritedReader
-
- OTHER_ELEMENTS = []
- NEED_INITIALIZE_VARIABLES = []
-
- class << self
- def other_elements
- inherited_array_reader("OTHER_ELEMENTS")
- end
- def need_initialize_variables
- inherited_array_reader("NEED_INITIALIZE_VARIABLES")
- end
-
- def inherited_base
- ::RSS::Maker::Base
- end
-
- def inherited(subclass)
- subclass.const_set("OTHER_ELEMENTS", [])
- subclass.const_set("NEED_INITIALIZE_VARIABLES", [])
- end
-
- def add_other_element(variable_name)
- self::OTHER_ELEMENTS << variable_name
- end
-
- def add_need_initialize_variable(variable_name, init_value=nil,
- &init_block)
- init_value ||= init_block
- self::NEED_INITIALIZE_VARIABLES << [variable_name, init_value]
- end
-
- def def_array_element(name, plural=nil, klass_name=nil)
- include Enumerable
- extend Forwardable
-
- plural ||= "#{name}s"
- klass_name ||= Utils.to_class_name(name)
- def_delegators("@#{plural}", :<<, :[], :[]=, :first, :last)
- def_delegators("@#{plural}", :push, :pop, :shift, :unshift)
- def_delegators("@#{plural}", :each, :size, :empty?, :clear)
-
- add_need_initialize_variable(plural) {[]}
-
- module_eval(<<-EOC, __FILE__, __LINE__ + 1)
- def new_#{name}
- #{name} = self.class::#{klass_name}.new(@maker)
- @#{plural} << #{name}
- if block_given?
- yield #{name}
- else
- #{name}
- end
- end
- alias new_child new_#{name}
-
- def to_feed(*args)
- @#{plural}.each do |#{name}|
- #{name}.to_feed(*args)
- end
- end
-
- def replace(elements)
- @#{plural}.replace(elements.to_a)
- end
- EOC
- end
-
- def def_classed_element_without_accessor(name, class_name=nil)
- class_name ||= Utils.to_class_name(name)
- add_other_element(name)
- add_need_initialize_variable(name) do |object|
- object.send("make_#{name}")
- end
- module_eval(<<-EOC, __FILE__, __LINE__ + 1)
- private
- def setup_#{name}(feed, current)
- @#{name}.to_feed(feed, current)
- end
-
- def make_#{name}
- self.class::#{class_name}.new(@maker)
- end
- EOC
- end
-
- def def_classed_element(name, class_name=nil, attribute_name=nil)
- def_classed_element_without_accessor(name, class_name)
- if attribute_name
- module_eval(<<-EOC, __FILE__, __LINE__ + 1)
- def #{name}
- if block_given?
- yield(@#{name})
- else
- @#{name}.#{attribute_name}
- end
- end
-
- def #{name}=(new_value)
- @#{name}.#{attribute_name} = new_value
- end
- EOC
- else
- attr_reader name
- end
- end
-
- def def_classed_elements(name, attribute, plural_class_name=nil,
- plural_name=nil, new_name=nil)
- plural_name ||= "#{name}s"
- new_name ||= name
- def_classed_element(plural_name, plural_class_name)
- local_variable_name = "_#{name}"
- new_value_variable_name = "new_value"
- additional_setup_code = nil
- if block_given?
- additional_setup_code = yield(local_variable_name,
- new_value_variable_name)
- end
- module_eval(<<-EOC, __FILE__, __LINE__ + 1)
- def #{name}
- #{local_variable_name} = #{plural_name}.first
- #{local_variable_name} ? #{local_variable_name}.#{attribute} : nil
- end
-
- def #{name}=(#{new_value_variable_name})
- #{local_variable_name} =
- #{plural_name}.first || #{plural_name}.new_#{new_name}
- #{additional_setup_code}
- #{local_variable_name}.#{attribute} = #{new_value_variable_name}
- end
- EOC
- end
-
- def def_other_element(name)
- attr_accessor name
- def_other_element_without_accessor(name)
- end
-
- def def_other_element_without_accessor(name)
- add_need_initialize_variable(name)
- add_other_element(name)
- module_eval(<<-EOC, __FILE__, __LINE__ + 1)
- def setup_#{name}(feed, current)
- if !@#{name}.nil? and current.respond_to?(:#{name}=)
- current.#{name} = @#{name}
- end
- end
- EOC
- end
-
- def def_csv_element(name, type=nil)
- def_other_element_without_accessor(name)
- attr_reader(name)
- converter = ""
- if type == :integer
- converter = "{|v| Integer(v)}"
- end
- module_eval(<<-EOC, __FILE__, __LINE__ + 1)
- def #{name}=(value)
- @#{name} = Utils::CSV.parse(value)#{converter}
- end
- EOC
- end
- end
-
- attr_reader :maker
- def initialize(maker)
- @maker = maker
- @default_values_are_set = false
- initialize_variables
- end
-
- def have_required_values?
- not_set_required_variables.empty?
- end
-
- def variable_is_set?
- variables.any? {|var| not __send__(var).nil?}
- end
-
- private
- def initialize_variables
- self.class.need_initialize_variables.each do |variable_name, init_value|
- if init_value.nil?
- value = nil
- else
- if init_value.respond_to?(:call)
- value = init_value.call(self)
- elsif init_value.is_a?(String)
- # just for backward compatibility
- value = instance_eval(init_value, __FILE__, __LINE__)
- else
- value = init_value
- end
- end
- instance_variable_set("@#{variable_name}", value)
- end
- end
-
- def setup_other_elements(feed, current=nil)
- current ||= current_element(feed)
- self.class.other_elements.each do |element|
- __send__("setup_#{element}", feed, current)
- end
- end
-
- def current_element(feed)
- feed
- end
-
- def set_default_values(&block)
- return yield if @default_values_are_set
-
- begin
- @default_values_are_set = true
- _set_default_values(&block)
- ensure
- @default_values_are_set = false
- end
- end
-
- def _set_default_values(&block)
- yield
- end
-
- def setup_values(target)
- set = false
- if have_required_values?
- variables.each do |var|
- setter = "#{var}="
- if target.respond_to?(setter)
- value = __send__(var)
- unless value.nil?
- target.__send__(setter, value)
- set = true
- end
- end
- end
- end
- set
- end
-
- def set_parent(target, parent)
- target.parent = parent if target.class.need_parent?
- end
-
- def variables
- self.class.need_initialize_variables.find_all do |name, init|
- # init == "nil" is just for backward compatibility
- init.nil? or init == "nil"
- end.collect do |name, init|
- name
- end
- end
-
- def not_set_required_variables
- required_variable_names.find_all do |var|
- __send__(var).nil?
- end
- end
-
- def required_variables_are_set?
- required_variable_names.each do |var|
- return false if __send__(var).nil?
- end
- true
- end
- end
-
- module AtomPersonConstructBase
- def self.append_features(klass)
- super
-
- klass.class_eval(<<-EOC, __FILE__, __LINE__ + 1)
- %w(name uri email).each do |element|
- attr_accessor element
- add_need_initialize_variable(element)
- end
- EOC
- end
- end
-
- module AtomTextConstructBase
- module EnsureXMLContent
- class << self
- def included(base)
- super
- base.class_eval do
- %w(type content xml_content).each do |element|
- attr_reader element
- attr_writer element if element != "xml_content"
- add_need_initialize_variable(element)
- end
-
- alias_method(:xhtml, :xml_content)
- end
- end
- end
-
- def ensure_xml_content(content)
- xhtml_uri = ::RSS::Atom::XHTML_URI
- unless content.is_a?(RSS::XML::Element) and
- ["div", xhtml_uri] == [content.name, content.uri]
- children = content
- children = [children] unless content.is_a?(Array)
- children = set_xhtml_uri_as_default_uri(children)
- content = RSS::XML::Element.new("div", nil, xhtml_uri,
- {"xmlns" => xhtml_uri},
- children)
- end
- content
- end
-
- def xml_content=(content)
- @xml_content = ensure_xml_content(content)
- end
-
- def xhtml=(content)
- self.xml_content = content
- end
-
- private
- def set_xhtml_uri_as_default_uri(children)
- children.collect do |child|
- if child.is_a?(RSS::XML::Element) and
- child.prefix.nil? and child.uri.nil?
- RSS::XML::Element.new(child.name, nil, ::RSS::Atom::XHTML_URI,
- child.attributes.dup,
- set_xhtml_uri_as_default_uri(child.children))
- else
- child
- end
- end
- end
- end
-
- def self.append_features(klass)
- super
-
- klass.class_eval do
- include EnsureXMLContent
- end
- end
- end
-
- module SetupDefaultDate
- private
- def _set_default_values(&block)
- keep = {
- :date => date,
- :dc_dates => dc_dates.to_a.dup,
- }
- _date = _parse_date_if_needed(date)
- if _date and !dc_dates.any? {|dc_date| dc_date.value == _date}
- dc_date = self.class::DublinCoreDates::DublinCoreDate.new(self)
- dc_date.value = _date.dup
- dc_dates.unshift(dc_date)
- end
- self.date ||= self.dc_date
- super(&block)
- ensure
- date = keep[:date]
- dc_dates.replace(keep[:dc_dates])
- end
-
- def _parse_date_if_needed(date_value)
- date_value = Time.parse(date_value) if date_value.is_a?(String)
- date_value
- end
- end
-
- module SetupDefaultLanguage
- private
- def _set_default_values(&block)
- keep = {
- :dc_languages => dc_languages.to_a.dup,
- }
- _language = language
- if _language and
- !dc_languages.any? {|dc_language| dc_language.value == _language}
- dc_language = self.class::DublinCoreLanguages::DublinCoreLanguage.new(self)
- dc_language.value = _language.dup
- dc_languages.unshift(dc_language)
- end
- super(&block)
- ensure
- dc_languages.replace(keep[:dc_languages])
- end
- end
-
- class RSSBase < Base
- class << self
- def make(*args, &block)
- new(*args).make(&block)
- end
- end
-
- %w(xml_stylesheets channel image items textinput).each do |element|
- attr_reader element
- add_need_initialize_variable(element) do |object|
- object.send("make_#{element}")
- end
- module_eval(<<-EOC, __FILE__, __LINE__ + 1)
- private
- def setup_#{element}(feed)
- @#{element}.to_feed(feed)
- end
-
- def make_#{element}
- self.class::#{Utils.to_class_name(element)}.new(self)
- end
- EOC
- end
-
- attr_reader :feed_version
- alias_method(:rss_version, :feed_version)
- attr_accessor :version, :encoding, :standalone
-
- def initialize(feed_version)
- super(self)
- @feed_type = nil
- @feed_subtype = nil
- @feed_version = feed_version
- @version = "1.0"
- @encoding = "UTF-8"
- @standalone = nil
- end
-
- def make
- yield(self)
- to_feed
- end
-
- def to_feed
- feed = make_feed
- setup_xml_stylesheets(feed)
- setup_elements(feed)
- setup_other_elements(feed)
- feed.validate
- feed
- end
-
- private
- remove_method :make_xml_stylesheets
- def make_xml_stylesheets
- XMLStyleSheets.new(self)
- end
- end
-
- class XMLStyleSheets < Base
- def_array_element("xml_stylesheet", nil, "XMLStyleSheet")
-
- class XMLStyleSheet < Base
-
- ::RSS::XMLStyleSheet::ATTRIBUTES.each do |attribute|
- attr_accessor attribute
- add_need_initialize_variable(attribute)
- end
-
- def to_feed(feed)
- xss = ::RSS::XMLStyleSheet.new
- guess_type_if_need(xss)
- set = setup_values(xss)
- if set
- feed.xml_stylesheets << xss
- end
- end
-
- private
- def guess_type_if_need(xss)
- if @type.nil?
- xss.href = @href
- @type = xss.type
- end
- end
-
- def required_variable_names
- %w(href type)
- end
- end
- end
-
- class ChannelBase < Base
- include SetupDefaultDate
-
- %w(cloud categories skipDays skipHours).each do |name|
- def_classed_element(name)
- end
-
- %w(generator copyright description title).each do |name|
- def_classed_element(name, nil, "content")
- end
-
- [
- ["link", "href", Proc.new {|target,| "#{target}.href = 'self'"}],
- ["author", "name"],
- ["contributor", "name"],
- ].each do |name, attribute, additional_setup_maker|
- def_classed_elements(name, attribute, &additional_setup_maker)
- end
-
- %w(id about language
- managingEditor webMaster rating docs ttl).each do |element|
- attr_accessor element
- add_need_initialize_variable(element)
- end
-
- %w(date lastBuildDate).each do |date_element|
- attr_reader date_element
- add_need_initialize_variable(date_element)
- end
-
- def date=(_date)
- @date = _parse_date_if_needed(_date)
- end
-
- def lastBuildDate=(_date)
- @lastBuildDate = _parse_date_if_needed(_date)
- end
-
- def pubDate
- date
- end
-
- def pubDate=(date)
- self.date = date
- end
-
- def updated
- date
- end
-
- def updated=(date)
- self.date = date
- end
-
- alias_method(:rights, :copyright)
- alias_method(:rights=, :copyright=)
-
- alias_method(:subtitle, :description)
- alias_method(:subtitle=, :description=)
-
- def icon
- image_favicon.about
- end
-
- def icon=(url)
- image_favicon.about = url
- end
-
- def logo
- maker.image.url
- end
-
- def logo=(url)
- maker.image.url = url
- end
-
- class SkipDaysBase < Base
- def_array_element("day")
-
- class DayBase < Base
- %w(content).each do |element|
- attr_accessor element
- add_need_initialize_variable(element)
- end
- end
- end
-
- class SkipHoursBase < Base
- def_array_element("hour")
-
- class HourBase < Base
- %w(content).each do |element|
- attr_accessor element
- add_need_initialize_variable(element)
- end
- end
- end
-
- class CloudBase < Base
- %w(domain port path registerProcedure protocol).each do |element|
- attr_accessor element
- add_need_initialize_variable(element)
- end
- end
-
- class CategoriesBase < Base
- def_array_element("category", "categories")
-
- class CategoryBase < Base
- %w(domain content label).each do |element|
- attr_accessor element
- add_need_initialize_variable(element)
- end
-
- alias_method(:term, :domain)
- alias_method(:term=, :domain=)
- alias_method(:scheme, :content)
- alias_method(:scheme=, :content=)
- end
- end
-
- class LinksBase < Base
- def_array_element("link")
-
- class LinkBase < Base
- %w(href rel type hreflang title length).each do |element|
- attr_accessor element
- add_need_initialize_variable(element)
- end
- end
- end
-
- class AuthorsBase < Base
- def_array_element("author")
-
- class AuthorBase < Base
- include AtomPersonConstructBase
- end
- end
-
- class ContributorsBase < Base
- def_array_element("contributor")
-
- class ContributorBase < Base
- include AtomPersonConstructBase
- end
- end
-
- class GeneratorBase < Base
- %w(uri version content).each do |element|
- attr_accessor element
- add_need_initialize_variable(element)
- end
- end
-
- class CopyrightBase < Base
- include AtomTextConstructBase
- end
-
- class DescriptionBase < Base
- include AtomTextConstructBase
- end
-
- class TitleBase < Base
- include AtomTextConstructBase
- end
- end
-
- class ImageBase < Base
- %w(title url width height description).each do |element|
- attr_accessor element
- add_need_initialize_variable(element)
- end
-
- def link
- @maker.channel.link
- end
- end
-
- class ItemsBase < Base
- def_array_element("item")
-
- attr_accessor :do_sort, :max_size
-
- def initialize(maker)
- super
- @do_sort = false
- @max_size = -1
- end
-
- def normalize
- if @max_size >= 0
- sort_if_need[0...@max_size]
- else
- sort_if_need[0..@max_size]
- end
- end
-
- private
- def sort_if_need
- if @do_sort.respond_to?(:call)
- @items.sort do |x, y|
- @do_sort.call(x, y)
- end
- elsif @do_sort
- @items.sort do |x, y|
- y <=> x
- end
- else
- @items
- end
- end
-
- class ItemBase < Base
- include SetupDefaultDate
-
- %w(guid enclosure source categories content).each do |name|
- def_classed_element(name)
- end
-
- %w(rights description title).each do |name|
- def_classed_element(name, nil, "content")
- end
-
- [
- ["author", "name"],
- ["link", "href", Proc.new {|target,| "#{target}.href = 'alternate'"}],
- ["contributor", "name"],
- ].each do |name, attribute|
- def_classed_elements(name, attribute)
- end
-
- %w(comments id published).each do |element|
- attr_accessor element
- add_need_initialize_variable(element)
- end
-
- %w(date).each do |date_element|
- attr_reader date_element
- add_need_initialize_variable(date_element)
- end
-
- def date=(_date)
- @date = _parse_date_if_needed(_date)
- end
-
- def pubDate
- date
- end
-
- def pubDate=(date)
- self.date = date
- end
-
- def updated
- date
- end
-
- def updated=(date)
- self.date = date
- end
-
- alias_method(:summary, :description)
- alias_method(:summary=, :description=)
-
- def <=>(other)
- _date = date || dc_date
- _other_date = other.date || other.dc_date
- if _date and _other_date
- _date <=> _other_date
- elsif _date
- 1
- elsif _other_date
- -1
- else
- 0
- end
- end
-
- class GuidBase < Base
- %w(isPermaLink content).each do |element|
- attr_accessor element
- add_need_initialize_variable(element)
- end
-
- def permanent_link?
- isPermaLink
- end
-
- def permanent_link=(bool)
- self.isPermaLink = bool
- end
- end
-
- class EnclosureBase < Base
- %w(url length type).each do |element|
- attr_accessor element
- add_need_initialize_variable(element)
- end
- end
-
- class SourceBase < Base
- include SetupDefaultDate
-
- %w(authors categories contributors generator icon
- logo rights subtitle title).each do |name|
- def_classed_element(name)
- end
-
- [
- ["link", "href"],
- ].each do |name, attribute|
- def_classed_elements(name, attribute)
- end
-
- %w(id content).each do |element|
- attr_accessor element
- add_need_initialize_variable(element)
- end
-
- alias_method(:url, :link)
- alias_method(:url=, :link=)
-
- %w(date).each do |date_element|
- attr_reader date_element
- add_need_initialize_variable(date_element)
- end
-
- def date=(_date)
- @date = _parse_date_if_needed(_date)
- end
-
- def updated
- date
- end
-
- def updated=(date)
- self.date = date
- end
-
- private
- AuthorsBase = ChannelBase::AuthorsBase
- CategoriesBase = ChannelBase::CategoriesBase
- ContributorsBase = ChannelBase::ContributorsBase
- GeneratorBase = ChannelBase::GeneratorBase
-
- class IconBase < Base
- %w(url).each do |element|
- attr_accessor element
- add_need_initialize_variable(element)
- end
- end
-
- LinksBase = ChannelBase::LinksBase
-
- class LogoBase < Base
- %w(uri).each do |element|
- attr_accessor element
- add_need_initialize_variable(element)
- end
- end
-
- class RightsBase < Base
- include AtomTextConstructBase
- end
-
- class SubtitleBase < Base
- include AtomTextConstructBase
- end
-
- class TitleBase < Base
- include AtomTextConstructBase
- end
- end
-
- CategoriesBase = ChannelBase::CategoriesBase
- AuthorsBase = ChannelBase::AuthorsBase
- LinksBase = ChannelBase::LinksBase
- ContributorsBase = ChannelBase::ContributorsBase
-
- class RightsBase < Base
- include AtomTextConstructBase
- end
-
- class DescriptionBase < Base
- include AtomTextConstructBase
- end
-
- class ContentBase < Base
- include AtomTextConstructBase::EnsureXMLContent
-
- %w(src).each do |element|
- attr_accessor(element)
- add_need_initialize_variable(element)
- end
-
- def xml_content=(content)
- content = ensure_xml_content(content) if inline_xhtml?
- @xml_content = content
- end
-
- alias_method(:xml, :xml_content)
- alias_method(:xml=, :xml_content=)
-
- def inline_text?
- [nil, "text", "html"].include?(@type)
- end
-
- def inline_html?
- @type == "html"
- end
-
- def inline_xhtml?
- @type == "xhtml"
- end
-
- def inline_other?
- !out_of_line? and ![nil, "text", "html", "xhtml"].include?(@type)
- end
-
- def inline_other_text?
- return false if @type.nil? or out_of_line?
- /\Atext\//i.match(@type) ? true : false
- end
-
- def inline_other_xml?
- return false if @type.nil? or out_of_line?
- /[\+\/]xml\z/i.match(@type) ? true : false
- end
-
- def inline_other_base64?
- return false if @type.nil? or out_of_line?
- @type.include?("/") and !inline_other_text? and !inline_other_xml?
- end
-
- def out_of_line?
- not @src.nil? and @content.nil?
- end
- end
-
- class TitleBase < Base
- include AtomTextConstructBase
- end
- end
- end
-
- class TextinputBase < Base
- %w(title description name link).each do |element|
- attr_accessor element
- add_need_initialize_variable(element)
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rss/maker/content.rb b/ruby_1_9_3/lib/rss/maker/content.rb
deleted file mode 100644
index 46c4911f73..0000000000
--- a/ruby_1_9_3/lib/rss/maker/content.rb
+++ /dev/null
@@ -1,21 +0,0 @@
-require 'rss/content'
-require 'rss/maker/1.0'
-require 'rss/maker/2.0'
-
-module RSS
- module Maker
- module ContentModel
- def self.append_features(klass)
- super
-
- ::RSS::ContentModel::ELEMENTS.each do |name|
- klass.def_other_element(name)
- end
- end
- end
-
- class ItemsBase
- class ItemBase; include ContentModel; end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rss/maker/dublincore.rb b/ruby_1_9_3/lib/rss/maker/dublincore.rb
deleted file mode 100644
index 717b074fae..0000000000
--- a/ruby_1_9_3/lib/rss/maker/dublincore.rb
+++ /dev/null
@@ -1,121 +0,0 @@
-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}"
- plural_klass_name = "DublinCore#{Utils.to_class_name(plural_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
diff --git a/ruby_1_9_3/lib/rss/maker/entry.rb b/ruby_1_9_3/lib/rss/maker/entry.rb
deleted file mode 100644
index b35936b208..0000000000
--- a/ruby_1_9_3/lib/rss/maker/entry.rb
+++ /dev/null
@@ -1,163 +0,0 @@
-require "rss/maker/atom"
-require "rss/maker/feed"
-
-module RSS
- module Maker
- module Atom
- class Entry < RSSBase
- def initialize(feed_version="1.0")
- super
- @feed_type = "atom"
- @feed_subtype = "entry"
- end
-
- private
- def make_feed
- ::RSS::Atom::Entry.new(@version, @encoding, @standalone)
- end
-
- def setup_elements(entry)
- setup_items(entry)
- end
-
- class Channel < ChannelBase
- class SkipDays < SkipDaysBase
- class Day < DayBase
- end
- end
-
- class SkipHours < SkipHoursBase
- class Hour < HourBase
- end
- end
-
- class Cloud < CloudBase
- end
-
- Categories = Feed::Channel::Categories
- Links = Feed::Channel::Links
- Authors = Feed::Channel::Authors
- Contributors = Feed::Channel::Contributors
-
- class Generator < GeneratorBase
- include AtomGenerator
-
- def self.not_set_name
- "maker.channel.generator"
- end
- end
-
- Copyright = Feed::Channel::Copyright
-
- class Description < DescriptionBase
- end
-
- Title = Feed::Channel::Title
- end
-
- class Image < ImageBase
- end
-
- class Items < ItemsBase
- def to_feed(entry)
- (normalize.first || Item.new(@maker)).to_feed(entry)
- end
-
- class Item < ItemBase
- def to_feed(entry)
- set_default_values do
- setup_values(entry)
- entry.dc_dates.clear
- setup_other_elements(entry)
- unless have_required_values?
- raise NotSetError.new("maker.item", not_set_required_variables)
- end
- end
- end
-
- private
- def required_variable_names
- %w(id updated)
- end
-
- def variables
- super + ["updated"]
- end
-
- def variable_is_set?
- super or !authors.empty?
- end
-
- def not_set_required_variables
- set_default_values do
- vars = super
- if authors.all? {|author| !author.have_required_values?}
- vars << "author"
- end
- vars << "title" unless title {|t| t.have_required_values?}
- vars
- end
- end
-
- def _set_default_values(&block)
- keep = {
- :authors => authors.to_a.dup,
- :contributors => contributors.to_a.dup,
- :categories => categories.to_a.dup,
- :id => id,
- :links => links.to_a.dup,
- :rights => @rights,
- :title => @title,
- :updated => updated,
- }
- authors.replace(@maker.channel.authors) if keep[:authors].empty?
- if keep[:contributors].empty?
- contributors.replace(@maker.channel.contributors)
- end
- if keep[:categories].empty?
- categories.replace(@maker.channel.categories)
- end
- self.id ||= link || @maker.channel.id
- links.replace(@maker.channel.links) if keep[:links].empty?
- unless keep[:rights].variable_is_set?
- @maker.channel.rights {|r| @rights = r}
- end
- unless keep[:title].variable_is_set?
- @maker.channel.title {|t| @title = t}
- end
- self.updated ||= @maker.channel.updated
- super(&block)
- ensure
- authors.replace(keep[:authors])
- contributors.replace(keep[:contributors])
- categories.replace(keep[:categories])
- links.replace(keep[:links])
- self.id = keep[:id]
- @rights = keep[:rights]
- @title = keep[:title]
- self.updated = keep[:updated]
- end
-
- Guid = Feed::Items::Item::Guid
- Enclosure = Feed::Items::Item::Enclosure
- Source = Feed::Items::Item::Source
- Categories = Feed::Items::Item::Categories
- Authors = Feed::Items::Item::Authors
- Contributors = Feed::Items::Item::Contributors
- Links = Feed::Items::Item::Links
- Rights = Feed::Items::Item::Rights
- Description = Feed::Items::Item::Description
- Title = Feed::Items::Item::Title
- Content = Feed::Items::Item::Content
- end
- end
-
- class Textinput < TextinputBase
- end
- end
- end
-
- add_maker("atom:entry", "1.0", Atom::Entry)
- add_maker("atom1.0:entry", "1.0", Atom::Entry)
- end
-end
diff --git a/ruby_1_9_3/lib/rss/maker/feed.rb b/ruby_1_9_3/lib/rss/maker/feed.rb
deleted file mode 100644
index 0129218b0c..0000000000
--- a/ruby_1_9_3/lib/rss/maker/feed.rb
+++ /dev/null
@@ -1,426 +0,0 @@
-require "rss/maker/atom"
-
-module RSS
- module Maker
- module Atom
- class Feed < RSSBase
- def initialize(feed_version="1.0")
- super
- @feed_type = "atom"
- @feed_subtype = "feed"
- end
-
- private
- def make_feed
- ::RSS::Atom::Feed.new(@version, @encoding, @standalone)
- end
-
- def setup_elements(feed)
- setup_channel(feed)
- setup_image(feed)
- setup_items(feed)
- end
-
- class Channel < ChannelBase
- include SetupDefaultLanguage
-
- def to_feed(feed)
- set_default_values do
- setup_values(feed)
- feed.dc_dates.clear
- setup_other_elements(feed)
- if image_favicon.about
- icon = feed.class::Icon.new
- icon.content = image_favicon.about
- feed.icon = icon
- end
- unless have_required_values?
- raise NotSetError.new("maker.channel",
- not_set_required_variables)
- end
- end
- end
-
- def have_required_values?
- super and
- (!authors.empty? or
- @maker.items.any? {|item| !item.authors.empty?})
- end
-
- private
- def required_variable_names
- %w(id updated)
- end
-
- def variables
- super + %w(id updated)
- end
-
- def variable_is_set?
- super or !authors.empty?
- end
-
- def not_set_required_variables
- vars = super
- if authors.empty? and
- @maker.items.all? {|item| item.author.to_s.empty?}
- vars << "author"
- end
- vars << "title" unless title {|t| t.have_required_values?}
- vars
- end
-
- def _set_default_values(&block)
- keep = {
- :id => id,
- }
- self.id ||= about
- super(&block)
- ensure
- self.id = keep[:id]
- end
-
- class SkipDays < SkipDaysBase
- def to_feed(*args)
- end
-
- class Day < DayBase
- end
- end
-
- class SkipHours < SkipHoursBase
- def to_feed(*args)
- end
-
- class Hour < HourBase
- end
- end
-
- class Cloud < CloudBase
- def to_feed(*args)
- end
- end
-
- class Categories < CategoriesBase
- class Category < CategoryBase
- include AtomCategory
-
- def self.not_set_name
- "maker.channel.category"
- end
- end
- end
-
- class Links < LinksBase
- class Link < LinkBase
- include AtomLink
-
- def self.not_set_name
- "maker.channel.link"
- end
- end
- end
-
- AtomPersons.def_atom_persons(self, "author", "maker.channel.author")
- AtomPersons.def_atom_persons(self, "contributor",
- "maker.channel.contributor")
-
- class Generator < GeneratorBase
- include AtomGenerator
-
- def self.not_set_name
- "maker.channel.generator"
- end
- end
-
- AtomTextConstruct.def_atom_text_construct(self, "rights",
- "maker.channel.copyright",
- "Copyright")
- AtomTextConstruct.def_atom_text_construct(self, "subtitle",
- "maker.channel.description",
- "Description")
- AtomTextConstruct.def_atom_text_construct(self, "title",
- "maker.channel.title")
- end
-
- class Image < ImageBase
- def to_feed(feed)
- logo = feed.class::Logo.new
- class << logo
- alias_method(:url=, :content=)
- end
- set = setup_values(logo)
- class << logo
- remove_method(:url=)
- end
- if set
- feed.logo = logo
- set_parent(logo, feed)
- setup_other_elements(feed, logo)
- elsif variable_is_set?
- raise NotSetError.new("maker.image", not_set_required_variables)
- end
- end
-
- private
- def required_variable_names
- %w(url)
- end
- end
-
- class Items < ItemsBase
- def to_feed(feed)
- normalize.each do |item|
- item.to_feed(feed)
- end
- setup_other_elements(feed, feed.entries)
- end
-
- class Item < ItemBase
- def to_feed(feed)
- set_default_values do
- entry = feed.class::Entry.new
- set = setup_values(entry)
- entry.dc_dates.clear
- setup_other_elements(feed, entry)
- if set
- feed.entries << entry
- set_parent(entry, feed)
- elsif variable_is_set?
- raise NotSetError.new("maker.item", not_set_required_variables)
- end
- end
- end
-
- def have_required_values?
- set_default_values do
- super and title {|t| t.have_required_values?}
- end
- end
-
- private
- def required_variable_names
- %w(id updated)
- end
-
- def variables
- super + ["updated"]
- end
-
- def not_set_required_variables
- vars = super
- vars << "title" unless title {|t| t.have_required_values?}
- vars
- end
-
- def _set_default_values(&block)
- keep = {
- :id => id,
- }
- self.id ||= link
- super(&block)
- ensure
- self.id = keep[:id]
- end
-
- class Guid < GuidBase
- def to_feed(feed, current)
- end
- end
-
- class Enclosure < EnclosureBase
- def to_feed(feed, current)
- end
- end
-
- class Source < SourceBase
- def to_feed(feed, current)
- source = current.class::Source.new
- setup_values(source)
- current.source = source
- set_parent(source, current)
- setup_other_elements(feed, source)
- current.source = nil if source.to_s == "<source/>"
- end
-
- private
- def required_variable_names
- []
- end
-
- def variables
- super + ["updated"]
- end
-
- AtomPersons.def_atom_persons(self, "author",
- "maker.item.source.author")
- AtomPersons.def_atom_persons(self, "contributor",
- "maker.item.source.contributor")
-
- class Categories < CategoriesBase
- class Category < CategoryBase
- include AtomCategory
-
- def self.not_set_name
- "maker.item.source.category"
- end
- end
- end
-
- class Generator < GeneratorBase
- include AtomGenerator
-
- def self.not_set_name
- "maker.item.source.generator"
- end
- end
-
- class Icon < IconBase
- def to_feed(feed, current)
- icon = current.class::Icon.new
- class << icon
- alias_method(:url=, :content=)
- end
- set = setup_values(icon)
- class << icon
- remove_method(:url=)
- end
- if set
- current.icon = icon
- set_parent(icon, current)
- setup_other_elements(feed, icon)
- elsif variable_is_set?
- raise NotSetError.new("maker.item.source.icon",
- not_set_required_variables)
- end
- end
-
- private
- def required_variable_names
- %w(url)
- end
- end
-
- class Links < LinksBase
- class Link < LinkBase
- include AtomLink
-
- def self.not_set_name
- "maker.item.source.link"
- end
- end
- end
-
- class Logo < LogoBase
- include AtomLogo
-
- def self.not_set_name
- "maker.item.source.logo"
- end
- end
-
- maker_name_base = "maker.item.source."
- maker_name = "#{maker_name_base}rights"
- AtomTextConstruct.def_atom_text_construct(self, "rights",
- maker_name)
- maker_name = "#{maker_name_base}subtitle"
- AtomTextConstruct.def_atom_text_construct(self, "subtitle",
- maker_name)
- maker_name = "#{maker_name_base}title"
- AtomTextConstruct.def_atom_text_construct(self, "title",
- maker_name)
- end
-
- class Categories < CategoriesBase
- class Category < CategoryBase
- include AtomCategory
-
- def self.not_set_name
- "maker.item.category"
- end
- end
- end
-
- AtomPersons.def_atom_persons(self, "author", "maker.item.author")
- AtomPersons.def_atom_persons(self, "contributor",
- "maker.item.contributor")
-
- class Links < LinksBase
- class Link < LinkBase
- include AtomLink
-
- def self.not_set_name
- "maker.item.link"
- end
- end
- end
-
- AtomTextConstruct.def_atom_text_construct(self, "rights",
- "maker.item.rights")
- AtomTextConstruct.def_atom_text_construct(self, "summary",
- "maker.item.description",
- "Description")
- AtomTextConstruct.def_atom_text_construct(self, "title",
- "maker.item.title")
-
- class Content < ContentBase
- def to_feed(feed, current)
- content = current.class::Content.new
- if setup_values(content)
- content.src = nil if content.src and content.content
- current.content = content
- set_parent(content, current)
- setup_other_elements(feed, content)
- elsif variable_is_set?
- raise NotSetError.new("maker.item.content",
- not_set_required_variables)
- end
- end
-
- alias_method(:xml, :xml_content)
-
- private
- def required_variable_names
- if out_of_line?
- %w(type)
- elsif xml_type?
- %w(xml_content)
- else
- %w(content)
- end
- end
-
- def variables
- if out_of_line?
- super
- elsif xml_type?
- super + %w(xml)
- else
- super
- end
- end
-
- def xml_type?
- _type = type
- return false if _type.nil?
- _type == "xhtml" or
- /(?:\+xml|\/xml)$/i =~ _type or
- %w(text/xml-external-parsed-entity
- application/xml-external-parsed-entity
- application/xml-dtd).include?(_type.downcase)
- end
- end
- end
- end
-
- class Textinput < TextinputBase
- end
- end
- end
-
- add_maker("atom", "1.0", Atom::Feed)
- add_maker("atom:feed", "1.0", Atom::Feed)
- add_maker("atom1.0", "1.0", Atom::Feed)
- add_maker("atom1.0:feed", "1.0", Atom::Feed)
- end
-end
diff --git a/ruby_1_9_3/lib/rss/maker/image.rb b/ruby_1_9_3/lib/rss/maker/image.rb
deleted file mode 100644
index 06084b4af4..0000000000
--- a/ruby_1_9_3/lib/rss/maker/image.rb
+++ /dev/null
@@ -1,111 +0,0 @@
-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
diff --git a/ruby_1_9_3/lib/rss/maker/itunes.rb b/ruby_1_9_3/lib/rss/maker/itunes.rb
deleted file mode 100644
index 8b7420da3c..0000000000
--- a/ruby_1_9_3/lib/rss/maker/itunes.rb
+++ /dev/null
@@ -1,242 +0,0 @@
-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
diff --git a/ruby_1_9_3/lib/rss/maker/slash.rb b/ruby_1_9_3/lib/rss/maker/slash.rb
deleted file mode 100644
index 27adef3832..0000000000
--- a/ruby_1_9_3/lib/rss/maker/slash.rb
+++ /dev/null
@@ -1,33 +0,0 @@
-require 'rss/slash'
-require 'rss/maker/1.0'
-
-module RSS
- module Maker
- module SlashModel
- def self.append_features(klass)
- super
-
- ::RSS::SlashModel::ELEMENT_INFOS.each do |name, type|
- full_name = "#{RSS::SLASH_PREFIX}_#{name}"
- case type
- when :csv_integer
- klass.def_csv_element(full_name, :integer)
- else
- klass.def_other_element(full_name)
- end
- end
-
- klass.module_eval do
- alias_method(:slash_hit_parades, :slash_hit_parade)
- alias_method(:slash_hit_parades=, :slash_hit_parade=)
- end
- end
- end
-
- class ItemsBase
- class ItemBase
- include SlashModel
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rss/maker/syndication.rb b/ruby_1_9_3/lib/rss/maker/syndication.rb
deleted file mode 100644
index b81230457c..0000000000
--- a/ruby_1_9_3/lib/rss/maker/syndication.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-require 'rss/syndication'
-require 'rss/maker/1.0'
-
-module RSS
- module Maker
- module SyndicationModel
- def self.append_features(klass)
- super
-
- ::RSS::SyndicationModel::ELEMENTS.each do |name|
- klass.def_other_element(name)
- end
- end
- end
-
- class ChannelBase; include SyndicationModel; end
- end
-end
diff --git a/ruby_1_9_3/lib/rss/maker/taxonomy.rb b/ruby_1_9_3/lib/rss/maker/taxonomy.rb
deleted file mode 100644
index 13ae9aa805..0000000000
--- a/ruby_1_9_3/lib/rss/maker/taxonomy.rb
+++ /dev/null
@@ -1,118 +0,0 @@
-require 'rss/taxonomy'
-require 'rss/maker/1.0'
-require 'rss/maker/dublincore'
-
-module RSS
- module Maker
- module TaxonomyTopicsModel
- def self.append_features(klass)
- super
-
- klass.def_classed_element("#{RSS::TAXO_PREFIX}_topics",
- "TaxonomyTopics")
- end
-
- def self.install_taxo_topics(klass)
- klass.module_eval(<<-EOC, __FILE__, __LINE__ + 1)
- class TaxonomyTopics < TaxonomyTopicsBase
- def to_feed(feed, current)
- if current.respond_to?(:taxo_topics)
- topics = current.class::TaxonomyTopics.new
- bag = topics.Bag
- @resources.each do |resource|
- bag.lis << RDF::Bag::Li.new(resource)
- end
- current.taxo_topics = topics
- end
- end
- end
-EOC
- end
-
- class TaxonomyTopicsBase < Base
- attr_reader :resources
- def_array_element("resource")
- remove_method :new_resource
- end
- end
-
- module TaxonomyTopicModel
- def self.append_features(klass)
- super
-
- class_name = "TaxonomyTopics"
- klass.def_classed_elements("#{TAXO_PREFIX}_topic", "value", class_name)
- end
-
- def self.install_taxo_topic(klass)
- klass.module_eval(<<-EOC, __FILE__, __LINE__ + 1)
- class TaxonomyTopics < TaxonomyTopicsBase
- class TaxonomyTopic < TaxonomyTopicBase
- DublinCoreModel.install_dublin_core(self)
- TaxonomyTopicsModel.install_taxo_topics(self)
-
- def to_feed(feed, current)
- if current.respond_to?(:taxo_topics)
- topic = current.class::TaxonomyTopic.new(value)
- topic.taxo_link = value
- taxo_topics.to_feed(feed, topic) if taxo_topics
- current.taxo_topics << topic
- setup_other_elements(feed, topic)
- end
- end
- end
- end
-EOC
- end
-
- class TaxonomyTopicsBase < Base
- def_array_element("topic", nil, "TaxonomyTopic")
- alias_method(:new_taxo_topic, :new_topic) # For backward compatibility
-
- class TaxonomyTopicBase < Base
- include DublinCoreModel
- include TaxonomyTopicsModel
-
- attr_accessor :value
- add_need_initialize_variable("value")
- alias_method(:taxo_link, :value)
- alias_method(:taxo_link=, :value=)
-
- def have_required_values?
- @value
- end
- end
- end
- end
-
- class RSSBase
- include TaxonomyTopicModel
- end
-
- class ChannelBase
- include TaxonomyTopicsModel
- end
-
- class ItemsBase
- class ItemBase
- include TaxonomyTopicsModel
- end
- end
-
- makers.each do |maker|
- maker.module_eval(<<-EOC, __FILE__, __LINE__ + 1)
- TaxonomyTopicModel.install_taxo_topic(self)
-
- class Channel
- TaxonomyTopicsModel.install_taxo_topics(self)
- end
-
- class Items
- class Item
- TaxonomyTopicsModel.install_taxo_topics(self)
- end
- end
- EOC
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rss/maker/trackback.rb b/ruby_1_9_3/lib/rss/maker/trackback.rb
deleted file mode 100644
index 00f001cb85..0000000000
--- a/ruby_1_9_3/lib/rss/maker/trackback.rb
+++ /dev/null
@@ -1,61 +0,0 @@
-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
diff --git a/ruby_1_9_3/lib/rss/parser.rb b/ruby_1_9_3/lib/rss/parser.rb
deleted file mode 100644
index c426a187b8..0000000000
--- a/ruby_1_9_3/lib/rss/parser.rb
+++ /dev/null
@@ -1,568 +0,0 @@
-require "forwardable"
-require "open-uri"
-
-require "rss/rss"
-require "rss/xml"
-
-module RSS
-
- class NotWellFormedError < Error
- attr_reader :line, :element
-
- # Create a new NotWellFormedError for an error at +line+
- # in +element+. If a block is given the return value of
- # the block ends up in the error message.
- def initialize(line=nil, element=nil)
- message = "This is not well formed XML"
- if element or line
- message << "\nerror occurred"
- message << " in #{element}" if element
- message << " at about #{line} line" if line
- end
- message << "\n#{yield}" if block_given?
- super(message)
- end
- end
-
- class XMLParserNotFound < Error
- def initialize
- super("available XML parser was not found in " <<
- "#{AVAILABLE_PARSER_LIBRARIES.inspect}.")
- end
- end
-
- class NotValidXMLParser < Error
- def initialize(parser)
- super("#{parser} is not an available XML parser. " <<
- "Available XML parser" <<
- (AVAILABLE_PARSERS.size > 1 ? "s are " : " is ") <<
- "#{AVAILABLE_PARSERS.inspect}.")
- end
- end
-
- class NSError < InvalidRSSError
- attr_reader :tag, :prefix, :uri
- def initialize(tag, prefix, require_uri)
- @tag, @prefix, @uri = tag, prefix, require_uri
- super("prefix <#{prefix}> doesn't associate uri " <<
- "<#{require_uri}> in tag <#{tag}>")
- end
- end
-
- class Parser
-
- extend Forwardable
-
- class << self
-
- @@default_parser = nil
-
- def default_parser
- @@default_parser || AVAILABLE_PARSERS.first
- end
-
- # Set @@default_parser to new_value if it is one of the
- # available parsers. Else raise NotValidXMLParser error.
- def default_parser=(new_value)
- if AVAILABLE_PARSERS.include?(new_value)
- @@default_parser = new_value
- else
- raise NotValidXMLParser.new(new_value)
- end
- end
-
- def parse(rss, do_validate=true, ignore_unknown_element=true,
- parser_class=default_parser)
- parser = new(rss, parser_class)
- parser.do_validate = do_validate
- parser.ignore_unknown_element = ignore_unknown_element
- parser.parse
- end
- end
-
- def_delegators(:@parser, :parse, :rss,
- :ignore_unknown_element,
- :ignore_unknown_element=, :do_validate,
- :do_validate=)
-
- def initialize(rss, parser_class=self.class.default_parser)
- @parser = parser_class.new(normalize_rss(rss))
- end
-
- private
-
- # Try to get the XML associated with +rss+.
- # Return +rss+ if it already looks like XML, or treat it as a URI,
- # or a file to get the XML,
- def normalize_rss(rss)
- return rss if maybe_xml?(rss)
-
- uri = to_uri(rss)
-
- if uri.respond_to?(:read)
- uri.read
- elsif !rss.tainted? and File.readable?(rss)
- File.open(rss) {|f| f.read}
- else
- rss
- end
- end
-
- # maybe_xml? tests if source is a string that looks like XML.
- def maybe_xml?(source)
- source.is_a?(String) and /</ =~ source
- end
-
- # Attempt to convert rss to a URI, but just return it if
- # there's a ::URI::Error
- def to_uri(rss)
- return rss if rss.is_a?(::URI::Generic)
-
- begin
- ::URI.parse(rss)
- rescue ::URI::Error
- rss
- end
- end
- end
-
- class BaseParser
-
- class << self
- def raise_for_undefined_entity?
- listener.raise_for_undefined_entity?
- end
- end
-
- def initialize(rss)
- @listener = self.class.listener.new
- @rss = rss
- end
-
- def rss
- @listener.rss
- end
-
- def ignore_unknown_element
- @listener.ignore_unknown_element
- end
-
- def ignore_unknown_element=(new_value)
- @listener.ignore_unknown_element = new_value
- end
-
- def do_validate
- @listener.do_validate
- end
-
- def do_validate=(new_value)
- @listener.do_validate = new_value
- end
-
- def parse
- if @listener.rss.nil?
- _parse
- end
- @listener.rss
- end
-
- end
-
- class BaseListener
-
- extend Utils
-
- class << self
-
- @@accessor_bases = {}
- @@registered_uris = {}
- @@class_names = {}
-
- # return the setter for the uri, tag_name pair, or nil.
- def setter(uri, tag_name)
- _getter = getter(uri, tag_name)
- if _getter
- "#{_getter}="
- else
- nil
- end
- end
-
- def getter(uri, tag_name)
- (@@accessor_bases[uri] || {})[tag_name]
- end
-
- # return the tag_names for setters associated with uri
- def available_tags(uri)
- (@@accessor_bases[uri] || {}).keys
- end
-
- # register uri against this name.
- def register_uri(uri, name)
- @@registered_uris[name] ||= {}
- @@registered_uris[name][uri] = nil
- end
-
- # test if this uri is registered against this name
- def uri_registered?(uri, name)
- @@registered_uris[name].has_key?(uri)
- end
-
- # record class_name for the supplied uri and tag_name
- def install_class_name(uri, tag_name, class_name)
- @@class_names[uri] ||= {}
- @@class_names[uri][tag_name] = class_name
- end
-
- # retrieve class_name for the supplied uri and tag_name
- # If it doesn't exist, capitalize the tag_name
- def class_name(uri, tag_name)
- name = (@@class_names[uri] || {})[tag_name]
- return name if name
-
- tag_name = tag_name.gsub(/[_\-]([a-z]?)/) {$1.upcase}
- tag_name[0, 1].upcase + tag_name[1..-1]
- end
-
- def install_get_text_element(uri, name, accessor_base)
- install_accessor_base(uri, name, accessor_base)
- def_get_text_element(uri, name, *get_file_and_line_from_caller(1))
- end
-
- def raise_for_undefined_entity?
- true
- end
-
- private
- # set the accessor for the uri, tag_name pair
- def install_accessor_base(uri, tag_name, accessor_base)
- @@accessor_bases[uri] ||= {}
- @@accessor_bases[uri][tag_name] = accessor_base.chomp("=")
- end
-
- def def_get_text_element(uri, element_name, file, line)
- register_uri(uri, element_name)
- method_name = "start_#{element_name}"
- unless private_method_defined?(method_name)
- define_method(method_name) do |name, prefix, attrs, ns|
- uri = _ns(ns, prefix)
- if self.class.uri_registered?(uri, element_name)
- start_get_text_element(name, prefix, ns, uri)
- else
- start_else_element(name, prefix, attrs, ns)
- end
- end
- private(method_name)
- end
- end
- end
- end
-
- module ListenerMixin
- attr_reader :rss
-
- attr_accessor :ignore_unknown_element
- attr_accessor :do_validate
-
- def initialize
- @rss = nil
- @ignore_unknown_element = true
- @do_validate = true
- @ns_stack = [{"xml" => :xml}]
- @tag_stack = [[]]
- @text_stack = ['']
- @proc_stack = []
- @last_element = nil
- @version = @encoding = @standalone = nil
- @xml_stylesheets = []
- @xml_child_mode = false
- @xml_element = nil
- @last_xml_element = nil
- end
-
- # set instance vars for version, encoding, standalone
- def xmldecl(version, encoding, standalone)
- @version, @encoding, @standalone = version, encoding, standalone
- end
-
- def instruction(name, content)
- if name == "xml-stylesheet"
- params = parse_pi_content(content)
- if params.has_key?("href")
- @xml_stylesheets << XMLStyleSheet.new(params)
- end
- end
- end
-
- def tag_start(name, attributes)
- @text_stack.push('')
-
- ns = @ns_stack.last.dup
- attrs = {}
- attributes.each do |n, v|
- if /\Axmlns(?:\z|:)/ =~ n
- ns[$POSTMATCH] = v
- else
- attrs[n] = v
- end
- end
- @ns_stack.push(ns)
-
- prefix, local = split_name(name)
- @tag_stack.last.push([_ns(ns, prefix), local])
- @tag_stack.push([])
- if @xml_child_mode
- previous = @last_xml_element
- element_attrs = attributes.dup
- unless previous
- ns.each do |ns_prefix, value|
- next if ns_prefix == "xml"
- key = ns_prefix.empty? ? "xmlns" : "xmlns:#{ns_prefix}"
- element_attrs[key] ||= value
- end
- end
- next_element = XML::Element.new(local,
- prefix.empty? ? nil : prefix,
- _ns(ns, prefix),
- element_attrs)
- previous << next_element if previous
- @last_xml_element = next_element
- pr = Proc.new do |text, tags|
- if previous
- @last_xml_element = previous
- else
- @xml_element = @last_xml_element
- @last_xml_element = nil
- end
- end
- @proc_stack.push(pr)
- else
- if @rss.nil? and respond_to?("initial_start_#{local}", true)
- __send__("initial_start_#{local}", local, prefix, attrs, ns.dup)
- elsif respond_to?("start_#{local}", true)
- __send__("start_#{local}", local, prefix, attrs, ns.dup)
- else
- start_else_element(local, prefix, attrs, ns.dup)
- end
- end
- end
-
- def tag_end(name)
- if DEBUG
- p "end tag #{name}"
- p @tag_stack
- end
- text = @text_stack.pop
- tags = @tag_stack.pop
- pr = @proc_stack.pop
- pr.call(text, tags) unless pr.nil?
- @ns_stack.pop
- end
-
- def text(data)
- if @xml_child_mode
- @last_xml_element << data if @last_xml_element
- else
- @text_stack.last << data
- end
- end
-
- private
- def _ns(ns, prefix)
- ns.fetch(prefix, "")
- end
-
- CONTENT_PATTERN = /\s*([^=]+)=(["'])([^\2]+?)\2/
- # Extract the first name="value" pair from content.
- # Works with single quotes according to the constant
- # CONTENT_PATTERN. Return a Hash.
- def parse_pi_content(content)
- params = {}
- content.scan(CONTENT_PATTERN) do |name, quote, value|
- params[name] = value
- end
- params
- end
-
- def start_else_element(local, prefix, attrs, ns)
- class_name = self.class.class_name(_ns(ns, prefix), local)
- current_class = @last_element.class
- if known_class?(current_class, class_name)
- next_class = current_class.const_get(class_name)
- start_have_something_element(local, prefix, attrs, ns, next_class)
- else
- if !@do_validate or @ignore_unknown_element
- @proc_stack.push(setup_next_element_in_unknown_element)
- else
- parent = "ROOT ELEMENT???"
- if current_class.tag_name
- parent = current_class.tag_name
- end
- raise NotExpectedTagError.new(local, _ns(ns, prefix), parent)
- end
- end
- end
-
- if Module.method(:const_defined?).arity == -1
- def known_class?(target_class, class_name)
- class_name and
- (target_class.const_defined?(class_name, false) or
- target_class.constants.include?(class_name.to_sym))
- end
- else
- def known_class?(target_class, class_name)
- class_name and
- (target_class.const_defined?(class_name) or
- target_class.constants.include?(class_name))
- end
- end
-
- NAMESPLIT = /^(?:([\w:][-\w.]*):)?([\w:][-\w.]*)/
- def split_name(name)
- name =~ NAMESPLIT
- [$1 || '', $2]
- end
-
- def check_ns(tag_name, prefix, ns, require_uri, ignore_unknown_element=nil)
- if _ns(ns, prefix) == require_uri
- true
- else
- if ignore_unknown_element.nil?
- ignore_unknown_element = @ignore_unknown_element
- end
-
- if ignore_unknown_element
- false
- elsif @do_validate
- raise NSError.new(tag_name, prefix, require_uri)
- else
- # Force bind required URI with prefix
- @ns_stack.last[prefix] = require_uri
- true
- end
- end
- end
-
- def start_get_text_element(tag_name, prefix, ns, required_uri)
- pr = Proc.new do |text, tags|
- setter = self.class.setter(required_uri, tag_name)
- if setter and @last_element.respond_to?(setter)
- if @do_validate
- getter = self.class.getter(required_uri, tag_name)
- if @last_element.__send__(getter)
- raise TooMuchTagError.new(tag_name, @last_element.tag_name)
- end
- end
- @last_element.__send__(setter, text.to_s)
- else
- if @do_validate and !@ignore_unknown_element
- raise NotExpectedTagError.new(tag_name, _ns(ns, prefix),
- @last_element.tag_name)
- end
- end
- end
- @proc_stack.push(pr)
- end
-
- def start_have_something_element(tag_name, prefix, attrs, ns, klass)
- if check_ns(tag_name, prefix, ns, klass.required_uri)
- attributes = collect_attributes(tag_name, prefix, attrs, ns, klass)
- @proc_stack.push(setup_next_element(tag_name, klass, attributes))
- else
- @proc_stack.push(setup_next_element_in_unknown_element)
- end
- end
-
- def collect_attributes(tag_name, prefix, attrs, ns, klass)
- attributes = {}
- klass.get_attributes.each do |a_name, a_uri, required, element_name|
- if a_uri.is_a?(String) or !a_uri.respond_to?(:include?)
- a_uri = [a_uri]
- end
- unless a_uri == [""]
- for prefix, uri in ns
- if a_uri.include?(uri)
- val = attrs["#{prefix}:#{a_name}"]
- break if val
- end
- end
- end
- if val.nil? and a_uri.include?("")
- val = attrs[a_name]
- end
-
- if @do_validate and required and val.nil?
- unless a_uri.include?("")
- for prefix, uri in ns
- if a_uri.include?(uri)
- a_name = "#{prefix}:#{a_name}"
- end
- end
- end
- raise MissingAttributeError.new(tag_name, a_name)
- end
-
- attributes[a_name] = val
- end
- attributes
- end
-
- def setup_next_element(tag_name, klass, attributes)
- previous = @last_element
- next_element = klass.new(@do_validate, attributes)
- previous.set_next_element(tag_name, next_element)
- @last_element = next_element
- @last_element.parent = previous if klass.need_parent?
- @xml_child_mode = @last_element.have_xml_content?
-
- Proc.new do |text, tags|
- p(@last_element.class) if DEBUG
- if @xml_child_mode
- @last_element.content = @xml_element.to_s
- xml_setter = @last_element.class.xml_setter
- @last_element.__send__(xml_setter, @xml_element)
- @xml_element = nil
- @xml_child_mode = false
- else
- if klass.have_content?
- if @last_element.need_base64_encode?
- text = text.lstrip.unpack("m").first
- end
- @last_element.content = text
- end
- end
- if @do_validate
- @last_element.validate_for_stream(tags, @ignore_unknown_element)
- end
- @last_element = previous
- end
- end
-
- def setup_next_element_in_unknown_element
- current_element, @last_element = @last_element, nil
- Proc.new {@last_element = current_element}
- end
- end
-
- unless const_defined? :AVAILABLE_PARSER_LIBRARIES
- AVAILABLE_PARSER_LIBRARIES = [
- ["rss/xmlparser", :XMLParserParser],
- ["rss/xmlscanner", :XMLScanParser],
- ["rss/rexmlparser", :REXMLParser],
- ]
- end
-
- AVAILABLE_PARSERS = []
-
- AVAILABLE_PARSER_LIBRARIES.each do |lib, parser|
- begin
- require lib
- AVAILABLE_PARSERS.push(const_get(parser))
- rescue LoadError
- end
- end
-
- if AVAILABLE_PARSERS.empty?
- raise XMLParserNotFound
- end
-end
diff --git a/ruby_1_9_3/lib/rss/rexmlparser.rb b/ruby_1_9_3/lib/rss/rexmlparser.rb
deleted file mode 100644
index 7112ac3669..0000000000
--- a/ruby_1_9_3/lib/rss/rexmlparser.rb
+++ /dev/null
@@ -1,54 +0,0 @@
-require "rexml/document"
-require "rexml/streamlistener"
-
-/\A(\d+)\.(\d+)(?:\.\d+)+\z/ =~ REXML::Version
-if ([$1.to_i, $2.to_i] <=> [2, 5]) < 0
- raise LoadError, "needs REXML 2.5 or later (#{REXML::Version})"
-end
-
-module RSS
-
- class REXMLParser < BaseParser
-
- class << self
- def listener
- REXMLListener
- end
- end
-
- private
- def _parse
- begin
- REXML::Document.parse_stream(@rss, @listener)
- rescue RuntimeError => e
- raise NotWellFormedError.new{e.message}
- rescue REXML::ParseException => e
- context = e.context
- line = context[0] if context
- raise NotWellFormedError.new(line){e.message}
- end
- end
-
- end
-
- class REXMLListener < BaseListener
-
- include REXML::StreamListener
- include ListenerMixin
-
- class << self
- def raise_for_undefined_entity?
- false
- end
- end
-
- def xmldecl(version, encoding, standalone)
- super(version, encoding, standalone == "yes")
- # Encoding is converted to UTF-8 when REXML parse XML.
- @encoding = 'UTF-8'
- end
-
- alias_method(:cdata, :text)
- end
-
-end
diff --git a/ruby_1_9_3/lib/rss/rss.rb b/ruby_1_9_3/lib/rss/rss.rb
deleted file mode 100644
index 3d90d54912..0000000000
--- a/ruby_1_9_3/lib/rss/rss.rb
+++ /dev/null
@@ -1,1342 +0,0 @@
-require "time"
-
-class Time
- class << self
- unless respond_to?(:w3cdtf)
- def w3cdtf(date)
- if /\A\s*
- (-?\d+)-(\d\d)-(\d\d)
- (?:T
- (\d\d):(\d\d)(?::(\d\d))?
- (\.\d+)?
- (Z|[+-]\d\d:\d\d)?)?
- \s*\z/ix =~ date and (($5 and $8) or (!$5 and !$8))
- datetime = [$1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i]
- usec = 0
- usec = $7.to_f * 1000000 if $7
- zone = $8
- if zone
- off = zone_offset(zone, datetime[0])
- datetime = apply_offset(*(datetime + [off]))
- datetime << usec
- time = Time.utc(*datetime)
- time.localtime unless zone_utc?(zone)
- time
- else
- datetime << usec
- Time.local(*datetime)
- end
- else
- raise ArgumentError.new("invalid date: #{date.inspect}")
- end
- end
- end
- end
-
- unless method_defined?(:w3cdtf)
- def w3cdtf
- if usec.zero?
- fraction_digits = 0
- else
- fraction_digits = Math.log10(usec.to_s.sub(/0*$/, '').to_i).floor + 1
- end
- xmlschema(fraction_digits)
- end
- end
-end
-
-
-require "English"
-require "rss/utils"
-require "rss/converter"
-require "rss/xml-stylesheet"
-
-module RSS
-
- VERSION = "0.2.7"
-
- URI = "http://purl.org/rss/1.0/"
-
- DEBUG = false
-
- class Error < StandardError; end
-
- class OverlappedPrefixError < Error
- attr_reader :prefix
- def initialize(prefix)
- @prefix = prefix
- end
- end
-
- class InvalidRSSError < Error; end
-
- ##
- # Raised if no matching tag is found.
-
- class MissingTagError < InvalidRSSError
- attr_reader :tag, :parent
- def initialize(tag, parent)
- @tag, @parent = tag, parent
- super("tag <#{tag}> is missing in tag <#{parent}>")
- end
- end
-
- ##
- # Raised if there are more occurrences of the tag than expected.
-
- class TooMuchTagError < InvalidRSSError
- attr_reader :tag, :parent
- def initialize(tag, parent)
- @tag, @parent = tag, parent
- super("tag <#{tag}> is too much in tag <#{parent}>")
- end
- end
-
- ##
- # Raised if a required attribute is missing.
-
- class MissingAttributeError < InvalidRSSError
- attr_reader :tag, :attribute
- def initialize(tag, attribute)
- @tag, @attribute = tag, attribute
- super("attribute <#{attribute}> is missing in tag <#{tag}>")
- end
- end
-
- ##
- # Raised when an unknown tag is found.
-
- class UnknownTagError < InvalidRSSError
- attr_reader :tag, :uri
- def initialize(tag, uri)
- @tag, @uri = tag, uri
- super("tag <#{tag}> is unknown in namespace specified by uri <#{uri}>")
- end
- end
-
- ##
- # Raised when an unexpected tag is encountered.
-
- class NotExpectedTagError < InvalidRSSError
- attr_reader :tag, :uri, :parent
- def initialize(tag, uri, parent)
- @tag, @uri, @parent = tag, uri, parent
- super("tag <{#{uri}}#{tag}> is not expected in tag <#{parent}>")
- end
- end
- # For backward compatibility :X
- NotExceptedTagError = NotExpectedTagError
-
- ##
- # Raised when an incorrect value is used.
-
- class NotAvailableValueError < InvalidRSSError
- attr_reader :tag, :value, :attribute
- def initialize(tag, value, attribute=nil)
- @tag, @value, @attribute = tag, value, attribute
- message = "value <#{value}> of "
- message << "attribute <#{attribute}> of " if attribute
- message << "tag <#{tag}> is not available."
- super(message)
- end
- end
-
- ##
- # Raised when an unknown conversion error occurs.
-
- class UnknownConversionMethodError < Error
- attr_reader :to, :from
- def initialize(to, from)
- @to = to
- @from = from
- super("can't convert to #{to} from #{from}.")
- end
- end
- # for backward compatibility
- UnknownConvertMethod = UnknownConversionMethodError
-
- ##
- # Raised when a conversion failure occurs.
-
- class ConversionError < Error
- attr_reader :string, :to, :from
- def initialize(string, to, from)
- @string = string
- @to = to
- @from = from
- super("can't convert #{@string} to #{to} from #{from}.")
- end
- end
-
- ##
- # Raised when a required variable is not set.
-
- class NotSetError < Error
- attr_reader :name, :variables
- def initialize(name, variables)
- @name = name
- @variables = variables
- super("required variables of #{@name} are not set: #{@variables.join(', ')}")
- end
- end
-
- ##
- # Raised when a RSS::Maker attempts to use an unknown maker.
-
- class UnsupportedMakerVersionError < Error
- attr_reader :version
- def initialize(version)
- @version = version
- super("Maker doesn't support version: #{@version}")
- end
- end
-
- module BaseModel
- include Utils
-
- def install_have_child_element(tag_name, uri, occurs, name=nil, type=nil)
- name ||= tag_name
- add_need_initialize_variable(name)
- install_model(tag_name, uri, occurs, name)
-
- writer_type, reader_type = type
- def_corresponded_attr_writer name, writer_type
- def_corresponded_attr_reader name, reader_type
- install_element(name) do |n, elem_name|
- <<-EOC
- if @#{n}
- "\#{@#{n}.to_s(need_convert, indent)}"
- else
- ''
- end
-EOC
- end
- end
- alias_method(:install_have_attribute_element, :install_have_child_element)
-
- def install_have_children_element(tag_name, uri, occurs, name=nil, plural_name=nil)
- name ||= tag_name
- plural_name ||= "#{name}s"
- add_have_children_element(name, plural_name)
- add_plural_form(name, plural_name)
- install_model(tag_name, uri, occurs, plural_name, true)
-
- def_children_accessor(name, plural_name)
- install_element(name, "s") do |n, elem_name|
- <<-EOC
- rv = []
- @#{n}.each do |x|
- value = "\#{x.to_s(need_convert, indent)}"
- rv << value if /\\A\\s*\\z/ !~ value
- end
- rv.join("\n")
-EOC
- end
- end
-
- def install_text_element(tag_name, uri, occurs, name=nil, type=nil,
- disp_name=nil)
- name ||= tag_name
- disp_name ||= name
- self::ELEMENTS << name unless self::ELEMENTS.include?(name)
- add_need_initialize_variable(name)
- install_model(tag_name, uri, occurs, name)
-
- def_corresponded_attr_writer(name, type, disp_name)
- def_corresponded_attr_reader(name, type || :convert)
- install_element(name) do |n, elem_name|
- <<-EOC
- if respond_to?(:#{n}_content)
- content = #{n}_content
- else
- content = @#{n}
- end
- if content
- rv = "\#{indent}<#{elem_name}>"
- value = html_escape(content)
- if need_convert
- rv << convert(value)
- else
- rv << value
- end
- rv << "</#{elem_name}>"
- rv
- else
- ''
- end
-EOC
- end
- end
-
- def install_date_element(tag_name, uri, occurs, name=nil, type=nil, disp_name=nil)
- name ||= tag_name
- type ||= :w3cdtf
- disp_name ||= name
- self::ELEMENTS << name
- add_need_initialize_variable(name)
- install_model(tag_name, uri, occurs, name)
-
- # accessor
- convert_attr_reader name
- date_writer(name, type, disp_name)
-
- install_element(name) do |n, elem_name|
- <<-EOC
- if @#{n}
- rv = "\#{indent}<#{elem_name}>"
- value = html_escape(@#{n}.#{type})
- if need_convert
- rv << convert(value)
- else
- rv << value
- end
- rv << "</#{elem_name}>"
- rv
- else
- ''
- end
-EOC
- end
-
- end
-
- private
- def install_element(name, postfix="")
- elem_name = name.sub('_', ':')
- method_name = "#{name}_element#{postfix}"
- add_to_element_method(method_name)
- module_eval(<<-EOC, *get_file_and_line_from_caller(2))
- def #{method_name}(need_convert=true, indent='')
- #{yield(name, elem_name)}
- end
- private :#{method_name}
-EOC
- end
-
- def inherit_convert_attr_reader(*attrs)
- attrs.each do |attr|
- attr = attr.id2name if attr.kind_of?(Integer)
- module_eval(<<-EOC, *get_file_and_line_from_caller(2))
- def #{attr}_without_inherit
- convert(@#{attr})
- end
-
- def #{attr}
- if @#{attr}
- #{attr}_without_inherit
- elsif @parent
- @parent.#{attr}
- else
- nil
- end
- end
-EOC
- end
- end
-
- def uri_convert_attr_reader(*attrs)
- attrs.each do |attr|
- attr = attr.id2name if attr.kind_of?(Integer)
- module_eval(<<-EOC, *get_file_and_line_from_caller(2))
- def #{attr}_without_base
- convert(@#{attr})
- end
-
- def #{attr}
- value = #{attr}_without_base
- return nil if value.nil?
- if /\\A[a-z][a-z0-9+.\\-]*:/i =~ value
- value
- else
- "\#{base}\#{value}"
- end
- end
-EOC
- end
- end
-
- def convert_attr_reader(*attrs)
- attrs.each do |attr|
- attr = attr.id2name if attr.kind_of?(Integer)
- module_eval(<<-EOC, *get_file_and_line_from_caller(2))
- def #{attr}
- convert(@#{attr})
- end
-EOC
- end
- end
-
- def yes_clean_other_attr_reader(*attrs)
- attrs.each do |attr|
- attr = attr.id2name if attr.kind_of?(Integer)
- module_eval(<<-EOC, __FILE__, __LINE__ + 1)
- attr_reader(:#{attr})
- def #{attr}?
- YesCleanOther.parse(@#{attr})
- end
- EOC
- end
- end
-
- def yes_other_attr_reader(*attrs)
- attrs.each do |attr|
- attr = attr.id2name if attr.kind_of?(Integer)
- module_eval(<<-EOC, __FILE__, __LINE__ + 1)
- attr_reader(:#{attr})
- def #{attr}?
- Utils::YesOther.parse(@#{attr})
- end
- EOC
- end
- end
-
- def csv_attr_reader(*attrs)
- separator = nil
- if attrs.last.is_a?(Hash)
- options = attrs.pop
- separator = options[:separator]
- end
- separator ||= ", "
- attrs.each do |attr|
- attr = attr.id2name if attr.kind_of?(Integer)
- module_eval(<<-EOC, __FILE__, __LINE__ + 1)
- attr_reader(:#{attr})
- def #{attr}_content
- if @#{attr}.nil?
- @#{attr}
- else
- @#{attr}.join(#{separator.dump})
- end
- end
- EOC
- end
- end
-
- def date_writer(name, type, disp_name=name)
- module_eval(<<-EOC, *get_file_and_line_from_caller(2))
- def #{name}=(new_value)
- if new_value.nil?
- @#{name} = new_value
- elsif new_value.kind_of?(Time)
- @#{name} = new_value.dup
- else
- if @do_validate
- begin
- @#{name} = Time.__send__('#{type}', new_value)
- rescue ArgumentError
- raise NotAvailableValueError.new('#{disp_name}', new_value)
- end
- else
- @#{name} = nil
- if /\\A\\s*\\z/ !~ new_value.to_s
- begin
- unless Date._parse(new_value, false).empty?
- @#{name} = Time.parse(new_value)
- end
- rescue ArgumentError
- end
- end
- end
- end
-
- # Is it need?
- if @#{name}
- class << @#{name}
- undef_method(:to_s)
- alias_method(:to_s, :#{type})
- end
- end
-
- end
-EOC
- end
-
- def integer_writer(name, disp_name=name)
- module_eval(<<-EOC, *get_file_and_line_from_caller(2))
- def #{name}=(new_value)
- if new_value.nil?
- @#{name} = new_value
- else
- if @do_validate
- begin
- @#{name} = Integer(new_value)
- rescue ArgumentError
- raise NotAvailableValueError.new('#{disp_name}', new_value)
- end
- else
- @#{name} = new_value.to_i
- end
- end
- end
-EOC
- end
-
- def positive_integer_writer(name, disp_name=name)
- module_eval(<<-EOC, *get_file_and_line_from_caller(2))
- def #{name}=(new_value)
- if new_value.nil?
- @#{name} = new_value
- else
- if @do_validate
- begin
- tmp = Integer(new_value)
- raise ArgumentError if tmp <= 0
- @#{name} = tmp
- rescue ArgumentError
- raise NotAvailableValueError.new('#{disp_name}', new_value)
- end
- else
- @#{name} = new_value.to_i
- end
- end
- end
-EOC
- end
-
- def boolean_writer(name, disp_name=name)
- module_eval(<<-EOC, *get_file_and_line_from_caller(2))
- def #{name}=(new_value)
- if new_value.nil?
- @#{name} = new_value
- else
- if @do_validate and
- ![true, false, "true", "false"].include?(new_value)
- raise NotAvailableValueError.new('#{disp_name}', new_value)
- end
- if [true, false].include?(new_value)
- @#{name} = new_value
- else
- @#{name} = new_value == "true"
- end
- end
- end
-EOC
- end
-
- def text_type_writer(name, disp_name=name)
- module_eval(<<-EOC, *get_file_and_line_from_caller(2))
- def #{name}=(new_value)
- if @do_validate and
- !["text", "html", "xhtml", nil].include?(new_value)
- raise NotAvailableValueError.new('#{disp_name}', new_value)
- end
- @#{name} = new_value
- end
-EOC
- end
-
- def content_writer(name, disp_name=name)
- klass_name = "self.class::#{Utils.to_class_name(name)}"
- module_eval(<<-EOC, *get_file_and_line_from_caller(2))
- def #{name}=(new_value)
- if new_value.is_a?(#{klass_name})
- @#{name} = new_value
- else
- @#{name} = #{klass_name}.new
- @#{name}.content = new_value
- end
- end
-EOC
- end
-
- def yes_clean_other_writer(name, disp_name=name)
- module_eval(<<-EOC, __FILE__, __LINE__ + 1)
- def #{name}=(value)
- value = (value ? "yes" : "no") if [true, false].include?(value)
- @#{name} = value
- end
- EOC
- end
-
- def yes_other_writer(name, disp_name=name)
- module_eval(<<-EOC, __FILE__, __LINE__ + 1)
- def #{name}=(new_value)
- if [true, false].include?(new_value)
- new_value = new_value ? "yes" : "no"
- end
- @#{name} = new_value
- end
- EOC
- end
-
- def csv_writer(name, disp_name=name)
- module_eval(<<-EOC, __FILE__, __LINE__ + 1)
- def #{name}=(new_value)
- @#{name} = Utils::CSV.parse(new_value)
- end
- EOC
- end
-
- def csv_integer_writer(name, disp_name=name)
- module_eval(<<-EOC, __FILE__, __LINE__ + 1)
- def #{name}=(new_value)
- @#{name} = Utils::CSV.parse(new_value) {|v| Integer(v)}
- end
- EOC
- end
-
- def def_children_accessor(accessor_name, plural_name)
- module_eval(<<-EOC, *get_file_and_line_from_caller(2))
- def #{plural_name}
- @#{accessor_name}
- end
-
- def #{accessor_name}(*args)
- if args.empty?
- @#{accessor_name}.first
- else
- @#{accessor_name}[*args]
- end
- end
-
- def #{accessor_name}=(*args)
- receiver = self.class.name
- warn("Warning:\#{caller.first.sub(/:in `.*'\z/, '')}: " \
- "Don't use `\#{receiver}\##{accessor_name} = XXX'/" \
- "`\#{receiver}\#set_#{accessor_name}(XXX)'. " \
- "Those APIs are not sense of Ruby. " \
- "Use `\#{receiver}\##{plural_name} << XXX' instead of them.")
- if args.size == 1
- @#{accessor_name}.push(args[0])
- else
- @#{accessor_name}.__send__("[]=", *args)
- end
- end
- alias_method(:set_#{accessor_name}, :#{accessor_name}=)
-EOC
- end
- end
-
- module SetupMaker
- def setup_maker(maker)
- target = maker_target(maker)
- unless target.nil?
- setup_maker_attributes(target)
- setup_maker_element(target)
- setup_maker_elements(target)
- end
- end
-
- private
- def maker_target(maker)
- nil
- end
-
- def setup_maker_attributes(target)
- end
-
- def setup_maker_element(target)
- self.class.need_initialize_variables.each do |var|
- value = __send__(var)
- next if value.nil?
- if value.respond_to?("setup_maker") and
- !not_need_to_call_setup_maker_variables.include?(var)
- value.setup_maker(target)
- else
- setter = "#{var}="
- if target.respond_to?(setter)
- target.__send__(setter, value)
- end
- end
- end
- end
-
- def not_need_to_call_setup_maker_variables
- []
- end
-
- def setup_maker_elements(parent)
- self.class.have_children_elements.each do |name, plural_name|
- if parent.respond_to?(plural_name)
- target = parent.__send__(plural_name)
- __send__(plural_name).each do |elem|
- elem.setup_maker(target)
- end
- end
- end
- end
- end
-
- class Element
- extend BaseModel
- include Utils
- extend Utils::InheritedReader
- include SetupMaker
-
- INDENT = " "
-
- MUST_CALL_VALIDATORS = {}
- MODELS = []
- GET_ATTRIBUTES = []
- HAVE_CHILDREN_ELEMENTS = []
- TO_ELEMENT_METHODS = []
- NEED_INITIALIZE_VARIABLES = []
- PLURAL_FORMS = {}
-
- class << self
- def must_call_validators
- inherited_hash_reader("MUST_CALL_VALIDATORS")
- end
- def models
- inherited_array_reader("MODELS")
- end
- def get_attributes
- inherited_array_reader("GET_ATTRIBUTES")
- end
- def have_children_elements
- inherited_array_reader("HAVE_CHILDREN_ELEMENTS")
- end
- def to_element_methods
- inherited_array_reader("TO_ELEMENT_METHODS")
- end
- def need_initialize_variables
- inherited_array_reader("NEED_INITIALIZE_VARIABLES")
- end
- def plural_forms
- inherited_hash_reader("PLURAL_FORMS")
- end
-
- def inherited_base
- ::RSS::Element
- end
-
- def inherited(klass)
- klass.const_set("MUST_CALL_VALIDATORS", {})
- klass.const_set("MODELS", [])
- klass.const_set("GET_ATTRIBUTES", [])
- klass.const_set("HAVE_CHILDREN_ELEMENTS", [])
- klass.const_set("TO_ELEMENT_METHODS", [])
- klass.const_set("NEED_INITIALIZE_VARIABLES", [])
- klass.const_set("PLURAL_FORMS", {})
-
- tag_name = klass.name.split(/::/).last
- tag_name[0, 1] = tag_name[0, 1].downcase
- klass.instance_variable_set("@tag_name", tag_name)
- klass.instance_variable_set("@have_content", false)
- end
-
- def install_must_call_validator(prefix, uri)
- self::MUST_CALL_VALIDATORS[uri] = prefix
- end
-
- def install_model(tag, uri, occurs=nil, getter=nil, plural=false)
- getter ||= tag
- if m = self::MODELS.find {|t, u, o, g, p| t == tag and u == uri}
- m[2] = occurs
- else
- self::MODELS << [tag, uri, occurs, getter, plural]
- end
- end
-
- def install_get_attribute(name, uri, required=true,
- type=nil, disp_name=nil,
- element_name=nil)
- disp_name ||= name
- element_name ||= name
- writer_type, reader_type = type
- def_corresponded_attr_writer name, writer_type, disp_name
- def_corresponded_attr_reader name, reader_type
- if type == :boolean and /^is/ =~ name
- alias_method "#{$POSTMATCH}?", name
- end
- self::GET_ATTRIBUTES << [name, uri, required, element_name]
- add_need_initialize_variable(disp_name)
- end
-
- def def_corresponded_attr_writer(name, type=nil, disp_name=nil)
- disp_name ||= name
- case type
- when :integer
- integer_writer name, disp_name
- when :positive_integer
- positive_integer_writer name, disp_name
- when :boolean
- boolean_writer name, disp_name
- when :w3cdtf, :rfc822, :rfc2822
- date_writer name, type, disp_name
- when :text_type
- text_type_writer name, disp_name
- when :content
- content_writer name, disp_name
- when :yes_clean_other
- yes_clean_other_writer name, disp_name
- when :yes_other
- yes_other_writer name, disp_name
- when :csv
- csv_writer name
- when :csv_integer
- csv_integer_writer name
- else
- attr_writer name
- end
- end
-
- def def_corresponded_attr_reader(name, type=nil)
- case type
- when :inherit
- inherit_convert_attr_reader name
- when :uri
- uri_convert_attr_reader name
- when :yes_clean_other
- yes_clean_other_attr_reader name
- when :yes_other
- yes_other_attr_reader name
- when :csv
- csv_attr_reader name
- when :csv_integer
- csv_attr_reader name, :separator => ","
- else
- convert_attr_reader name
- end
- end
-
- def content_setup(type=nil, disp_name=nil)
- writer_type, reader_type = type
- def_corresponded_attr_writer :content, writer_type, disp_name
- def_corresponded_attr_reader :content, reader_type
- @have_content = true
- end
-
- def have_content?
- @have_content
- end
-
- def add_have_children_element(variable_name, plural_name)
- self::HAVE_CHILDREN_ELEMENTS << [variable_name, plural_name]
- end
-
- def add_to_element_method(method_name)
- self::TO_ELEMENT_METHODS << method_name
- end
-
- def add_need_initialize_variable(variable_name)
- self::NEED_INITIALIZE_VARIABLES << variable_name
- end
-
- def add_plural_form(singular, plural)
- self::PLURAL_FORMS[singular] = plural
- end
-
- def required_prefix
- nil
- end
-
- def required_uri
- ""
- end
-
- def need_parent?
- false
- end
-
- def install_ns(prefix, uri)
- if self::NSPOOL.has_key?(prefix)
- raise OverlappedPrefixError.new(prefix)
- end
- self::NSPOOL[prefix] = uri
- end
-
- def tag_name
- @tag_name
- end
- end
-
- attr_accessor :parent, :do_validate
-
- def initialize(do_validate=true, attrs=nil)
- @parent = nil
- @converter = nil
- if attrs.nil? and (do_validate.is_a?(Hash) or do_validate.is_a?(Array))
- do_validate, attrs = true, do_validate
- end
- @do_validate = do_validate
- initialize_variables(attrs || {})
- end
-
- def tag_name
- self.class.tag_name
- end
-
- def full_name
- tag_name
- end
-
- def converter=(converter)
- @converter = converter
- targets = children.dup
- self.class.have_children_elements.each do |variable_name, plural_name|
- targets.concat(__send__(plural_name))
- end
- targets.each do |target|
- target.converter = converter unless target.nil?
- end
- end
-
- def convert(value)
- if @converter
- @converter.convert(value)
- else
- value
- end
- end
-
- def valid?(ignore_unknown_element=true)
- validate(ignore_unknown_element)
- true
- rescue RSS::Error
- false
- end
-
- def validate(ignore_unknown_element=true)
- do_validate = @do_validate
- @do_validate = true
- validate_attribute
- __validate(ignore_unknown_element)
- ensure
- @do_validate = do_validate
- end
-
- def validate_for_stream(tags, ignore_unknown_element=true)
- validate_attribute
- __validate(ignore_unknown_element, tags, false)
- end
-
- def to_s(need_convert=true, indent='')
- if self.class.have_content?
- return "" if !empty_content? and !content_is_set?
- rv = tag(indent) do |next_indent|
- if empty_content?
- ""
- else
- xmled_content
- end
- end
- else
- rv = tag(indent) do |next_indent|
- self.class.to_element_methods.collect do |method_name|
- __send__(method_name, false, next_indent)
- end
- end
- end
- rv = convert(rv) if need_convert
- rv
- end
-
- def have_xml_content?
- false
- end
-
- def need_base64_encode?
- false
- end
-
- def set_next_element(tag_name, next_element)
- klass = next_element.class
- prefix = ""
- prefix << "#{klass.required_prefix}_" if klass.required_prefix
- key = "#{prefix}#{tag_name.gsub(/-/, '_')}"
- if self.class.plural_forms.has_key?(key)
- ary = __send__("#{self.class.plural_forms[key]}")
- ary << next_element
- else
- __send__("#{key}=", next_element)
- end
- end
-
- protected
- def have_required_elements?
- self.class::MODELS.all? do |tag, uri, occurs, getter|
- if occurs.nil? or occurs == "+"
- child = __send__(getter)
- if child.is_a?(Array)
- children = child
- children.any? {|c| c.have_required_elements?}
- else
- !child.to_s.empty?
- end
- else
- true
- end
- end
- end
-
- private
- def initialize_variables(attrs)
- normalized_attrs = {}
- attrs.each do |key, value|
- normalized_attrs[key.to_s] = value
- end
- self.class.need_initialize_variables.each do |variable_name|
- value = normalized_attrs[variable_name.to_s]
- if value
- __send__("#{variable_name}=", value)
- else
- instance_variable_set("@#{variable_name}", nil)
- end
- end
- initialize_have_children_elements
- @content = normalized_attrs["content"] if self.class.have_content?
- end
-
- def initialize_have_children_elements
- self.class.have_children_elements.each do |variable_name, plural_name|
- instance_variable_set("@#{variable_name}", [])
- end
- end
-
- def tag(indent, additional_attrs={}, &block)
- next_indent = indent + INDENT
-
- attrs = collect_attrs
- return "" if attrs.nil?
-
- return "" unless have_required_elements?
-
- attrs.update(additional_attrs)
- start_tag = make_start_tag(indent, next_indent, attrs.dup)
-
- if block
- content = block.call(next_indent)
- else
- content = []
- end
-
- if content.is_a?(String)
- content = [content]
- start_tag << ">"
- end_tag = "</#{full_name}>"
- else
- content = content.reject{|x| x.empty?}
- if content.empty?
- return "" if attrs.empty?
- end_tag = "/>"
- else
- start_tag << ">\n"
- end_tag = "\n#{indent}</#{full_name}>"
- end
- end
-
- start_tag + content.join("\n") + end_tag
- end
-
- def make_start_tag(indent, next_indent, attrs)
- start_tag = ["#{indent}<#{full_name}"]
- unless attrs.empty?
- start_tag << attrs.collect do |key, value|
- %Q[#{h key}="#{h value}"]
- end.join("\n#{next_indent}")
- end
- start_tag.join(" ")
- end
-
- def collect_attrs
- attrs = {}
- _attrs.each do |name, required, alias_name|
- value = __send__(alias_name || name)
- return nil if required and value.nil?
- next if value.nil?
- return nil if attrs.has_key?(name)
- attrs[name] = value
- end
- attrs
- end
-
- def tag_name_with_prefix(prefix)
- "#{prefix}:#{tag_name}"
- end
-
- # For backward compatibility
- def calc_indent
- ''
- end
-
- def children
- rv = []
- self.class.models.each do |name, uri, occurs, getter|
- value = __send__(getter)
- next if value.nil?
- value = [value] unless value.is_a?(Array)
- value.each do |v|
- rv << v if v.is_a?(Element)
- end
- end
- rv
- end
-
- def _tags
- rv = []
- self.class.models.each do |name, uri, occurs, getter, plural|
- value = __send__(getter)
- next if value.nil?
- if plural and value.is_a?(Array)
- rv.concat([[uri, name]] * value.size)
- else
- rv << [uri, name]
- end
- end
- rv
- end
-
- def _attrs
- self.class.get_attributes.collect do |name, uri, required, element_name|
- [element_name, required, name]
- end
- end
-
- def __validate(ignore_unknown_element, tags=_tags, recursive=true)
- if recursive
- children.compact.each do |child|
- child.validate
- end
- end
- must_call_validators = self.class.must_call_validators
- tags = tag_filter(tags.dup)
- p tags if DEBUG
- must_call_validators.each do |uri, prefix|
- _validate(ignore_unknown_element, tags[uri], uri)
- meth = "#{prefix}_validate"
- if !prefix.empty? and respond_to?(meth, true)
- __send__(meth, ignore_unknown_element, tags[uri], uri)
- end
- end
- end
-
- def validate_attribute
- _attrs.each do |a_name, required, alias_name|
- value = instance_variable_get("@#{alias_name || a_name}")
- if required and value.nil?
- raise MissingAttributeError.new(tag_name, a_name)
- end
- __send__("#{alias_name || a_name}=", value)
- end
- end
-
- def _validate(ignore_unknown_element, tags, uri, models=self.class.models)
- count = 1
- do_redo = false
- not_shift = false
- tag = nil
- models = models.find_all {|model| model[1] == uri}
- element_names = models.collect {|model| model[0]}
- if tags
- tags_size = tags.size
- tags = tags.sort_by {|x| element_names.index(x) || tags_size}
- end
-
- models.each_with_index do |model, i|
- name, _, occurs, = model
-
- if DEBUG
- p "before"
- p tags
- p model
- end
-
- if not_shift
- not_shift = false
- elsif tags
- tag = tags.shift
- end
-
- if DEBUG
- p "mid"
- p count
- end
-
- case occurs
- when '?'
- if count > 2
- raise TooMuchTagError.new(name, tag_name)
- else
- if name == tag
- do_redo = true
- else
- not_shift = true
- end
- end
- when '*'
- if name == tag
- do_redo = true
- else
- not_shift = true
- end
- when '+'
- if name == tag
- do_redo = true
- else
- if count > 1
- not_shift = true
- else
- raise MissingTagError.new(name, tag_name)
- end
- end
- else
- if name == tag
- if models[i+1] and models[i+1][0] != name and
- tags and tags.first == name
- raise TooMuchTagError.new(name, tag_name)
- end
- else
- raise MissingTagError.new(name, tag_name)
- end
- end
-
- if DEBUG
- p "after"
- p not_shift
- p do_redo
- p tag
- end
-
- if do_redo
- do_redo = false
- count += 1
- redo
- else
- count = 1
- end
-
- end
-
- if !ignore_unknown_element and !tags.nil? and !tags.empty?
- raise NotExpectedTagError.new(tags.first, uri, tag_name)
- end
-
- end
-
- def tag_filter(tags)
- rv = {}
- tags.each do |tag|
- rv[tag[0]] = [] unless rv.has_key?(tag[0])
- rv[tag[0]].push(tag[1])
- end
- rv
- end
-
- def empty_content?
- false
- end
-
- def content_is_set?
- if have_xml_content?
- __send__(self.class.xml_getter)
- else
- content
- end
- end
-
- def xmled_content
- if have_xml_content?
- __send__(self.class.xml_getter).to_s
- else
- _content = content
- _content = [_content].pack("m").delete("\n") if need_base64_encode?
- h(_content)
- end
- end
- end
-
- module RootElementMixin
-
- include XMLStyleSheetMixin
-
- attr_reader :output_encoding
- attr_reader :feed_type, :feed_subtype, :feed_version
- attr_accessor :version, :encoding, :standalone
- def initialize(feed_version, version=nil, encoding=nil, standalone=nil)
- super()
- @feed_type = nil
- @feed_subtype = nil
- @feed_version = feed_version
- @version = version || '1.0'
- @encoding = encoding
- @standalone = standalone
- @output_encoding = nil
- end
-
- def feed_info
- [@feed_type, @feed_version, @feed_subtype]
- end
-
- def output_encoding=(enc)
- @output_encoding = enc
- self.converter = Converter.new(@output_encoding, @encoding)
- end
-
- def setup_maker(maker)
- maker.version = version
- maker.encoding = encoding
- maker.standalone = standalone
-
- xml_stylesheets.each do |xss|
- xss.setup_maker(maker)
- end
-
- super
- end
-
- def to_feed(type, &block)
- Maker.make(type) do |maker|
- setup_maker(maker)
- block.call(maker) if block
- end
- end
-
- def to_rss(type, &block)
- to_feed("rss#{type}", &block)
- end
-
- def to_atom(type, &block)
- to_feed("atom:#{type}", &block)
- end
-
- def to_xml(type=nil, &block)
- if type.nil? or same_feed_type?(type)
- to_s
- else
- to_feed(type, &block).to_s
- end
- end
-
- private
- def same_feed_type?(type)
- if /^(atom|rss)?(\d+\.\d+)?(?::(.+))?$/i =~ type
- feed_type = ($1 || @feed_type).downcase
- feed_version = $2 || @feed_version
- feed_subtype = $3 || @feed_subtype
- [feed_type, feed_version, feed_subtype] == feed_info
- else
- false
- end
- end
-
- def tag(indent, attrs={}, &block)
- rv = super(indent, ns_declarations.merge(attrs), &block)
- return rv if rv.empty?
- "#{xmldecl}#{xml_stylesheet_pi}#{rv}"
- end
-
- def xmldecl
- rv = %Q[<?xml version="#{@version}"]
- if @output_encoding or @encoding
- rv << %Q[ encoding="#{@output_encoding or @encoding}"]
- end
- rv << %Q[ standalone="yes"] if @standalone
- rv << "?>\n"
- rv
- end
-
- def ns_declarations
- decls = {}
- self.class::NSPOOL.collect do |prefix, uri|
- prefix = ":#{prefix}" unless prefix.empty?
- decls["xmlns#{prefix}"] = uri
- end
- decls
- end
-
- def maker_target(target)
- target
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rss/slash.rb b/ruby_1_9_3/lib/rss/slash.rb
deleted file mode 100644
index f102413b46..0000000000
--- a/ruby_1_9_3/lib/rss/slash.rb
+++ /dev/null
@@ -1,49 +0,0 @@
-require 'rss/1.0'
-
-module RSS
- SLASH_PREFIX = 'slash'
- SLASH_URI = "http://purl.org/rss/1.0/modules/slash/"
-
- RDF.install_ns(SLASH_PREFIX, SLASH_URI)
-
- module SlashModel
- extend BaseModel
-
- ELEMENT_INFOS = \
- [
- ["section"],
- ["department"],
- ["comments", :positive_integer],
- ["hit_parade", :csv_integer],
- ]
-
- class << self
- def append_features(klass)
- super
-
- return if klass.instance_of?(Module)
- klass.install_must_call_validator(SLASH_PREFIX, SLASH_URI)
- ELEMENT_INFOS.each do |name, type, *additional_infos|
- full_name = "#{SLASH_PREFIX}_#{name}"
- klass.install_text_element(full_name, SLASH_URI, "?",
- full_name, type, name)
- end
-
- klass.module_eval do
- alias_method(:slash_hit_parades, :slash_hit_parade)
- undef_method(:slash_hit_parade)
- alias_method(:slash_hit_parade, :slash_hit_parade_content)
- end
- end
- end
- end
-
- class RDF
- class Item; include SlashModel; end
- end
-
- SlashModel::ELEMENT_INFOS.each do |name, type|
- accessor_base = "#{SLASH_PREFIX}_#{name}"
- BaseListener.install_get_text_element(SLASH_URI, name, accessor_base)
- end
-end
diff --git a/ruby_1_9_3/lib/rss/syndication.rb b/ruby_1_9_3/lib/rss/syndication.rb
deleted file mode 100644
index c375645dd6..0000000000
--- a/ruby_1_9_3/lib/rss/syndication.rb
+++ /dev/null
@@ -1,67 +0,0 @@
-require "rss/1.0"
-
-module RSS
-
- SY_PREFIX = 'sy'
- SY_URI = "http://purl.org/rss/1.0/modules/syndication/"
-
- RDF.install_ns(SY_PREFIX, SY_URI)
-
- module SyndicationModel
-
- extend BaseModel
-
- ELEMENTS = []
-
- def self.append_features(klass)
- super
-
- klass.install_must_call_validator(SY_PREFIX, SY_URI)
- klass.module_eval do
- [
- ["updatePeriod"],
- ["updateFrequency", :positive_integer]
- ].each do |name, type|
- install_text_element(name, SY_URI, "?",
- "#{SY_PREFIX}_#{name}", type,
- "#{SY_PREFIX}:#{name}")
- end
-
- %w(updateBase).each do |name|
- install_date_element(name, SY_URI, "?",
- "#{SY_PREFIX}_#{name}", 'w3cdtf',
- "#{SY_PREFIX}:#{name}")
- end
- end
-
- klass.module_eval(<<-EOC, __FILE__, __LINE__ + 1)
- alias_method(:_sy_updatePeriod=, :sy_updatePeriod=)
- def sy_updatePeriod=(new_value)
- new_value = new_value.strip
- validate_sy_updatePeriod(new_value) if @do_validate
- self._sy_updatePeriod = new_value
- end
- EOC
- end
-
- private
- SY_UPDATEPERIOD_AVAILABLE_VALUES = %w(hourly daily weekly monthly yearly)
- def validate_sy_updatePeriod(value)
- unless SY_UPDATEPERIOD_AVAILABLE_VALUES.include?(value)
- raise NotAvailableValueError.new("updatePeriod", value)
- end
- end
- end
-
- class RDF
- class Channel; include SyndicationModel; end
- end
-
- prefix_size = SY_PREFIX.size + 1
- SyndicationModel::ELEMENTS.uniq!
- SyndicationModel::ELEMENTS.each do |full_name|
- name = full_name[prefix_size..-1]
- BaseListener.install_get_text_element(SY_URI, name, full_name)
- end
-
-end
diff --git a/ruby_1_9_3/lib/rss/taxonomy.rb b/ruby_1_9_3/lib/rss/taxonomy.rb
deleted file mode 100644
index b82e55dacc..0000000000
--- a/ruby_1_9_3/lib/rss/taxonomy.rb
+++ /dev/null
@@ -1,145 +0,0 @@
-require "rss/1.0"
-require "rss/dublincore"
-
-module RSS
-
- TAXO_PREFIX = "taxo"
- TAXO_URI = "http://purl.org/rss/1.0/modules/taxonomy/"
-
- RDF.install_ns(TAXO_PREFIX, TAXO_URI)
-
- TAXO_ELEMENTS = []
-
- %w(link).each do |name|
- full_name = "#{TAXO_PREFIX}_#{name}"
- BaseListener.install_get_text_element(TAXO_URI, name, full_name)
- TAXO_ELEMENTS << "#{TAXO_PREFIX}_#{name}"
- end
-
- %w(topic topics).each do |name|
- class_name = Utils.to_class_name(name)
- BaseListener.install_class_name(TAXO_URI, name, "Taxonomy#{class_name}")
- TAXO_ELEMENTS << "#{TAXO_PREFIX}_#{name}"
- end
-
- module TaxonomyTopicsModel
- extend BaseModel
-
- def self.append_features(klass)
- super
-
- klass.install_must_call_validator(TAXO_PREFIX, TAXO_URI)
- %w(topics).each do |name|
- klass.install_have_child_element(name, TAXO_URI, "?",
- "#{TAXO_PREFIX}_#{name}")
- end
- end
-
- class TaxonomyTopics < Element
- include RSS10
-
- Bag = ::RSS::RDF::Bag
-
- class << self
- def required_prefix
- TAXO_PREFIX
- end
-
- def required_uri
- TAXO_URI
- end
- end
-
- @tag_name = "topics"
-
- install_have_child_element("Bag", RDF::URI, nil)
- install_must_call_validator('rdf', RDF::URI)
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.Bag = args[0]
- end
- self.Bag ||= Bag.new
- end
-
- def full_name
- tag_name_with_prefix(TAXO_PREFIX)
- end
-
- def maker_target(target)
- target.taxo_topics
- end
-
- def resources
- if @Bag
- @Bag.lis.collect do |li|
- li.resource
- end
- else
- []
- end
- end
- end
- end
-
- module TaxonomyTopicModel
- extend BaseModel
-
- def self.append_features(klass)
- super
- var_name = "#{TAXO_PREFIX}_topic"
- klass.install_have_children_element("topic", TAXO_URI, "*", var_name)
- end
-
- class TaxonomyTopic < Element
- include RSS10
-
- include DublinCoreModel
- include TaxonomyTopicsModel
-
- class << self
- def required_prefix
- TAXO_PREFIX
- end
-
- def required_uri
- TAXO_URI
- end
- end
-
- @tag_name = "topic"
-
- install_get_attribute("about", ::RSS::RDF::URI, true, nil, nil,
- "#{RDF::PREFIX}:about")
- install_text_element("link", TAXO_URI, "?", "#{TAXO_PREFIX}_link")
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.about = args[0]
- end
- end
-
- def full_name
- tag_name_with_prefix(TAXO_PREFIX)
- end
-
- def maker_target(target)
- target.new_taxo_topic
- end
- end
- end
-
- class RDF
- include TaxonomyTopicModel
- class Channel
- include TaxonomyTopicsModel
- end
- class Item; include TaxonomyTopicsModel; end
- end
-end
diff --git a/ruby_1_9_3/lib/rss/trackback.rb b/ruby_1_9_3/lib/rss/trackback.rb
deleted file mode 100644
index 59fedb5f3e..0000000000
--- a/ruby_1_9_3/lib/rss/trackback.rb
+++ /dev/null
@@ -1,288 +0,0 @@
-require 'rss/1.0'
-require 'rss/2.0'
-
-module RSS
-
- TRACKBACK_PREFIX = 'trackback'
- TRACKBACK_URI = 'http://madskills.com/public/xml/rss/module/trackback/'
-
- RDF.install_ns(TRACKBACK_PREFIX, TRACKBACK_URI)
- Rss.install_ns(TRACKBACK_PREFIX, TRACKBACK_URI)
-
- module TrackBackUtils
- private
- def trackback_validate(ignore_unknown_element, tags, uri)
- return if tags.nil?
- if tags.find {|tag| tag == "about"} and
- !tags.find {|tag| tag == "ping"}
- raise MissingTagError.new("#{TRACKBACK_PREFIX}:ping", tag_name)
- end
- end
- end
-
- module BaseTrackBackModel
-
- ELEMENTS = %w(ping about)
-
- def append_features(klass)
- super
-
- unless klass.class == Module
- klass.module_eval {include TrackBackUtils}
-
- klass.install_must_call_validator(TRACKBACK_PREFIX, TRACKBACK_URI)
- %w(ping).each do |name|
- var_name = "#{TRACKBACK_PREFIX}_#{name}"
- klass_name = "TrackBack#{Utils.to_class_name(name)}"
- klass.install_have_child_element(name, TRACKBACK_URI, "?", var_name)
- klass.module_eval(<<-EOC, __FILE__, __LINE__)
- remove_method :#{var_name}
- def #{var_name}
- @#{var_name} and @#{var_name}.value
- end
-
- remove_method :#{var_name}=
- def #{var_name}=(value)
- @#{var_name} = Utils.new_with_value_if_need(#{klass_name}, value)
- end
- EOC
- end
-
- [%w(about s)].each do |name, postfix|
- var_name = "#{TRACKBACK_PREFIX}_#{name}"
- klass_name = "TrackBack#{Utils.to_class_name(name)}"
- klass.install_have_children_element(name, TRACKBACK_URI, "*",
- var_name)
- klass.module_eval(<<-EOC, __FILE__, __LINE__)
- remove_method :#{var_name}
- def #{var_name}(*args)
- if args.empty?
- @#{var_name}.first and @#{var_name}.first.value
- else
- ret = @#{var_name}.__send__("[]", *args)
- if ret.is_a?(Array)
- ret.collect {|x| x.value}
- else
- ret.value
- end
- end
- end
-
- remove_method :#{var_name}=
- remove_method :set_#{var_name}
- def #{var_name}=(*args)
- if args.size == 1
- item = Utils.new_with_value_if_need(#{klass_name}, args[0])
- @#{var_name}.push(item)
- else
- new_val = args.last
- if new_val.is_a?(Array)
- new_val = new_value.collect do |val|
- Utils.new_with_value_if_need(#{klass_name}, val)
- end
- else
- new_val = Utils.new_with_value_if_need(#{klass_name}, new_val)
- end
- @#{var_name}.__send__("[]=", *(args[0..-2] + [new_val]))
- end
- end
- alias set_#{var_name} #{var_name}=
- EOC
- end
- end
- end
- end
-
- module TrackBackModel10
- extend BaseModel
- extend BaseTrackBackModel
-
- class TrackBackPing < Element
- include RSS10
-
- class << self
-
- def required_prefix
- TRACKBACK_PREFIX
- end
-
- def required_uri
- TRACKBACK_URI
- end
-
- end
-
- @tag_name = "ping"
-
- [
- ["resource", ::RSS::RDF::URI, true]
- ].each do |name, uri, required|
- install_get_attribute(name, uri, required, nil, nil,
- "#{::RSS::RDF::PREFIX}:#{name}")
- end
-
- alias_method(:value, :resource)
- alias_method(:value=, :resource=)
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.resource = args[0]
- end
- end
-
- def full_name
- tag_name_with_prefix(TRACKBACK_PREFIX)
- end
- end
-
- class TrackBackAbout < Element
- include RSS10
-
- class << self
-
- def required_prefix
- TRACKBACK_PREFIX
- end
-
- def required_uri
- TRACKBACK_URI
- end
-
- end
-
- @tag_name = "about"
-
- [
- ["resource", ::RSS::RDF::URI, true]
- ].each do |name, uri, required|
- install_get_attribute(name, uri, required, nil, nil,
- "#{::RSS::RDF::PREFIX}:#{name}")
- end
-
- alias_method(:value, :resource)
- alias_method(:value=, :resource=)
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.resource = args[0]
- end
- end
-
- def full_name
- tag_name_with_prefix(TRACKBACK_PREFIX)
- end
-
- private
- def maker_target(abouts)
- abouts.new_about
- end
-
- def setup_maker_attributes(about)
- about.resource = self.resource
- end
-
- end
- end
-
- module TrackBackModel20
- extend BaseModel
- extend BaseTrackBackModel
-
- class TrackBackPing < Element
- include RSS09
-
- @tag_name = "ping"
-
- content_setup
-
- class << self
-
- def required_prefix
- TRACKBACK_PREFIX
- end
-
- def required_uri
- TRACKBACK_URI
- end
-
- end
-
- alias_method(:value, :content)
- alias_method(:value=, :content=)
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.content = args[0]
- end
- end
-
- def full_name
- tag_name_with_prefix(TRACKBACK_PREFIX)
- end
-
- end
-
- class TrackBackAbout < Element
- include RSS09
-
- @tag_name = "about"
-
- content_setup
-
- class << self
-
- def required_prefix
- TRACKBACK_PREFIX
- end
-
- def required_uri
- TRACKBACK_URI
- end
-
- end
-
- alias_method(:value, :content)
- alias_method(:value=, :content=)
-
- def initialize(*args)
- if Utils.element_initialize_arguments?(args)
- super
- else
- super()
- self.content = args[0]
- end
- end
-
- def full_name
- tag_name_with_prefix(TRACKBACK_PREFIX)
- end
-
- end
- end
-
- class RDF
- class Item; include TrackBackModel10; end
- end
-
- class Rss
- class Channel
- class Item; include TrackBackModel20; end
- end
- end
-
- BaseTrackBackModel::ELEMENTS.each do |name|
- class_name = Utils.to_class_name(name)
- BaseListener.install_class_name(TRACKBACK_URI, name,
- "TrackBack#{class_name}")
- end
-
- BaseTrackBackModel::ELEMENTS.collect! {|name| "#{TRACKBACK_PREFIX}_#{name}"}
-end
diff --git a/ruby_1_9_3/lib/rss/utils.rb b/ruby_1_9_3/lib/rss/utils.rb
deleted file mode 100644
index 75b05d45c7..0000000000
--- a/ruby_1_9_3/lib/rss/utils.rb
+++ /dev/null
@@ -1,111 +0,0 @@
-module RSS
- module Utils
- module_function
-
- # Convert a name_with_underscores to CamelCase.
- def to_class_name(name)
- name.split(/[_\-]/).collect do |part|
- "#{part[0, 1].upcase}#{part[1..-1]}"
- end.join("")
- end
-
- def get_file_and_line_from_caller(i=0)
- file, line, = caller[i].split(':')
- line = line.to_i
- line += 1 if i.zero?
- [file, line]
- end
-
- # escape '&', '"', '<' and '>' for use in HTML.
- def html_escape(s)
- s.to_s.gsub(/&/, "&amp;").gsub(/\"/, "&quot;").gsub(/>/, "&gt;").gsub(/</, "&lt;")
- end
- alias h html_escape
-
- # If +value+ is an instance of class +klass+, return it, else
- # create a new instance of +klass+ with value +value+.
- def new_with_value_if_need(klass, value)
- if value.is_a?(klass)
- value
- else
- klass.new(value)
- end
- end
-
- def element_initialize_arguments?(args)
- [true, false].include?(args[0]) and args[1].is_a?(Hash)
- end
-
- module YesCleanOther
- module_function
- def parse(value)
- if [true, false, nil].include?(value)
- value
- else
- case value.to_s
- when /\Ayes\z/i
- true
- when /\Aclean\z/i
- false
- else
- nil
- end
- end
- end
- end
-
- module YesOther
- module_function
- def parse(value)
- if [true, false].include?(value)
- value
- else
- /\Ayes\z/i.match(value.to_s) ? true : false
- end
- end
- end
-
- module CSV
- module_function
- def parse(value, &block)
- if value.is_a?(String)
- value = value.strip.split(/\s*,\s*/)
- value = value.collect(&block) if block_given?
- value
- else
- value
- end
- end
- end
-
- module InheritedReader
- def inherited_reader(constant_name)
- base_class = inherited_base
- result = base_class.const_get(constant_name)
- found_base_class = false
- ancestors.reverse_each do |klass|
- if found_base_class
- if klass.const_defined?(constant_name)
- result = yield(result, klass.const_get(constant_name))
- end
- else
- found_base_class = klass == base_class
- end
- end
- result
- end
-
- def inherited_array_reader(constant_name)
- inherited_reader(constant_name) do |result, current|
- current + result
- end
- end
-
- def inherited_hash_reader(constant_name)
- inherited_reader(constant_name) do |result, current|
- result.merge(current)
- end
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rss/xml-stylesheet.rb b/ruby_1_9_3/lib/rss/xml-stylesheet.rb
deleted file mode 100644
index 96ee95050e..0000000000
--- a/ruby_1_9_3/lib/rss/xml-stylesheet.rb
+++ /dev/null
@@ -1,105 +0,0 @@
-require "rss/utils"
-
-module RSS
-
- module XMLStyleSheetMixin
- attr_accessor :xml_stylesheets
- def initialize(*args)
- super
- @xml_stylesheets = []
- end
-
- private
- def xml_stylesheet_pi
- xsss = @xml_stylesheets.collect do |xss|
- pi = xss.to_s
- pi = nil if /\A\s*\z/ =~ pi
- pi
- end.compact
- xsss.push("") unless xsss.empty?
- xsss.join("\n")
- end
- end
-
- class XMLStyleSheet
-
- include Utils
-
- ATTRIBUTES = %w(href type title media charset alternate)
-
- GUESS_TABLE = {
- "xsl" => "text/xsl",
- "css" => "text/css",
- }
-
- attr_accessor(*ATTRIBUTES)
- attr_accessor(:do_validate)
- def initialize(*attrs)
- if attrs.size == 1 and
- (attrs.first.is_a?(Hash) or attrs.first.is_a?(Array))
- attrs = attrs.first
- end
- @do_validate = true
- ATTRIBUTES.each do |attr|
- __send__("#{attr}=", nil)
- end
- vars = ATTRIBUTES.dup
- vars.unshift(:do_validate)
- attrs.each do |name, value|
- if vars.include?(name.to_s)
- __send__("#{name}=", value)
- end
- end
- end
-
- def to_s
- rv = ""
- if @href
- rv << %Q[<?xml-stylesheet]
- ATTRIBUTES.each do |name|
- if __send__(name)
- rv << %Q[ #{name}="#{h __send__(name)}"]
- end
- end
- rv << %Q[?>]
- end
- rv
- end
-
- remove_method(:href=)
- def href=(value)
- @href = value
- if @href and @type.nil?
- @type = guess_type(@href)
- end
- @href
- end
-
- remove_method(:alternate=)
- def alternate=(value)
- if value.nil? or /\A(?:yes|no)\z/ =~ value
- @alternate = value
- else
- if @do_validate
- args = ["?xml-stylesheet?", %Q[alternate="#{value}"]]
- raise NotAvailableValueError.new(*args)
- end
- end
- @alternate
- end
-
- def setup_maker(maker)
- xss = maker.xml_stylesheets.new_xml_stylesheet
- ATTRIBUTES.each do |attr|
- xss.__send__("#{attr}=", __send__(attr))
- end
- end
-
- private
- def guess_type(filename)
- /\.([^.]+)$/ =~ filename
- GUESS_TABLE[$1]
- end
-
- end
-end
diff --git a/ruby_1_9_3/lib/rss/xml.rb b/ruby_1_9_3/lib/rss/xml.rb
deleted file mode 100644
index 1ae878b772..0000000000
--- a/ruby_1_9_3/lib/rss/xml.rb
+++ /dev/null
@@ -1,71 +0,0 @@
-require "rss/utils"
-
-module RSS
- module XML
- class Element
- include Enumerable
-
- attr_reader :name, :prefix, :uri, :attributes, :children
- def initialize(name, prefix=nil, uri=nil, attributes={}, children=[])
- @name = name
- @prefix = prefix
- @uri = uri
- @attributes = attributes
- if children.is_a?(String) or !children.respond_to?(:each)
- @children = [children]
- else
- @children = children
- end
- end
-
- def [](name)
- @attributes[name]
- end
-
- def []=(name, value)
- @attributes[name] = value
- end
-
- def <<(child)
- @children << child
- end
-
- def each(&block)
- @children.each(&block)
- end
-
- def ==(other)
- other.kind_of?(self.class) and
- @name == other.name and
- @uri == other.uri and
- @attributes == other.attributes and
- @children == other.children
- end
-
- def to_s
- rv = "<#{full_name}"
- attributes.each do |key, value|
- rv << " #{Utils.html_escape(key)}=\"#{Utils.html_escape(value)}\""
- end
- if children.empty?
- rv << "/>"
- else
- rv << ">"
- children.each do |child|
- rv << child.to_s
- end
- rv << "</#{full_name}>"
- end
- rv
- end
-
- def full_name
- if @prefix
- "#{@prefix}:#{@name}"
- else
- @name
- end
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rss/xmlparser.rb b/ruby_1_9_3/lib/rss/xmlparser.rb
deleted file mode 100644
index aa902be396..0000000000
--- a/ruby_1_9_3/lib/rss/xmlparser.rb
+++ /dev/null
@@ -1,93 +0,0 @@
-begin
- require "xml/parser"
-rescue LoadError
- require "xmlparser"
-end
-
-begin
- require "xml/encoding-ja"
-rescue LoadError
- require "xmlencoding-ja"
- if defined?(Kconv)
- module XMLEncoding_ja
- class SJISHandler
- include Kconv
- end
- end
- end
-end
-
-module XML
- class Parser
- unless defined?(Error)
- Error = ::XMLParserError
- end
- end
-end
-
-module RSS
-
- class REXMLLikeXMLParser < ::XML::Parser
-
- include ::XML::Encoding_ja
-
- def listener=(listener)
- @listener = listener
- end
-
- def startElement(name, attrs)
- @listener.tag_start(name, attrs)
- end
-
- def endElement(name)
- @listener.tag_end(name)
- end
-
- def character(data)
- @listener.text(data)
- end
-
- def xmlDecl(version, encoding, standalone)
- @listener.xmldecl(version, encoding, standalone == 1)
- end
-
- def processingInstruction(target, content)
- @listener.instruction(target, content)
- end
-
- end
-
- class XMLParserParser < BaseParser
-
- class << self
- def listener
- XMLParserListener
- end
- end
-
- private
- def _parse
- begin
- parser = REXMLLikeXMLParser.new
- parser.listener = @listener
- parser.parse(@rss)
- rescue ::XML::Parser::Error => e
- raise NotWellFormedError.new(parser.line){e.message}
- end
- end
-
- end
-
- class XMLParserListener < BaseListener
-
- include ListenerMixin
-
- def xmldecl(version, encoding, standalone)
- super
- # Encoding is converted to UTF-8 when XMLParser parses XML.
- @encoding = 'UTF-8'
- end
-
- end
-
-end
diff --git a/ruby_1_9_3/lib/rss/xmlscanner.rb b/ruby_1_9_3/lib/rss/xmlscanner.rb
deleted file mode 100644
index 1cdf81c0c3..0000000000
--- a/ruby_1_9_3/lib/rss/xmlscanner.rb
+++ /dev/null
@@ -1,121 +0,0 @@
-require 'xmlscan/scanner'
-require 'stringio'
-
-module RSS
-
- class XMLScanParser < BaseParser
-
- class << self
- def listener
- XMLScanListener
- end
- end
-
- private
- def _parse
- begin
- if @rss.is_a?(String)
- input = StringIO.new(@rss)
- else
- input = @rss
- end
- scanner = XMLScan::XMLScanner.new(@listener)
- scanner.parse(input)
- rescue XMLScan::Error => e
- lineno = e.lineno || scanner.lineno || input.lineno
- raise NotWellFormedError.new(lineno){e.message}
- end
- end
-
- end
-
- class XMLScanListener < BaseListener
-
- include XMLScan::Visitor
- include ListenerMixin
-
- ENTITIES = {
- 'lt' => '<',
- 'gt' => '>',
- 'amp' => '&',
- 'quot' => '"',
- 'apos' => '\''
- }
-
- def on_xmldecl_version(str)
- @version = str
- end
-
- def on_xmldecl_encoding(str)
- @encoding = str
- end
-
- def on_xmldecl_standalone(str)
- @standalone = str
- end
-
- def on_xmldecl_end
- xmldecl(@version, @encoding, @standalone == "yes")
- end
-
- alias_method(:on_pi, :instruction)
- alias_method(:on_chardata, :text)
- alias_method(:on_cdata, :text)
-
- def on_etag(name)
- tag_end(name)
- end
-
- def on_entityref(ref)
- text(entity(ref))
- end
-
- def on_charref(code)
- text([code].pack('U'))
- end
-
- alias_method(:on_charref_hex, :on_charref)
-
- def on_stag(name)
- @attrs = {}
- end
-
- def on_attribute(name)
- @attrs[name] = @current_attr = ''
- end
-
- def on_attr_value(str)
- @current_attr << str
- end
-
- def on_attr_entityref(ref)
- @current_attr << entity(ref)
- end
-
- def on_attr_charref(code)
- @current_attr << [code].pack('U')
- end
-
- alias_method(:on_attr_charref_hex, :on_attr_charref)
-
- def on_stag_end(name)
- tag_start(name, @attrs)
- end
-
- def on_stag_end_empty(name)
- tag_start(name, @attrs)
- tag_end(name)
- end
-
- private
- def entity(ref)
- ent = ENTITIES[ref]
- if ent
- ent
- else
- wellformed_error("undefined entity: #{ref}")
- end
- end
- end
-
-end
diff --git a/ruby_1_9_3/lib/rubygems.rb b/ruby_1_9_3/lib/rubygems.rb
deleted file mode 100644
index 7ed27461bb..0000000000
--- a/ruby_1_9_3/lib/rubygems.rb
+++ /dev/null
@@ -1,1305 +0,0 @@
-# -*- ruby -*-
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-module Gem
- QUICKLOADER_SUCKAGE = RUBY_VERSION =~ /^1\.9\.1/
-
- # Only MRI 1.9.2 has the custom prelude.
- GEM_PRELUDE_SUCKAGE = RUBY_VERSION =~ /^1\.9\.2/ && RUBY_ENGINE == "ruby"
-end
-
-if Gem::GEM_PRELUDE_SUCKAGE and defined?(Gem::QuickLoader) then
- Gem::QuickLoader.remove
-
- $LOADED_FEATURES.delete Gem::QuickLoader.path_to_full_rubygems_library
-
- if $LOADED_FEATURES.any? do |path| path.end_with? '/rubygems.rb' end then
- # TODO path does not exist here
- raise LoadError, "another rubygems is already loaded from #{path}"
- end
-
- class << Gem
- remove_method :try_activate if Gem.respond_to?(:try_activate, true)
- end
-end
-
-require 'rubygems/defaults'
-require 'rbconfig'
-require "rubygems/deprecate"
-
-##
-# RubyGems is the Ruby standard for publishing and managing third party
-# libraries.
-#
-# For user documentation, see:
-#
-# * <tt>gem help</tt> and <tt>gem help [command]</tt>
-# * {RubyGems User Guide}[http://docs.rubygems.org/read/book/1]
-# * {Frequently Asked Questions}[http://docs.rubygems.org/read/book/3]
-#
-# For gem developer documentation see:
-#
-# * {Creating Gems}[http://docs.rubygems.org/read/chapter/5]
-# * Gem::Specification
-# * Gem::Version for version dependency notes
-#
-# Further RubyGems documentation can be found at:
-#
-# * {RubyGems API}[http://rubygems.rubyforge.org/rdoc] (also available from
-# <tt>gem server</tt>)
-# * {RubyGems Bookshelf}[http://rubygem.org]
-#
-# == RubyGems Plugins
-#
-# As of RubyGems 1.3.2, RubyGems will load plugins installed in gems or
-# $LOAD_PATH. Plugins must be named 'rubygems_plugin' (.rb, .so, etc) and
-# placed at the root of your gem's #require_path. Plugins are discovered via
-# Gem::find_files then loaded. Take care when implementing a plugin as your
-# plugin file may be loaded multiple times if multiple versions of your gem
-# are installed.
-#
-# For an example plugin, see the graph gem which adds a `gem graph` command.
-#
-# == RubyGems Defaults, Packaging
-#
-# RubyGems defaults are stored in rubygems/defaults.rb. If you're packaging
-# RubyGems or implementing Ruby you can change RubyGems' defaults.
-#
-# For RubyGems packagers, provide lib/rubygems/operating_system.rb and
-# override any defaults from lib/rubygems/defaults.rb.
-#
-# For Ruby implementers, provide lib/rubygems/#{RUBY_ENGINE}.rb and override
-# any defaults from lib/rubygems/defaults.rb.
-#
-# If you need RubyGems to perform extra work on install or uninstall, your
-# defaults override file can set pre and post install and uninstall hooks.
-# See Gem::pre_install, Gem::pre_uninstall, Gem::post_install,
-# Gem::post_uninstall.
-#
-# == Bugs
-#
-# You can submit bugs to the
-# {RubyGems bug tracker}[http://rubyforge.org/tracker/?atid=575&group_id=126]
-# on RubyForge
-#
-# == Credits
-#
-# RubyGems is currently maintained by Eric Hodel.
-#
-# RubyGems was originally developed at RubyConf 2003 by:
-#
-# * Rich Kilmer -- rich(at)infoether.com
-# * Chad Fowler -- chad(at)chadfowler.com
-# * David Black -- dblack(at)wobblini.net
-# * Paul Brannan -- paul(at)atdesk.com
-# * Jim Weirch -- jim(at)weirichhouse.org
-#
-# Contributors:
-#
-# * Gavin Sinclair -- gsinclair(at)soyabean.com.au
-# * George Marrows -- george.marrows(at)ntlworld.com
-# * Dick Davies -- rasputnik(at)hellooperator.net
-# * Mauricio Fernandez -- batsman.geo(at)yahoo.com
-# * Simon Strandgaard -- neoneye(at)adslhome.dk
-# * Dave Glasser -- glasser(at)mit.edu
-# * Paul Duncan -- pabs(at)pablotron.org
-# * Ville Aine -- vaine(at)cs.helsinki.fi
-# * Eric Hodel -- drbrain(at)segment7.net
-# * Daniel Berger -- djberg96(at)gmail.com
-# * Phil Hagelberg -- technomancy(at)gmail.com
-# * Ryan Davis -- ryand-ruby(at)zenspider.com
-# * Evan Phoenix -- evan@phx.io
-#
-# (If your name is missing, PLEASE let us know!)
-#
-# Thanks!
-#
-# -The RubyGems Team
-
-module Gem
- VERSION = '1.8.23'
-
- ##
- # Raised when RubyGems is unable to load or activate a gem. Contains the
- # name and version requirements of the gem that either conflicts with
- # already activated gems or that RubyGems is otherwise unable to activate.
-
- class LoadError < ::LoadError
- # Name of gem
- attr_accessor :name
-
- # Version requirement of gem
- attr_accessor :requirement
- end
-
- # :stopdoc:
-
- RubyGemsVersion = VERSION
-
- RbConfigPriorities = %w[
- EXEEXT RUBY_SO_NAME arch bindir datadir libdir ruby_install_name
- ruby_version rubylibprefix sitedir sitelibdir vendordir vendorlibdir
- ]
-
- unless defined?(ConfigMap)
- ##
- # Configuration settings from ::RbConfig
- ConfigMap = Hash.new do |cm, key|
- cm[key] = RbConfig::CONFIG[key.to_s]
- end
- else
- RbConfigPriorities.each do |key|
- ConfigMap[key.to_sym] = RbConfig::CONFIG[key]
- end
- end
-
- RubyGemsPackageVersion = VERSION
-
- RUBYGEMS_DIR = File.dirname File.expand_path(__FILE__)
-
- # :startdoc:
-
- ##
- # An Array of Regexps that match windows ruby platforms.
-
- WIN_PATTERNS = [
- /bccwin/i,
- /cygwin/i,
- /djgpp/i,
- /mingw/i,
- /mswin/i,
- /wince/i,
- ]
-
- @@source_index = nil
- @@win_platform = nil
-
- @configuration = nil
- @loaded_specs = {}
- @platforms = []
- @ruby = nil
- @sources = nil
-
- @post_build_hooks ||= []
- @post_install_hooks ||= []
- @post_uninstall_hooks ||= []
- @pre_uninstall_hooks ||= []
- @pre_install_hooks ||= []
- @pre_reset_hooks ||= []
- @post_reset_hooks ||= []
-
- ##
- # Try to activate a gem containing +path+. Returns true if
- # activation succeeded or wasn't needed because it was already
- # activated. Returns false if it can't find the path in a gem.
-
- def self.try_activate path
- # TODO: deprecate when 1.9.3 comes out.
- # finds the _latest_ version... regardless of loaded specs and their deps
-
- # TODO: use find_all and bork if ambiguous
-
- spec = Gem::Specification.find_by_path path
- return false unless spec
-
- begin
- spec.activate
- rescue Gem::LoadError # this could fail due to gem dep collisions, go lax
- Gem::Specification.find_by_name(spec.name).activate
- end
-
- return true
- end
-
- ##
- # Activates an installed gem matching +dep+. The gem must satisfy
- # +requirements+.
- #
- # Returns true if the gem is activated, false if it is already
- # loaded, or an exception otherwise.
- #
- # Gem#activate adds the library paths in +dep+ to $LOAD_PATH. Before a Gem
- # is activated its required Gems are activated. If the version information
- # is omitted, the highest version Gem of the supplied name is loaded. If a
- # Gem is not found that meets the version requirements or a required Gem is
- # not found, a Gem::LoadError is raised.
- #
- # More information on version requirements can be found in the
- # Gem::Requirement and Gem::Version documentation.
-
- def self.activate(dep, *requirements)
- raise ArgumentError, "Deprecated use of Gem.activate(dep)" if
- Gem::Dependency === dep
-
- Gem::Specification.find_by_name(dep, *requirements).activate
- end
-
- def self.activate_dep dep, *requirements # :nodoc:
- dep.to_spec.activate
- end
-
- def self.activate_spec spec # :nodoc:
- spec.activate
- end
-
- def self.unresolved_deps
- @unresolved_deps ||= Hash.new { |h, n| h[n] = Gem::Dependency.new n }
- end
-
- ##
- # An Array of all possible load paths for all versions of all gems in the
- # Gem installation.
-
- def self.all_load_paths
- result = []
-
- Gem.path.each do |gemdir|
- each_load_path all_partials(gemdir) do |load_path|
- result << load_path
- end
- end
-
- result
- end
-
- ##
- # Return all the partial paths in +gemdir+.
-
- def self.all_partials(gemdir)
- Dir[File.join(gemdir, "gems/*")]
- end
-
- private_class_method :all_partials
-
- ##
- # See if a given gem is available.
-
- def self.available?(dep, *requirements)
- requirements = Gem::Requirement.default if requirements.empty?
-
- unless dep.respond_to?(:name) and dep.respond_to?(:requirement) then
- dep = Gem::Dependency.new dep, requirements
- end
-
- not dep.matching_specs(true).empty?
- end
-
- ##
- # Find the full path to the executable for gem +name+. If the +exec_name+
- # is not given, the gem's default_executable is chosen, otherwise the
- # specified executable's path is returned. +requirements+ allows
- # you to specify specific gem versions.
-
- def self.bin_path(name, exec_name = nil, *requirements)
- # TODO: fails test_self_bin_path_bin_file_gone_in_latest
- # Gem::Specification.find_by_name(name, *requirements).bin_file exec_name
-
- raise ArgumentError, "you must supply exec_name" unless exec_name
-
- requirements = Gem::Requirement.default if
- requirements.empty?
-
- specs = Gem::Dependency.new(name, requirements).matching_specs(true)
-
- raise Gem::GemNotFoundException,
- "can't find gem #{name} (#{requirements})" if specs.empty?
-
- specs = specs.find_all { |spec|
- spec.executables.include? exec_name
- } if exec_name
-
- unless spec = specs.last
- msg = "can't find gem #{name} (#{requirements}) with executable #{exec_name}"
- raise Gem::GemNotFoundException, msg
- end
-
- spec.bin_file exec_name
- end
-
- ##
- # The mode needed to read a file as straight binary.
-
- def self.binary_mode
- 'rb'
- end
-
- ##
- # The path where gem executables are to be installed.
-
- def self.bindir(install_dir=Gem.dir)
- # TODO: move to Gem::Dirs
- return File.join install_dir, 'bin' unless
- install_dir.to_s == Gem.default_dir.to_s
- Gem.default_bindir
- end
-
- ##
- # Reset the +dir+ and +path+ values. The next time +dir+ or +path+
- # is requested, the values will be calculated from scratch. This is
- # mainly used by the unit tests to provide test isolation.
-
- def self.clear_paths
- @@source_index = nil
- @paths = nil
- @user_home = nil
- @searcher = nil
- Gem::Specification.reset
- end
-
- ##
- # The path to standard location of the user's .gemrc file.
-
- def self.config_file
- @config_file ||= File.join Gem.user_home, '.gemrc'
- end
-
- ##
- # The standard configuration object for gems.
-
- def self.configuration
- @configuration ||= Gem::ConfigFile.new []
- end
-
- ##
- # Use the given configuration object (which implements the ConfigFile
- # protocol) as the standard configuration object.
-
- def self.configuration=(config)
- @configuration = config
- end
-
- ##
- # The path the the data directory specified by the gem name. If the
- # package is not available as a gem, return nil.
-
- def self.datadir(gem_name)
-# TODO: deprecate
- spec = @loaded_specs[gem_name]
- return nil if spec.nil?
- File.join spec.full_gem_path, "data", gem_name
- end
-
- ##
- # A Zlib::Deflate.deflate wrapper
-
- def self.deflate(data)
- require 'zlib'
- Zlib::Deflate.deflate data
- end
-
- def self.paths
- @paths ||= Gem::PathSupport.new
- end
-
- def self.paths=(env)
- clear_paths
- @paths = Gem::PathSupport.new env
- Gem::Specification.dirs = @paths.path # FIX: home is at end
- end
-
- ##
- # The path where gems are to be installed.
- #--
- # FIXME deprecate these once everything else has been done -ebh
-
- def self.dir
- # TODO: raise "no"
- paths.home
- end
-
- def self.path
- # TODO: raise "no"
- paths.path
- end
-
- ##
- # Expand each partial gem path with each of the required paths specified
- # in the Gem spec. Each expanded path is yielded.
-
- def self.each_load_path(partials)
- partials.each do |gp|
- base = File.basename gp
- specfn = File.join(dir, "specifications", "#{base}.gemspec")
- if File.exists? specfn
- spec = eval(File.read(specfn))
- spec.require_paths.each do |rp|
- yield File.join(gp,rp)
- end
- else
- filename = File.join(gp, 'lib')
- yield(filename) if File.exists? filename
- end
- end
- end
-
- private_class_method :each_load_path
-
-
- ##
- # Quietly ensure the named Gem directory contains all the proper
- # subdirectories. If we can't create a directory due to a permission
- # problem, then we will silently continue.
-
- def self.ensure_gem_subdirectories dir = Gem.dir
- old_umask = File.umask
- File.umask old_umask | 002
-
- require 'fileutils'
-
- %w[cache doc gems specifications].each do |name|
- subdir = File.join dir, name
- next if File.exist? subdir
- FileUtils.mkdir_p subdir rescue nil # in case of perms issues -- lame
- end
- ensure
- File.umask old_umask
- end
-
- ##
- # Returns a list of paths matching +glob+ that can be used by a gem to pick
- # up features from other gems. For example:
- #
- # Gem.find_files('rdoc/discover').each do |path| load path end
- #
- # if +check_load_path+ is true (the default), then find_files also searches
- # $LOAD_PATH for files as well as gems.
- #
- # Note that find_files will return all files even if they are from different
- # versions of the same gem.
-
- def self.find_files(glob, check_load_path=true)
- files = []
-
- if check_load_path
- files = $LOAD_PATH.map { |load_path|
- Dir["#{File.expand_path glob, load_path}#{Gem.suffix_pattern}"]
- }.flatten.select { |file| File.file? file.untaint }
- end
-
- files.concat Gem::Specification.map { |spec|
- spec.matches_for_glob("#{glob}#{Gem.suffix_pattern}")
- }.flatten
-
- # $LOAD_PATH might contain duplicate entries or reference
- # the spec dirs directly, so we prune.
- files.uniq! if check_load_path
-
- return files
- end
-
- ##
- # Finds the user's home directory.
- #--
- # Some comments from the ruby-talk list regarding finding the home
- # directory:
- #
- # I have HOME, USERPROFILE and HOMEDRIVE + HOMEPATH. Ruby seems
- # to be depending on HOME in those code samples. I propose that
- # it should fallback to USERPROFILE and HOMEDRIVE + HOMEPATH (at
- # least on Win32).
- #++
- #--
- #
- # FIXME move to pathsupport
- #
- #++
-
- def self.find_home
- windows = File::ALT_SEPARATOR
- if not windows or RUBY_VERSION >= '1.9' then
- File.expand_path "~"
- else
- ['HOME', 'USERPROFILE'].each do |key|
- return File.expand_path ENV[key] if ENV[key]
- end
-
- if ENV['HOMEDRIVE'] && ENV['HOMEPATH'] then
- File.expand_path "#{ENV['HOMEDRIVE']}#{ENV['HOMEPATH']}"
- end
- end
- rescue
- if windows then
- File.expand_path File.join(ENV['HOMEDRIVE'] || ENV['SystemDrive'], '/')
- else
- File.expand_path "/"
- end
- end
-
- private_class_method :find_home
-
- ##
- # Zlib::GzipReader wrapper that unzips +data+.
-
- def self.gunzip(data)
- # TODO: move to utils
- require 'stringio'
- require 'zlib'
- data = StringIO.new data
-
- Zlib::GzipReader.new(data).read
- end
-
- ##
- # Zlib::GzipWriter wrapper that zips +data+.
-
- def self.gzip(data)
- # TODO: move to utils
- require 'stringio'
- require 'zlib'
- zipped = StringIO.new
-
- Zlib::GzipWriter.wrap zipped do |io| io.write data end
-
- zipped.string
- end
-
- ##
- # A Zlib::Inflate#inflate wrapper
-
- def self.inflate(data)
- # TODO: move to utils
- require 'zlib'
- Zlib::Inflate.inflate data
- end
-
- ##
- # Get the default RubyGems API host. This is normally
- # <tt>https://rubygems.org</tt>.
-
- def self.host
- # TODO: move to utils
- @host ||= "https://rubygems.org"
- end
-
- ## Set the default RubyGems API host.
-
- def self.host= host
- # TODO: move to utils
- @host = host
- end
-
- ##
- # Return a list of all possible load paths for the latest version for all
- # gems in the Gem installation.
-
- def self.latest_load_paths
- result = []
-
- Gem.path.each do |gemdir|
- each_load_path(latest_partials(gemdir)) do |load_path|
- result << load_path
- end
- end
-
- result
- end
-
- ##
- # Return only the latest partial paths in the given +gemdir+.
-
- def self.latest_partials(gemdir)
- latest = {}
- all_partials(gemdir).each do |gp|
- base = File.basename gp
-
- if base.to_s =~ /(.*)-((\d+\.)*\d+)/ then
- name, version = $1, $2
- ver = Gem::Version.new(version)
- if latest[name].nil? || ver > latest[name][0]
- latest[name] = [ver, gp]
- end
- end
- end
- latest.collect { |k,v| v[1] }
- end
-
- private_class_method :latest_partials
-
- ##
- # The index to insert activated gem paths into the $LOAD_PATH.
- #
- # Defaults to the site lib directory unless gem_prelude.rb has loaded paths,
- # then it inserts the activated gem's paths before the gem_prelude.rb paths
- # so you can override the gem_prelude.rb default $LOAD_PATH paths.
-
- def self.load_path_insert_index
- index = $LOAD_PATH.index ConfigMap[:sitelibdir]
-
- if QUICKLOADER_SUCKAGE then
- $LOAD_PATH.each_with_index do |path, i|
- if path.instance_variables.include?(:@gem_prelude_index) or
- path.instance_variables.include?('@gem_prelude_index') then
- index = i
- break
- end
- end
- end
-
- index
- end
-
- @yaml_loaded = false
-
- ##
- # Loads YAML, preferring Psych
-
- def self.load_yaml
- return if @yaml_loaded
-
- test_syck = ENV['TEST_SYCK']
-
- unless test_syck
- begin
- gem 'psych', '~> 1.2', '>= 1.2.1'
- rescue Gem::LoadError
- # It's OK if the user does not have the psych gem installed. We will
- # attempt to require the stdlib version
- end
-
- begin
- # Try requiring the gem version *or* stdlib version of psych.
- require 'psych'
- rescue ::LoadError
- # If we can't load psych, thats fine, go on.
- else
- # If 'yaml' has already been required, then we have to
- # be sure to switch it over to the newly loaded psych.
- if defined?(YAML::ENGINE) && YAML::ENGINE.yamler != "psych"
- YAML::ENGINE.yamler = "psych"
- end
-
- require 'rubygems/psych_additions'
- require 'rubygems/psych_tree'
- end
- end
-
- require 'yaml'
-
- # If we're supposed to be using syck, then we may have to force
- # activate it via the YAML::ENGINE API.
- if test_syck and defined?(YAML::ENGINE)
- YAML::ENGINE.yamler = "syck" unless YAML::ENGINE.syck?
- end
-
- # Now that we're sure some kind of yaml library is loaded, pull
- # in our hack to deal with Syck's DefaultKey ugliness.
- require 'rubygems/syck_hack'
-
- @yaml_loaded = true
- end
-
- ##
- # The file name and line number of the caller of the caller of this method.
-
- def self.location_of_caller
- caller[1] =~ /(.*?):(\d+).*?$/i
- file = $1
- lineno = $2.to_i
-
- # TODO: it is ALWAYS joined! STUPID!
- [file, lineno]
- end
-
- ##
- # The version of the Marshal format for your Ruby.
-
- def self.marshal_version
- "#{Marshal::MAJOR_VERSION}.#{Marshal::MINOR_VERSION}"
- end
-
- ##
- # Get the appropriate cache path.
- #
- # Pass a string to use a different base path, or nil/false (default) for
- # Gem.dir.
- #
-
- def self.cache_dir(custom_dir=false)
- File.join(custom_dir || Gem.dir, "cache")
- end
-
- ##
- # Given a gem path, find the gem in cache.
- #
- # Pass a string as the second argument to use a different base path, or
- # nil/false (default) for Gem.dir.
-
- def self.cache_gem(filename, user_dir=false)
- cache_dir(user_dir).add(filename)
- end
-
- ##
- # Set array of platforms this RubyGems supports (primarily for testing).
-
- def self.platforms=(platforms)
- @platforms = platforms
- end
-
- ##
- # Array of platforms this RubyGems supports.
-
- def self.platforms
- @platforms ||= []
- if @platforms.empty?
- @platforms = [Gem::Platform::RUBY, Gem::Platform.local]
- end
- @platforms
- end
-
- ##
- # Adds a post-build hook that will be passed an Gem::Installer instance
- # when Gem::Installer#install is called. The hook is called after the gem
- # has been extracted and extensions have been built but before the
- # executables or gemspec has been written. If the hook returns +false+ then
- # the gem's files will be removed and the install will be aborted.
-
- def self.post_build(&hook)
- @post_build_hooks << hook
- end
-
- ##
- # Adds a post-install hook that will be passed an Gem::Installer instance
- # when Gem::Installer#install is called
-
- def self.post_install(&hook)
- @post_install_hooks << hook
- end
-
- ##
- # Adds a hook that will get run after Gem::Specification.reset is
- # run.
-
- def self.post_reset(&hook)
- @post_reset_hooks << hook
- end
-
- ##
- # Adds a post-uninstall hook that will be passed a Gem::Uninstaller instance
- # and the spec that was uninstalled when Gem::Uninstaller#uninstall is
- # called
-
- def self.post_uninstall(&hook)
- @post_uninstall_hooks << hook
- end
-
- ##
- # Adds a pre-install hook that will be passed an Gem::Installer instance
- # when Gem::Installer#install is called. If the hook returns +false+ then
- # the install will be aborted.
-
- def self.pre_install(&hook)
- @pre_install_hooks << hook
- end
-
- ##
- # Adds a hook that will get run before Gem::Specification.reset is
- # run.
-
- def self.pre_reset(&hook)
- @pre_reset_hooks << hook
- end
-
- ##
- # Adds a pre-uninstall hook that will be passed an Gem::Uninstaller instance
- # and the spec that will be uninstalled when Gem::Uninstaller#uninstall is
- # called
-
- def self.pre_uninstall(&hook)
- @pre_uninstall_hooks << hook
- end
-
- ##
- # The directory prefix this RubyGems was installed at. If your
- # prefix is in a standard location (ie, rubygems is installed where
- # you'd expect it to be), then prefix returns nil.
-
- def self.prefix
- prefix = File.dirname RUBYGEMS_DIR
-
- if prefix != File.expand_path(ConfigMap[:sitelibdir]) and
- prefix != File.expand_path(ConfigMap[:libdir]) and
- 'lib' == File.basename(RUBYGEMS_DIR) then
- prefix
- end
- end
-
- ##
- # Promotes the load paths of the +gem_name+ over the load paths of
- # +over_name+. Useful for allowing one gem to override features in another
- # using #find_files.
-
- def self.promote_load_path(gem_name, over_name)
- gem = Gem.loaded_specs[gem_name]
- over = Gem.loaded_specs[over_name]
-
- raise ArgumentError, "gem #{gem_name} is not activated" if gem.nil?
- raise ArgumentError, "gem #{over_name} is not activated" if over.nil?
-
- last_gem_path = Gem::Path.path(gem.full_gem_path).add(gem.require_paths.last)
-
- over_paths = over.require_paths.map do |path|
- Gem::Path.path(over.full_gem_path).add(path).to_s
- end
-
- over_paths.each do |path|
- $LOAD_PATH.delete path
- end
-
- gem = $LOAD_PATH.index(last_gem_path) + 1
-
- $LOAD_PATH.insert(gem, *over_paths)
- end
-
- ##
- # Refresh source_index from disk and clear searcher.
-
- def self.refresh
- Gem::Specification.reset
- @source_index = nil
- @searcher = nil
- end
-
- ##
- # Safely read a file in binary mode on all platforms.
-
- def self.read_binary(path)
- File.open path, binary_mode do |f| f.read end
- end
-
- ##
- # Report a load error during activation. The message of load error
- # depends on whether it was a version mismatch or if there are not gems of
- # any version by the requested name.
-
- def self.report_activate_error(gem)
- matches = Gem::Specification.find_by_name(gem.name)
-
- if matches.empty? then
- error = Gem::LoadError.new(
- "Could not find RubyGem #{gem.name} (#{gem.requirement})\n")
- else
- error = Gem::LoadError.new(
- "RubyGem version error: " +
- "#{gem.name}(#{matches.first.version} not #{gem.requirement})\n")
- end
-
- error.name = gem.name
- error.requirement = gem.requirement
- raise error
- end
-
- private_class_method :report_activate_error
-
- ##
- # Full path to +libfile+ in +gemname+. Searches for the latest gem unless
- # +requirements+ is given.
-
- def self.required_location(gemname, libfile, *requirements)
- requirements = Gem::Requirement.default if requirements.empty?
-
- matches = Gem::Specification.find_all_by_name gemname, *requirements
-
- return nil if matches.empty?
-
- spec = matches.last
- spec.require_paths.each do |path|
- result = Gem::Path.path(spec.full_gem_path).add(path, libfile)
- return result if result.exist?
- end
-
- nil
- end
-
- ##
- # The path to the running Ruby interpreter.
-
- def self.ruby
- if @ruby.nil? then
- @ruby = File.join(ConfigMap[:bindir],
- "#{ConfigMap[:ruby_install_name]}#{ConfigMap[:EXEEXT]}")
-
- @ruby = "\"#{@ruby}\"" if @ruby =~ /\s/
- end
-
- @ruby
- end
-
- def self.latest_spec_for name
- dependency = Gem::Dependency.new name
- fetcher = Gem::SpecFetcher.fetcher
- spec_tuples = fetcher.find_matching dependency
-
- match = spec_tuples.select { |(n, _, p), _|
- n == name and Gem::Platform.match p
- }.sort_by { |(_, version, _), _|
- version
- }.last
-
- match and fetcher.fetch_spec(*match)
- end
-
- def self.latest_version_for name
- spec = latest_spec_for name
- spec and spec.version
- end
-
- def self.latest_rubygems_version
- latest_version_for "rubygems-update"
- end
-
- ##
- # A Gem::Version for the currently running ruby.
-
- def self.ruby_version
- return @ruby_version if defined? @ruby_version
- version = RUBY_VERSION.dup
-
- if defined?(RUBY_PATCHLEVEL) && RUBY_PATCHLEVEL != -1 then
- version << ".#{RUBY_PATCHLEVEL}"
- elsif defined?(RUBY_REVISION) then
- version << ".dev.#{RUBY_REVISION}"
- end
-
- @ruby_version = Gem::Version.new version
- end
-
- ##
- # The GemPathSearcher object used to search for matching installed gems.
-
- def self.searcher
- @searcher ||= Gem::GemPathSearcher.new
- end
-
- ##
- # Returns the Gem::SourceIndex of specifications that are in the Gem.path
-
- def self.source_index
- @@source_index ||= Gem::Deprecate.skip_during do
- SourceIndex.new Gem::Specification.dirs
- end
- end
-
- ##
- # Returns an Array of sources to fetch remote gems from. If the sources
- # list is empty, attempts to load the "sources" gem, then uses
- # default_sources if it is not installed.
-
- def self.sources
- @sources ||= default_sources
- end
-
- ##
- # Need to be able to set the sources without calling
- # Gem.sources.replace since that would cause an infinite loop.
-
- def self.sources= new_sources
- @sources = new_sources
- end
-
- ##
- # Glob pattern for require-able path suffixes.
-
- def self.suffix_pattern
- @suffix_pattern ||= "{#{suffixes.join(',')}}"
- end
-
- def self.loaded_path? path
- # TODO: ruby needs a feature to let us query what's loaded in 1.8 and 1.9
- re = /(^|\/)#{Regexp.escape path}#{Regexp.union(*Gem.suffixes)}$/
- $LOADED_FEATURES.any? { |s| s =~ re }
- end
-
- ##
- # Suffixes for require-able paths.
-
- def self.suffixes
- @suffixes ||= ['',
- '.rb',
- *%w(DLEXT DLEXT2).map { |key|
- val = RbConfig::CONFIG[key]
- next unless val and not val.empty?
- ".#{val}"
- }
- ].compact.uniq
- end
-
- ##
- # Prints the amount of time the supplied block takes to run using the debug
- # UI output.
-
- def self.time(msg, width = 0, display = Gem.configuration.verbose)
- now = Time.now
-
- value = yield
-
- elapsed = Time.now - now
-
- ui.say "%2$*1$s: %3$3.3fs" % [-width, msg, elapsed] if display
-
- value
- end
-
- ##
- # Lazily loads DefaultUserInteraction and returns the default UI.
-
- def self.ui
- require 'rubygems/user_interaction'
-
- Gem::DefaultUserInteraction.ui
- end
-
- ##
- # Use the +home+ and +paths+ values for Gem.dir and Gem.path. Used mainly
- # by the unit tests to provide environment isolation.
-
- def self.use_paths(home, *paths)
- paths = nil if paths == [nil]
- paths = paths.first if Array === Array(paths).first
- self.paths = { "GEM_HOME" => home, "GEM_PATH" => paths }
- # TODO: self.paths = home, paths
- end
-
- ##
- # The home directory for the user.
-
- def self.user_home
- @user_home ||= find_home
- end
-
- ##
- # Is this a windows platform?
-
- def self.win_platform?
- if @@win_platform.nil? then
- @@win_platform = !!WIN_PATTERNS.find { |r| RUBY_PLATFORM =~ r }
- end
-
- @@win_platform
- end
-
- ##
- # Load +plugins+ as ruby files
-
- def self.load_plugin_files(plugins)
- plugins.each do |plugin|
-
- # Skip older versions of the GemCutter plugin: Its commands are in
- # RubyGems proper now.
-
- next if plugin =~ /gemcutter-0\.[0-3]/
-
- begin
- load plugin
- rescue ::Exception => e
- details = "#{plugin.inspect}: #{e.message} (#{e.class})"
- warn "Error loading RubyGems plugin #{details}"
- end
- end
- end
-
- ##
- # Find all 'rubygems_plugin' files in installed gems and load them
-
- def self.load_plugins
- load_plugin_files find_files('rubygems_plugin', false)
- end
-
- ##
- # Find all 'rubygems_plugin' files in $LOAD_PATH and load them
-
- def self.load_env_plugins
- path = "rubygems_plugin"
-
- files = []
- $LOAD_PATH.each do |load_path|
- globbed = Dir["#{File.expand_path path, load_path}#{Gem.suffix_pattern}"]
-
- globbed.each do |load_path_file|
- files << load_path_file if File.file?(load_path_file.untaint)
- end
- end
-
- load_plugin_files files
- end
-
- class << self
-
- ##
- # Hash of loaded Gem::Specification keyed by name
-
- attr_reader :loaded_specs
-
- ##
- # The list of hooks to be run before Gem::Install#install finishes
- # installation
-
- attr_reader :post_build_hooks
-
- ##
- # The list of hooks to be run before Gem::Install#install does any work
-
- attr_reader :post_install_hooks
-
- ##
- # The list of hooks to be run after Gem::Specification.reset is run.
-
- attr_reader :post_reset_hooks
-
- ##
- # The list of hooks to be run before Gem::Uninstall#uninstall does any
- # work
-
- attr_reader :post_uninstall_hooks
-
- ##
- # The list of hooks to be run after Gem::Install#install is finished
-
- attr_reader :pre_install_hooks
-
- ##
- # The list of hooks to be run before Gem::Specification.reset is run.
-
- attr_reader :pre_reset_hooks
-
- ##
- # The list of hooks to be run after Gem::Uninstall#uninstall is finished
-
- attr_reader :pre_uninstall_hooks
- end
-
- def self.cache # :nodoc:
- source_index
- end
-
- ##
- # Location of Marshal quick gemspecs on remote repositories
-
- MARSHAL_SPEC_DIR = "quick/Marshal.#{Gem.marshal_version}/"
-
- autoload :Version, 'rubygems/version'
- autoload :Requirement, 'rubygems/requirement'
- autoload :Dependency, 'rubygems/dependency'
- autoload :DependencyList, 'rubygems/dependency_list'
- autoload :GemPathSearcher, 'rubygems/gem_path_searcher'
- autoload :SpecFetcher, 'rubygems/spec_fetcher'
- autoload :Specification, 'rubygems/specification'
- autoload :Cache, 'rubygems/source_index'
- autoload :SourceIndex, 'rubygems/source_index'
- autoload :PathSupport, 'rubygems/path_support'
- autoload :Platform, 'rubygems/platform'
- autoload :Builder, 'rubygems/builder'
- autoload :ConfigFile, 'rubygems/config_file'
-end
-
-module Kernel
-
- remove_method :gem if 'method' == defined? gem # from gem_prelude.rb on 1.9
-
- ##
- # Use Kernel#gem to activate a specific version of +gem_name+.
- #
- # +requirements+ is a list of version requirements that the
- # specified gem must match, most commonly "= example.version.number". See
- # Gem::Requirement for how to specify a version requirement.
- #
- # If you will be activating the latest version of a gem, there is no need to
- # call Kernel#gem, Kernel#require will do the right thing for you.
- #
- # Kernel#gem returns true if the gem was activated, otherwise false. If the
- # gem could not be found, didn't match the version requirements, or a
- # different version was already activated, an exception will be raised.
- #
- # Kernel#gem should be called *before* any require statements (otherwise
- # RubyGems may load a conflicting library version).
- #
- # In older RubyGems versions, the environment variable GEM_SKIP could be
- # used to skip activation of specified gems, for example to test out changes
- # that haven't been installed yet. Now RubyGems defers to -I and the
- # RUBYLIB environment variable to skip activation of a gem.
- #
- # Example:
- #
- # GEM_SKIP=libA:libB ruby -I../libA -I../libB ./mycode.rb
-
- def gem(gem_name, *requirements) # :doc:
- skip_list = (ENV['GEM_SKIP'] || "").split(/:/)
- raise Gem::LoadError, "skipping #{gem_name}" if skip_list.include? gem_name
- spec = Gem::Dependency.new(gem_name, *requirements).to_spec
- spec.activate if spec
- end
-
- private :gem
-
-end
-
-##
-# Return the path to the data directory associated with the named package. If
-# the package is loaded as a gem, return the gem specific data directory.
-# Otherwise return a path to the share area as define by
-# "#{ConfigMap[:datadir]}/#{package_name}".
-
-def RbConfig.datadir(package_name) # :nodoc:
- warn "#{Gem.location_of_caller.join ':'}:Warning: " \
- "RbConfig.datadir is deprecated and will be removed on or after " \
- "August 2011. " \
- "Use Gem::datadir."
-
- require 'rbconfig/datadir'
-
- Gem.datadir(package_name) || File.join(Gem::ConfigMap[:datadir], package_name)
-end
-
-require 'rubygems/exceptions'
-
-gem_preluded = Gem::GEM_PRELUDE_SUCKAGE and defined? Gem
-unless gem_preluded then # TODO: remove guard after 1.9.2 dropped
- begin
- ##
- # Defaults the operating system (or packager) wants to provide for RubyGems.
-
- require 'rubygems/defaults/operating_system'
- rescue LoadError
- end
-
- if defined?(RUBY_ENGINE) then
- begin
- ##
- # Defaults the ruby implementation wants to provide for RubyGems
-
- require "rubygems/defaults/#{RUBY_ENGINE}"
- rescue LoadError
- end
- end
-end
-
-##
-# Enables the require hook for RubyGems.
-
-require 'rubygems/custom_require'
-
-module Gem
- class << self
- extend Gem::Deprecate
- deprecate :activate_dep, "Specification#activate", 2011, 6
- deprecate :activate_spec, "Specification#activate", 2011, 6
- deprecate :cache, "Gem::source_index", 2011, 8
- deprecate :activate, "Specification#activate", 2011, 10
- deprecate :all_load_paths, :none, 2011, 10
- deprecate :all_partials, :none, 2011, 10
- deprecate :latest_load_paths, :none, 2011, 10
- deprecate :promote_load_path, :none, 2011, 10
- deprecate :available?, "Specification::find_by_name", 2011, 11
- deprecate :cache_dir, "Specification#cache_dir", 2011, 11
- deprecate :cache_gem, "Specification#cache_file", 2011, 11
- deprecate :default_system_source_cache_dir, :none, 2011, 11
- deprecate :default_user_source_cache_dir, :none, 2011, 11
- deprecate :report_activate_error, :none, 2011, 11
- deprecate :required_location, :none, 2011, 11
- deprecate :searcher, "Specification", 2011, 11
- deprecate :source_index, "Specification", 2011, 11
- end
-end
diff --git a/ruby_1_9_3/lib/rubygems/builder.rb b/ruby_1_9_3/lib/rubygems/builder.rb
deleted file mode 100644
index 25e8fc8321..0000000000
--- a/ruby_1_9_3/lib/rubygems/builder.rb
+++ /dev/null
@@ -1,99 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-require 'rubygems'
-require 'rubygems/user_interaction'
-
-Gem.load_yaml
-
-require 'rubygems/package'
-
-##
-# The Builder class processes RubyGem specification files
-# to produce a .gem file.
-
-class Gem::Builder
-
- include Gem::UserInteraction
-
- ##
- # Constructs a builder instance for the provided specification
- #
- # spec:: [Gem::Specification] The specification instance
-
- def initialize(spec)
- @spec = spec
- end
-
- ##
- # Builds the gem from the specification. Returns the name of the file
- # written.
-
- def build(skip_validation=false)
- @spec.mark_version
- @spec.validate unless skip_validation
- @signer = sign
- write_package
- say success if Gem.configuration.verbose
- File.basename @spec.cache_file
- end
-
- def success
- <<-EOM
- Successfully built RubyGem
- Name: #{@spec.name}
- Version: #{@spec.version}
- File: #{File.basename @spec.cache_file}
-EOM
- end
-
- private
-
- ##
- # If the signing key was specified, then load the file, and swap to the
- # public key (TODO: we should probably just omit the signing key in favor of
- # the signing certificate, but that's for the future, also the signature
- # algorithm should be configurable)
-
- def sign
- signer = nil
-
- if @spec.respond_to?(:signing_key) and @spec.signing_key then
- require 'rubygems/security'
-
- signer = Gem::Security::Signer.new @spec.signing_key, @spec.cert_chain
- @spec.signing_key = nil
- @spec.cert_chain = signer.cert_chain.map { |cert| cert.to_s }
- end
-
- signer
- end
-
- def write_package
- file_name = File.basename @spec.cache_file
- open file_name, 'wb' do |gem_io|
- Gem::Package.open gem_io, 'w', @signer do |pkg|
- yaml = @spec.to_yaml
- pkg.metadata = yaml
-
- @spec.files.each do |file|
- next if File.directory?(file)
- next if file == file_name # Don't add gem onto itself
-
- stat = File.stat(file)
- mode = stat.mode & 0777
- size = stat.size
-
- pkg.add_file_simple file, mode, size do |tar_io|
- tar_io.write open(file, "rb") { |f| f.read }
- end
- end
- end
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/command.rb b/ruby_1_9_3/lib/rubygems/command.rb
deleted file mode 100644
index 49253ef56b..0000000000
--- a/ruby_1_9_3/lib/rubygems/command.rb
+++ /dev/null
@@ -1,536 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-require 'optparse'
-require 'rubygems/user_interaction'
-
-##
-# Base class for all Gem commands. When creating a new gem command, define
-# #new, #execute, #arguments, #defaults_str, #description and #usage
-# (as appropriate). See the above mentioned methods for details.
-#
-# A very good example to look at is Gem::Commands::ContentsCommand
-
-class Gem::Command
-
- include Gem::UserInteraction
-
- ##
- # The name of the command.
-
- attr_reader :command
-
- ##
- # The options for the command.
-
- attr_reader :options
-
- ##
- # The default options for the command.
-
- attr_accessor :defaults
-
- ##
- # The name of the command for command-line invocation.
-
- attr_accessor :program_name
-
- ##
- # A short description of the command.
-
- attr_accessor :summary
-
- ##
- # Arguments used when building gems
-
- def self.build_args
- @build_args ||= []
- end
-
- def self.build_args=(value)
- @build_args = value
- end
-
- def self.common_options
- @common_options ||= []
- end
-
- def self.add_common_option(*args, &handler)
- Gem::Command.common_options << [args, handler]
- end
-
- def self.extra_args
- @extra_args ||= []
- end
-
- def self.extra_args=(value)
- case value
- when Array
- @extra_args = value
- when String
- @extra_args = value.split
- end
- end
-
- ##
- # Return an array of extra arguments for the command. The extra arguments
- # come from the gem configuration file read at program startup.
-
- def self.specific_extra_args(cmd)
- specific_extra_args_hash[cmd]
- end
-
- ##
- # Add a list of extra arguments for the given command. +args+ may be an
- # array or a string to be split on white space.
-
- def self.add_specific_extra_args(cmd,args)
- args = args.split(/\s+/) if args.kind_of? String
- specific_extra_args_hash[cmd] = args
- end
-
- ##
- # Accessor for the specific extra args hash (self initializing).
-
- def self.specific_extra_args_hash
- @specific_extra_args_hash ||= Hash.new do |h,k|
- h[k] = Array.new
- end
- end
-
- ##
- # Initializes a generic gem command named +command+. +summary+ is a short
- # description displayed in `gem help commands`. +defaults+ are the default
- # options. Defaults should be mirrored in #defaults_str, unless there are
- # none.
- #
- # When defining a new command subclass, use add_option to add command-line
- # switches.
- #
- # Unhandled arguments (gem names, files, etc.) are left in
- # <tt>options[:args]</tt>.
-
- def initialize(command, summary=nil, defaults={})
- @command = command
- @summary = summary
- @program_name = "gem #{command}"
- @defaults = defaults
- @options = defaults.dup
- @option_groups = Hash.new { |h,k| h[k] = [] }
- @parser = nil
- @when_invoked = nil
- end
-
- ##
- # True if +long+ begins with the characters from +short+.
-
- def begins?(long, short)
- return false if short.nil?
- long[0, short.length] == short
- end
-
- ##
- # Override to provide command handling.
- #
- # #options will be filled in with your parsed options, unparsed options will
- # be left in <tt>options[:args]</tt>.
- #
- # See also: #get_all_gem_names, #get_one_gem_name,
- # #get_one_optional_argument
-
- def execute
- raise Gem::Exception, "generic command has no actions"
- end
-
- ##
- # Display to the user that a gem couldn't be found and reasons why
-
- def show_lookup_failure(gem_name, version, errors, domain)
- if errors and !errors.empty?
- alert_error "Could not find a valid gem '#{gem_name}' (#{version}), here is why:"
- errors.each { |x| say " #{x.wordy}" }
- else
- alert_error "Could not find a valid gem '#{gem_name}' (#{version}) in any repository"
- end
-
- unless domain == :local then # HACK
- suggestions = Gem::SpecFetcher.fetcher.suggest_gems_from_name gem_name
-
- unless suggestions.empty?
- alert_error "Possible alternatives: #{suggestions.join(", ")}"
- end
- end
- end
-
- ##
- # Get all gem names from the command line.
-
- def get_all_gem_names
- args = options[:args]
-
- if args.nil? or args.empty? then
- raise Gem::CommandLineError,
- "Please specify at least one gem name (e.g. gem build GEMNAME)"
- end
-
- args.select { |arg| arg !~ /^-/ }
- end
-
- ##
- # Get a single gem name from the command line. Fail if there is no gem name
- # or if there is more than one gem name given.
-
- def get_one_gem_name
- args = options[:args]
-
- if args.nil? or args.empty? then
- raise Gem::CommandLineError,
- "Please specify a gem name on the command line (e.g. gem build GEMNAME)"
- end
-
- if args.size > 1 then
- raise Gem::CommandLineError,
- "Too many gem names (#{args.join(', ')}); please specify only one"
- end
-
- args.first
- end
-
- ##
- # Get a single optional argument from the command line. If more than one
- # argument is given, return only the first. Return nil if none are given.
-
- def get_one_optional_argument
- args = options[:args] || []
- args.first
- end
-
- ##
- # Override to provide details of the arguments a command takes. It should
- # return a left-justified string, one argument per line.
- #
- # For example:
- #
- # def usage
- # "#{program_name} FILE [FILE ...]"
- # end
- #
- # def arguments
- # "FILE name of file to find"
- # end
-
- def arguments
- ""
- end
-
- ##
- # Override to display the default values of the command options. (similar to
- # +arguments+, but displays the default values).
- #
- # For example:
- #
- # def defaults_str
- # --no-gems-first --no-all
- # end
-
- def defaults_str
- ""
- end
-
- ##
- # Override to display a longer description of what this command does.
-
- def description
- nil
- end
-
- ##
- # Override to display the usage for an individual gem command.
- #
- # The text "[options]" is automatically appended to the usage text.
-
- def usage
- program_name
- end
-
- ##
- # Display the help message for the command.
-
- def show_help
- parser.program_name = usage
- say parser
- end
-
- ##
- # Invoke the command with the given list of arguments.
-
- def invoke(*args)
- handle_options args
-
- if options[:help] then
- show_help
- elsif @when_invoked then
- @when_invoked.call options
- else
- execute
- end
- end
-
- ##
- # Call the given block when invoked.
- #
- # Normal command invocations just executes the +execute+ method of the
- # command. Specifying an invocation block allows the test methods to
- # override the normal action of a command to determine that it has been
- # invoked correctly.
-
- def when_invoked(&block)
- @when_invoked = block
- end
-
- ##
- # Add a command-line option and handler to the command.
- #
- # See OptionParser#make_switch for an explanation of +opts+.
- #
- # +handler+ will be called with two values, the value of the argument and
- # the options hash.
- #
- # If the first argument of add_option is a Symbol, it's used to group
- # options in output. See `gem help list` for an example.
-
- def add_option(*opts, &handler) # :yields: value, options
- group_name = Symbol === opts.first ? opts.shift : :options
-
- @option_groups[group_name] << [opts, handler]
- end
-
- ##
- # Remove previously defined command-line argument +name+.
-
- def remove_option(name)
- @option_groups.each do |_, option_list|
- option_list.reject! { |args, _| args.any? { |x| x =~ /^#{name}/ } }
- end
- end
-
- ##
- # Merge a set of command options with the set of default options (without
- # modifying the default option hash).
-
- def merge_options(new_options)
- @options = @defaults.clone
- new_options.each do |k,v| @options[k] = v end
- end
-
- ##
- # True if the command handles the given argument list.
-
- def handles?(args)
- begin
- parser.parse!(args.dup)
- return true
- rescue
- return false
- end
- end
-
- ##
- # Handle the given list of arguments by parsing them and recording the
- # results.
-
- def handle_options(args)
- args = add_extra_args(args)
- @options = @defaults.clone
- parser.parse!(args)
- @options[:args] = args
- end
-
- ##
- # Adds extra args from ~/.gemrc
-
- def add_extra_args(args)
- result = []
-
- s_extra = Gem::Command.specific_extra_args(@command)
- extra = Gem::Command.extra_args + s_extra
-
- until extra.empty? do
- ex = []
- ex << extra.shift
- ex << extra.shift if extra.first.to_s =~ /^[^-]/
- result << ex if handles?(ex)
- end
-
- result.flatten!
- result.concat(args)
- result
- end
-
- private
-
- ##
- # Create on demand parser.
-
- def parser
- create_option_parser if @parser.nil?
- @parser
- end
-
- def create_option_parser
- @parser = OptionParser.new
-
- @parser.separator nil
- regular_options = @option_groups.delete :options
-
- configure_options "", regular_options
-
- @option_groups.sort_by { |n,_| n.to_s }.each do |group_name, option_list|
- @parser.separator nil
- configure_options group_name, option_list
- end
-
- @parser.separator nil
- configure_options "Common", Gem::Command.common_options
-
- unless arguments.empty?
- @parser.separator nil
- @parser.separator " Arguments:"
- arguments.split(/\n/).each do |arg_desc|
- @parser.separator " #{arg_desc}"
- end
- end
-
- if @summary then
- @parser.separator nil
- @parser.separator " Summary:"
- wrap(@summary, 80 - 4).split("\n").each do |line|
- @parser.separator " #{line.strip}"
- end
- end
-
- if description then
- formatted = description.split("\n\n").map do |chunk|
- wrap chunk, 80 - 4
- end.join "\n"
-
- @parser.separator nil
- @parser.separator " Description:"
- formatted.split("\n").each do |line|
- @parser.separator " #{line.rstrip}"
- end
- end
-
- unless defaults_str.empty?
- @parser.separator nil
- @parser.separator " Defaults:"
- defaults_str.split(/\n/).each do |line|
- @parser.separator " #{line}"
- end
- end
- end
-
- def configure_options(header, option_list)
- return if option_list.nil? or option_list.empty?
-
- header = header.to_s.empty? ? '' : "#{header} "
- @parser.separator " #{header}Options:"
-
- option_list.each do |args, handler|
- args.select { |arg| arg =~ /^-/ }
- @parser.on(*args) do |value|
- handler.call(value, @options)
- end
- end
-
- @parser.separator ''
- end
-
- ##
- # Wraps +text+ to +width+
-
- def wrap(text, width) # :doc:
- text.gsub(/(.{1,#{width}})( +|$\n?)|(.{1,#{width}})/, "\\1\\3\n")
- end
-
- # ----------------------------------------------------------------
- # Add the options common to all commands.
-
- add_common_option('-h', '--help',
- 'Get help on this command') do |value, options|
- options[:help] = true
- end
-
- add_common_option('-V', '--[no-]verbose',
- 'Set the verbose level of output') do |value, options|
- # Set us to "really verbose" so the progress meter works
- if Gem.configuration.verbose and value then
- Gem.configuration.verbose = 1
- else
- Gem.configuration.verbose = value
- end
- end
-
- add_common_option('-q', '--quiet', 'Silence commands') do |value, options|
- Gem.configuration.verbose = false
- end
-
- # Backtrace and config-file are added so they show up in the help
- # commands. Both options are actually handled before the other
- # options get parsed.
-
- add_common_option('--config-file FILE',
- 'Use this config file instead of default') do
- end
-
- add_common_option('--backtrace',
- 'Show stack backtrace on errors') do
- end
-
- add_common_option('--debug',
- 'Turn on Ruby debugging') do
- end
-
- # :stopdoc:
-
- HELP = <<-HELP
-RubyGems is a sophisticated package manager for Ruby. This is a
-basic help message containing pointers to more information.
-
- Usage:
- gem -h/--help
- gem -v/--version
- gem command [arguments...] [options...]
-
- Examples:
- gem install rake
- gem list --local
- gem build package.gemspec
- gem help install
-
- Further help:
- gem help commands list all 'gem' commands
- gem help examples show some examples of usage
- gem help platforms show information about platforms
- gem help <COMMAND> show help on COMMAND
- (e.g. 'gem help install')
- gem server present a web page at
- http://localhost:8808/
- with info about installed gems
- Further information:
- http://rubygems.rubyforge.org
- HELP
-
- # :startdoc:
-
-end
-
-##
-# This is where Commands will be placed in the namespace
-
-module Gem::Commands
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/command_manager.rb b/ruby_1_9_3/lib/rubygems/command_manager.rb
deleted file mode 100644
index 9edd550136..0000000000
--- a/ruby_1_9_3/lib/rubygems/command_manager.rb
+++ /dev/null
@@ -1,194 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-require 'rubygems/command'
-require 'rubygems/user_interaction'
-
-##
-# The command manager registers and installs all the individual sub-commands
-# supported by the gem command.
-#
-# Extra commands can be provided by writing a rubygems_plugin.rb
-# file in an installed gem. You should register your command against the
-# Gem::CommandManager instance, like this:
-#
-# # file rubygems_plugin.rb
-# require 'rubygems/command_manager'
-#
-# class Gem::Commands::EditCommand < Gem::Command
-# # ...
-# end
-#
-# Gem::CommandManager.instance.register_command :edit
-#
-# See Gem::Command for instructions on writing gem commands.
-
-class Gem::CommandManager
-
- include Gem::UserInteraction
-
- ##
- # Return the authoritative instance of the command manager.
-
- def self.instance
- @command_manager ||= new
- end
-
- ##
- # Reset the authoritative instance of the command manager.
-
- def self.reset
- @command_manager = nil
- end
-
- ##
- # Register all the subcommands supported by the gem command.
-
- def initialize
- require 'timeout'
- @commands = {}
- register_command :build
- register_command :cert
- register_command :check
- register_command :cleanup
- register_command :contents
- register_command :dependency
- register_command :environment
- register_command :fetch
- register_command :generate_index
- register_command :help
- register_command :install
- register_command :list
- register_command :lock
- register_command :outdated
- register_command :owner
- register_command :pristine
- register_command :push
- register_command :query
- register_command :rdoc
- register_command :search
- register_command :server
- register_command :sources
- register_command :specification
- register_command :stale
- register_command :uninstall
- register_command :unpack
- register_command :update
- register_command :which
- end
-
- ##
- # Register the Symbol +command+ as a gem command.
-
- def register_command(command)
- @commands[command] = false
- end
-
- ##
- # Unregister the Symbol +command+ as a gem command.
-
- def unregister_command(command)
- @commands.delete command
- end
-
- ##
- # Return the registered command from the command name.
-
- def [](command_name)
- command_name = command_name.intern
- return nil if @commands[command_name].nil?
- @commands[command_name] ||= load_and_instantiate(command_name)
- end
-
- ##
- # Return a sorted list of all command names (as strings).
-
- def command_names
- @commands.keys.collect {|key| key.to_s}.sort
- end
-
- ##
- # Run the config specified by +args+.
-
- def run(args)
- process_args(args)
- rescue StandardError, Timeout::Error => ex
- alert_error "While executing gem ... (#{ex.class})\n #{ex.to_s}"
- ui.errs.puts "\t#{ex.backtrace.join "\n\t"}" if
- Gem.configuration.backtrace
- terminate_interaction(1)
- rescue Interrupt
- alert_error "Interrupted"
- terminate_interaction(1)
- end
-
- def process_args(args)
- args = args.to_str.split(/\s+/) if args.respond_to?(:to_str)
- if args.size == 0
- say Gem::Command::HELP
- terminate_interaction(1)
- end
- case args[0]
- when '-h', '--help'
- say Gem::Command::HELP
- terminate_interaction(0)
- when '-v', '--version'
- say Gem::VERSION
- terminate_interaction(0)
- when /^-/
- alert_error "Invalid option: #{args[0]}. See 'gem --help'."
- terminate_interaction(1)
- else
- cmd_name = args.shift.downcase
- cmd = find_command(cmd_name)
- cmd.invoke(*args)
- end
- end
-
- def find_command(cmd_name)
- possibilities = find_command_possibilities cmd_name
- if possibilities.size > 1 then
- raise "Ambiguous command #{cmd_name} matches [#{possibilities.join(', ')}]"
- elsif possibilities.size < 1 then
- raise "Unknown command #{cmd_name}"
- end
-
- self[possibilities.first]
- end
-
- def find_command_possibilities(cmd_name)
- len = cmd_name.length
-
- command_names.select { |n| cmd_name == n[0, len] }
- end
-
- private
-
- def load_and_instantiate(command_name)
- command_name = command_name.to_s
- const_name = command_name.capitalize.gsub(/_(.)/) { $1.upcase } << "Command"
- commands = Gem::Commands
- retried = false
-
- begin
- commands.const_get(const_name).new
- rescue NameError
- raise if retried
-
- retried = true
- begin
- require "rubygems/commands/#{command_name}_command"
- rescue Exception => e
- alert_error "Loading command: #{command_name} (#{e.class})\n #{e}"
- ui.errs.puts "\t#{e.backtrace.join "\n\t"}" if
- Gem.configuration.backtrace
- end
- retry
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/commands/build_command.rb b/ruby_1_9_3/lib/rubygems/commands/build_command.rb
deleted file mode 100644
index 36a6fe48f2..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/build_command.rb
+++ /dev/null
@@ -1,59 +0,0 @@
-require 'rubygems/command'
-require 'rubygems/builder'
-
-class Gem::Commands::BuildCommand < Gem::Command
-
- def initialize
- super 'build', 'Build a gem from a gemspec'
-
- add_option '--force', 'skip validation of the spec' do |value, options|
- options[:force] = true
- end
- end
-
- def arguments # :nodoc:
- "GEMSPEC_FILE gemspec file name to build a gem for"
- end
-
- def usage # :nodoc:
- "#{program_name} GEMSPEC_FILE"
- end
-
- def execute
- gemspec = get_one_gem_name
-
- if File.exist? gemspec
- spec = load_gemspec gemspec
-
- if spec then
- Gem::Builder.new(spec).build options[:force]
- else
- alert_error "Error loading gemspec. Aborting."
- terminate_interaction 1
- end
- else
- alert_error "Gemspec file not found: #{gemspec}"
- terminate_interaction 1
- end
- end
-
- def load_gemspec filename
- if yaml?(filename)
- open(filename) do |f|
- begin
- Gem::Specification.from_yaml(f)
- rescue Gem::EndOfYAMLException
- nil
- end
- end
- else
- Gem::Specification.load(filename) # can return nil
- end
- end
-
- def yaml?(filename)
- line = open(filename) { |f| line = f.gets }
- result = line =~ %r{!ruby/object:Gem::Specification}
- result
- end
-end
diff --git a/ruby_1_9_3/lib/rubygems/commands/cert_command.rb b/ruby_1_9_3/lib/rubygems/commands/cert_command.rb
deleted file mode 100644
index b416b3863d..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/cert_command.rb
+++ /dev/null
@@ -1,86 +0,0 @@
-require 'rubygems/command'
-require 'rubygems/security'
-
-class Gem::Commands::CertCommand < Gem::Command
-
- def initialize
- super 'cert', 'Manage RubyGems certificates and signing settings'
-
- add_option('-a', '--add CERT',
- 'Add a trusted certificate.') do |value, options|
- cert = OpenSSL::X509::Certificate.new(File.read(value))
- Gem::Security.add_trusted_cert(cert)
- say "Added '#{cert.subject.to_s}'"
- end
-
- add_option('-l', '--list',
- 'List trusted certificates.') do |value, options|
- glob_str = File::join(Gem::Security::OPT[:trust_dir], '*.pem')
- Dir::glob(glob_str) do |path|
- begin
- cert = OpenSSL::X509::Certificate.new(File.read(path))
- # this could probably be formatted more gracefully
- say cert.subject.to_s
- rescue OpenSSL::X509::CertificateError
- next
- end
- end
- end
-
- add_option('-r', '--remove STRING',
- 'Remove trusted certificates containing',
- 'STRING.') do |value, options|
- trust_dir = Gem::Security::OPT[:trust_dir]
- glob_str = File::join(trust_dir, '*.pem')
-
- Dir::glob(glob_str) do |path|
- begin
- cert = OpenSSL::X509::Certificate.new(File.read(path))
- if cert.subject.to_s.downcase.index(value)
- say "Removed '#{cert.subject.to_s}'"
- File.unlink(path)
- end
- rescue OpenSSL::X509::CertificateError
- next
- end
- end
- end
-
- add_option('-b', '--build EMAIL_ADDR',
- 'Build private key and self-signed',
- 'certificate for EMAIL_ADDR.') do |value, options|
- vals = Gem::Security.build_self_signed_cert(value)
- FileUtils.chmod 0600, vals[:key_path]
- say "Public Cert: #{vals[:cert_path]}"
- say "Private Key: #{vals[:key_path]}"
- say "Don't forget to move the key file to somewhere private..."
- end
-
- add_option('-C', '--certificate CERT',
- 'Certificate for --sign command.') do |value, options|
- cert = OpenSSL::X509::Certificate.new(File.read(value))
- options[:issuer_cert] = cert
- end
-
- add_option('-K', '--private-key KEY',
- 'Private key for --sign command.') do |value, options|
- key = OpenSSL::PKey::RSA.new(File.read(value))
- options[:issuer_key] = key
- end
-
- add_option('-s', '--sign NEWCERT',
- 'Sign a certificate with my key and',
- 'certificate.') do |value, options|
- cert = OpenSSL::X509::Certificate.new(File.read(value))
- my_cert = options[:issuer_cert]
- my_key = options[:issuer_key]
- cert = Gem::Security.sign_cert(cert, my_key, my_cert)
- File.open(value, 'wb') { |file| file.write(cert.to_pem) }
- end
- end
-
- def execute
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/commands/check_command.rb b/ruby_1_9_3/lib/rubygems/commands/check_command.rb
deleted file mode 100644
index 5a1bfd4f12..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/check_command.rb
+++ /dev/null
@@ -1,65 +0,0 @@
-require 'rubygems/command'
-require 'rubygems/version_option'
-require 'rubygems/validator'
-
-class Gem::Commands::CheckCommand < Gem::Command
-
- include Gem::VersionOption
-
- def initialize
- super 'check', 'Check installed gems',
- :verify => false, :alien => false
-
- add_option( '--verify FILE',
- 'Verify gem file against its internal',
- 'checksum') do |value, options|
- options[:verify] = value
- end
-
- add_option('-a', '--alien', "Report 'unmanaged' or rogue files in the",
- "gem repository") do |value, options|
- options[:alien] = true
- end
-
- add_version_option 'check'
- end
-
- def execute
- if options[:alien]
- say "Performing the 'alien' operation"
- say
- gems = get_all_gem_names rescue []
- Gem::Validator.new.alien(gems).sort.each do |key, val|
- unless val.empty? then
- say "#{key} has #{val.size} problems"
- val.each do |error_entry|
- say " #{error_entry.path}:"
- say " #{error_entry.problem}"
- end
- else
- say "#{key} is error-free" if Gem.configuration.verbose
- end
- say
- end
- end
-
- if options[:verify]
- gem_name = options[:verify]
- unless gem_name
- alert_error "Must specify a .gem file with --verify NAME"
- return
- end
- unless File.exist?(gem_name)
- alert_error "Unknown file: #{gem_name}."
- return
- end
- say "Verifying gem: '#{gem_name}'"
- begin
- Gem::Validator.new.verify_gem_file(gem_name)
- rescue Exception
- alert_error "#{gem_name} is invalid."
- end
- end
- end
-
-end
diff --git a/ruby_1_9_3/lib/rubygems/commands/cleanup_command.rb b/ruby_1_9_3/lib/rubygems/commands/cleanup_command.rb
deleted file mode 100644
index 124c4c203a..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/cleanup_command.rb
+++ /dev/null
@@ -1,100 +0,0 @@
-require 'rubygems/command'
-require 'rubygems/dependency_list'
-require 'rubygems/uninstaller'
-
-class Gem::Commands::CleanupCommand < Gem::Command
-
- def initialize
- super 'cleanup',
- 'Clean up old versions of installed gems in the local repository',
- :force => false, :install_dir => Gem.dir
-
- add_option('-d', '--dryrun', "") do |value, options|
- options[:dryrun] = true
- end
- end
-
- def arguments # :nodoc:
- "GEMNAME name of gem to cleanup"
- end
-
- def defaults_str # :nodoc:
- "--no-dryrun"
- end
-
- def description # :nodoc:
- <<-EOF
-The cleanup command removes old gems from GEM_HOME. If an older version is
-installed elsewhere in GEM_PATH the cleanup command won't touch it.
- EOF
- end
-
- def usage # :nodoc:
- "#{program_name} [GEMNAME ...]"
- end
-
- def execute
- say "Cleaning up installed gems..."
- primary_gems = {}
-
- Gem::Specification.each do |spec|
- if primary_gems[spec.name].nil? or
- primary_gems[spec.name].version < spec.version then
- primary_gems[spec.name] = spec
- end
- end
-
- gems_to_cleanup = unless options[:args].empty? then
- options[:args].map do |gem_name|
- Gem::Specification.find_all_by_name gem_name
- end.flatten
- else
- Gem::Specification.to_a
- end
-
- gems_to_cleanup = gems_to_cleanup.select { |spec|
- primary_gems[spec.name].version != spec.version
- }
-
- deplist = Gem::DependencyList.new
- gems_to_cleanup.uniq.each do |spec| deplist.add spec end
-
- deps = deplist.strongly_connected_components.flatten.reverse
-
- original_path = Gem.path
-
- deps.each do |spec|
- if options[:dryrun] then
- say "Dry Run Mode: Would uninstall #{spec.full_name}"
- else
- say "Attempting to uninstall #{spec.full_name}"
-
- options[:args] = [spec.name]
-
- uninstall_options = {
- :executables => false,
- :version => "= #{spec.version}",
- }
-
- uninstall_options[:user_install] = Gem.user_dir == spec.base_dir
-
- uninstaller = Gem::Uninstaller.new spec.name, uninstall_options
-
- begin
- uninstaller.uninstall
- rescue Gem::DependencyRemovalException, Gem::InstallError,
- Gem::GemNotInHomeException, Gem::FilePermissionError => e
- say "Unable to uninstall #{spec.full_name}:"
- say "\t#{e.class}: #{e.message}"
- end
- end
-
- # Restore path Gem::Uninstaller may have change
- Gem.use_paths(*original_path)
- end
-
- say "Clean Up Complete"
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/commands/contents_command.rb b/ruby_1_9_3/lib/rubygems/commands/contents_command.rb
deleted file mode 100644
index e483484615..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/contents_command.rb
+++ /dev/null
@@ -1,101 +0,0 @@
-require 'rubygems/command'
-require 'rubygems/version_option'
-
-class Gem::Commands::ContentsCommand < Gem::Command
-
- include Gem::VersionOption
-
- def initialize
- super 'contents', 'Display the contents of the installed gems',
- :specdirs => [], :lib_only => false, :prefix => true
-
- add_version_option
-
- add_option( '--all',
- "Contents for all gems") do |all, options|
- options[:all] = all
- end
-
- add_option('-s', '--spec-dir a,b,c', Array,
- "Search for gems under specific paths") do |spec_dirs, options|
- options[:specdirs] = spec_dirs
- end
-
- add_option('-l', '--[no-]lib-only',
- "Only return files in the Gem's lib_dirs") do |lib_only, options|
- options[:lib_only] = lib_only
- end
-
- add_option( '--[no-]prefix',
- "Don't include installed path prefix") do |prefix, options|
- options[:prefix] = prefix
- end
- end
-
- def arguments # :nodoc:
- "GEMNAME name of gem to list contents for"
- end
-
- def defaults_str # :nodoc:
- "--no-lib-only --prefix"
- end
-
- def usage # :nodoc:
- "#{program_name} GEMNAME [GEMNAME ...]"
- end
-
- def execute
- version = options[:version] || Gem::Requirement.default
-
- spec_dirs = options[:specdirs].map do |i|
- [i, File.join(i, "specifications")]
- end.flatten
-
- path_kind = if spec_dirs.empty? then
- spec_dirs = Gem::Specification.dirs
- "default gem paths"
- else
- "specified path"
- end
-
- gem_names = if options[:all] then
- Gem::Specification.map(&:name)
- else
- get_all_gem_names
- end
-
- gem_names.each do |name|
- # HACK: find_by_name fails for some reason... ARGH
- # How many places must we embed our resolve logic?
- spec = Gem::Specification.find_all_by_name(name, version).last
-
- unless spec then
- say "Unable to find gem '#{name}' in #{path_kind}"
-
- if Gem.configuration.verbose then
- say "\nDirectories searched:"
- spec_dirs.each { |dir| say dir }
- end
-
- terminate_interaction 1 if gem_names.length == 1
- end
-
- gem_path = spec.full_gem_path
- extra = "/{#{spec.require_paths.join ','}}" if options[:lib_only]
- glob = "#{gem_path}#{extra}/**/*"
- files = Dir[glob]
-
- gem_path = File.join gem_path, '' # add trailing / if missing
-
- files.sort.each do |file|
- next if File.directory? file
-
- file = file.sub gem_path, '' unless options[:prefix]
-
- say file
- end
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/commands/dependency_command.rb b/ruby_1_9_3/lib/rubygems/commands/dependency_command.rb
deleted file mode 100644
index 67cbbc1d5e..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/dependency_command.rb
+++ /dev/null
@@ -1,160 +0,0 @@
-require 'rubygems/command'
-require 'rubygems/local_remote_options'
-require 'rubygems/version_option'
-
-class Gem::Commands::DependencyCommand < Gem::Command
-
- include Gem::LocalRemoteOptions
- include Gem::VersionOption
-
- def initialize
- super 'dependency',
- 'Show the dependencies of an installed gem',
- :version => Gem::Requirement.default, :domain => :local
-
- add_version_option
- add_platform_option
- add_prerelease_option
-
- add_option('-R', '--[no-]reverse-dependencies',
- 'Include reverse dependencies in the output') do
- |value, options|
- options[:reverse_dependencies] = value
- end
-
- add_option('-p', '--pipe',
- "Pipe Format (name --version ver)") do |value, options|
- options[:pipe_format] = value
- end
-
- add_local_remote_options
- end
-
- def arguments # :nodoc:
- "GEMNAME name of gem to show dependencies for"
- end
-
- def defaults_str # :nodoc:
- "--local --version '#{Gem::Requirement.default}' --no-reverse-dependencies"
- end
-
- def usage # :nodoc:
- "#{program_name} GEMNAME"
- end
-
- def execute
- if options[:reverse_dependencies] and remote? and not local? then
- alert_error 'Only reverse dependencies for local gems are supported.'
- terminate_interaction 1
- end
-
- options[:args] << '' if options[:args].empty?
-
- pattern = if options[:args].length == 1 and
- options[:args].first =~ /\A\/(.*)\/(i)?\z/m then
- flags = $2 ? Regexp::IGNORECASE : nil
- Regexp.new $1, flags
- else
- /\A#{Regexp.union(*options[:args])}/
- end
-
- # TODO: deprecate for real damnit
- dependency = Gem::Deprecate.skip_during {
- Gem::Dependency.new pattern, options[:version]
- }
- dependency.prerelease = options[:prerelease]
-
- specs = []
-
- specs.concat dependency.matching_specs if local?
-
- if remote? and not options[:reverse_dependencies] then
- fetcher = Gem::SpecFetcher.fetcher
-
- # REFACTOR: fetcher.find_specs_matching => specs
- specs_and_sources = fetcher.find_matching(dependency,
- dependency.specific?, true,
- dependency.prerelease?)
-
- specs.concat specs_and_sources.map { |spec_tuple, source_uri|
- fetcher.fetch_spec spec_tuple, URI.parse(source_uri)
- }
- end
-
- if specs.empty? then
- patterns = options[:args].join ','
- say "No gems found matching #{patterns} (#{options[:version]})" if
- Gem.configuration.verbose
-
- terminate_interaction 1
- end
-
- specs = specs.uniq.sort
-
- reverse = Hash.new { |h, k| h[k] = [] }
-
- if options[:reverse_dependencies] then
- specs.each do |spec|
- reverse[spec.full_name] = find_reverse_dependencies spec
- end
- end
-
- if options[:pipe_format] then
- specs.each do |spec|
- unless spec.dependencies.empty?
- spec.dependencies.sort_by { |dep| dep.name }.each do |dep|
- say "#{dep.name} --version '#{dep.requirement}'"
- end
- end
- end
- else
- response = ''
-
- specs.each do |spec|
- response << print_dependencies(spec)
- unless reverse[spec.full_name].empty? then
- response << " Used by\n"
- reverse[spec.full_name].each do |sp, dep|
- response << " #{sp} (#{dep})\n"
- end
- end
- response << "\n"
- end
-
- say response
- end
- end
-
- def print_dependencies(spec, level = 0)
- response = ''
- response << ' ' * level + "Gem #{spec.full_name}\n"
- unless spec.dependencies.empty? then
- spec.dependencies.sort_by { |dep| dep.name }.each do |dep|
- response << ' ' * level + " #{dep}\n"
- end
- end
- response
- end
-
- ##
- # Returns an Array of [specification, dep] that are satisfied by +spec+.
-
- def find_reverse_dependencies(spec)
- result = []
-
- Gem::Specification.each do |sp|
- sp.dependencies.each do |dep|
- dep = Gem::Dependency.new(*dep) unless Gem::Dependency === dep
-
- if spec.name == dep.name and
- dep.requirement.satisfied_by?(spec.version) then
- result << [sp.full_name, dep]
- end
- end
- end
-
- result
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/commands/environment_command.rb b/ruby_1_9_3/lib/rubygems/commands/environment_command.rb
deleted file mode 100644
index 9585c71250..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/environment_command.rb
+++ /dev/null
@@ -1,130 +0,0 @@
-require 'rubygems/command'
-
-class Gem::Commands::EnvironmentCommand < Gem::Command
-
- def initialize
- super 'environment', 'Display information about the RubyGems environment'
- end
-
- def arguments # :nodoc:
- args = <<-EOF
- packageversion display the package version
- gemdir display the path where gems are installed
- gempath display path used to search for gems
- version display the gem format version
- remotesources display the remote gem servers
- platform display the supported gem platforms
- <omitted> display everything
- EOF
- return args.gsub(/^\s+/, '')
- end
-
- def description # :nodoc:
- <<-EOF
-The RubyGems environment can be controlled through command line arguments,
-gemrc files, environment variables and built-in defaults.
-
-Command line argument defaults and some RubyGems defaults can be set in
-~/.gemrc file for individual users and a /etc/gemrc for all users. A gemrc
-is a YAML file with the following YAML keys:
-
- :sources: A YAML array of remote gem repositories to install gems from
- :verbose: Verbosity of the gem command. false, true, and :really are the
- levels
- :update_sources: Enable/disable automatic updating of repository metadata
- :backtrace: Print backtrace when RubyGems encounters an error
- :gempath: The paths in which to look for gems
- gem_command: A string containing arguments for the specified gem command
-
-Example:
-
- :verbose: false
- install: --no-wrappers
- update: --no-wrappers
-
-RubyGems' default local repository can be overridden with the GEM_PATH and
-GEM_HOME environment variables. GEM_HOME sets the default repository to
-install into. GEM_PATH allows multiple local repositories to be searched for
-gems.
-
-If you are behind a proxy server, RubyGems uses the HTTP_PROXY,
-HTTP_PROXY_USER and HTTP_PROXY_PASS environment variables to discover the
-proxy server.
-
-If you are packaging RubyGems all of RubyGems' defaults are in
-lib/rubygems/defaults.rb. You may override these in
-lib/rubygems/defaults/operating_system.rb
- EOF
- end
-
- def usage # :nodoc:
- "#{program_name} [arg]"
- end
-
- def execute
- out = ''
- arg = options[:args][0]
- case arg
- when /^packageversion/ then
- out << Gem::RubyGemsPackageVersion
- when /^version/ then
- out << Gem::VERSION
- when /^gemdir/, /^gemhome/, /^home/, /^GEM_HOME/ then
- out << Gem.dir
- when /^gempath/, /^path/, /^GEM_PATH/ then
- out << Gem.path.join(File::PATH_SEPARATOR)
- when /^remotesources/ then
- out << Gem.sources.join("\n")
- when /^platform/ then
- out << Gem.platforms.join(File::PATH_SEPARATOR)
- when nil then
- out = "RubyGems Environment:\n"
-
- out << " - RUBYGEMS VERSION: #{Gem::VERSION}\n"
-
- out << " - RUBY VERSION: #{RUBY_VERSION} (#{RUBY_RELEASE_DATE}"
- out << " patchlevel #{RUBY_PATCHLEVEL}" if defined? RUBY_PATCHLEVEL
- out << ") [#{RUBY_PLATFORM}]\n"
-
- out << " - INSTALLATION DIRECTORY: #{Gem.dir}\n"
-
- out << " - RUBYGEMS PREFIX: #{Gem.prefix}\n" unless Gem.prefix.nil?
-
- out << " - RUBY EXECUTABLE: #{Gem.ruby}\n"
-
- out << " - EXECUTABLE DIRECTORY: #{Gem.bindir}\n"
-
- out << " - RUBYGEMS PLATFORMS:\n"
- Gem.platforms.each do |platform|
- out << " - #{platform}\n"
- end
-
- out << " - GEM PATHS:\n"
- out << " - #{Gem.dir}\n"
-
- path = Gem.path.dup
- path.delete Gem.dir
- path.each do |p|
- out << " - #{p}\n"
- end
-
- out << " - GEM CONFIGURATION:\n"
- Gem.configuration.each do |name, value|
- value = value.gsub(/./, '*') if name == 'gemcutter_key'
- out << " - #{name.inspect} => #{value.inspect}\n"
- end
-
- out << " - REMOTE SOURCES:\n"
- Gem.sources.each do |s|
- out << " - #{s}\n"
- end
-
- else
- raise Gem::CommandLineError, "Unknown environment option [#{arg}]"
- end
- say out
- true
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/commands/fetch_command.rb b/ruby_1_9_3/lib/rubygems/commands/fetch_command.rb
deleted file mode 100644
index e7c9cc9525..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/fetch_command.rb
+++ /dev/null
@@ -1,78 +0,0 @@
-require 'rubygems/command'
-require 'rubygems/local_remote_options'
-require 'rubygems/version_option'
-
-class Gem::Commands::FetchCommand < Gem::Command
-
- include Gem::LocalRemoteOptions
- include Gem::VersionOption
-
- def initialize
- super 'fetch', 'Download a gem and place it in the current directory'
-
- add_bulk_threshold_option
- add_proxy_option
- add_source_option
- add_clear_sources_option
-
- add_version_option
- add_platform_option
- add_prerelease_option
- end
-
- def arguments # :nodoc:
- 'GEMNAME name of gem to download'
- end
-
- def defaults_str # :nodoc:
- "--version '#{Gem::Requirement.default}'"
- end
-
- def usage # :nodoc:
- "#{program_name} GEMNAME [GEMNAME ...]"
- end
-
- def execute
- version = options[:version] || Gem::Requirement.default
- all = Gem::Requirement.default != version
-
- platform = Gem.platforms.last
- gem_names = get_all_gem_names
-
- gem_names.each do |gem_name|
- dep = Gem::Dependency.new gem_name, version
- dep.prerelease = options[:prerelease]
-
- specs_and_sources, errors =
- Gem::SpecFetcher.fetcher.fetch_with_errors(dep, all, true,
- dep.prerelease?)
-
- if platform then
- filtered = specs_and_sources.select { |s,| s.platform == platform }
- specs_and_sources = filtered unless filtered.empty?
- end
-
- spec, source_uri = specs_and_sources.sort_by { |s,| s.version }.last
-
- if spec.nil? then
- show_lookup_failure gem_name, version, errors, options[:domain]
- next
- end
-
- file = "#{spec.full_name}.gem"
- remote_path = URI.parse(source_uri) + "gems/#{file}"
-
- fetch = Gem::RemoteFetcher.fetcher
-
- gem = fetch.fetch_path remote_path.to_s
-
- File.open file, "wb" do |f|
- f.write gem
- end
-
- say "Downloaded #{spec.full_name}"
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/commands/generate_index_command.rb b/ruby_1_9_3/lib/rubygems/commands/generate_index_command.rb
deleted file mode 100644
index d4b4790649..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/generate_index_command.rb
+++ /dev/null
@@ -1,124 +0,0 @@
-require 'rubygems/command'
-require 'rubygems/indexer'
-
-##
-# Generates a index files for use as a gem server.
-#
-# See `gem help generate_index`
-
-class Gem::Commands::GenerateIndexCommand < Gem::Command
-
- def initialize
- super 'generate_index',
- 'Generates the index files for a gem server directory',
- :directory => '.', :build_legacy => true, :build_modern => true
-
- add_option '-d', '--directory=DIRNAME',
- 'repository base dir containing gems subdir' do |dir, options|
- options[:directory] = File.expand_path dir
- end
-
- add_option '--[no-]legacy',
- 'Generate Marshal.4.8' do |value, options|
- unless options[:build_modern] or value then
- raise OptionParser::InvalidOption, 'no indicies will be built'
- end
-
- options[:build_legacy] = value
- end
-
- add_option '--[no-]modern',
- 'Generate indexes for RubyGems newer',
- 'than 1.2.0' do |value, options|
- unless options[:build_legacy] or value then
- raise OptionParser::InvalidOption, 'no indicies will be built'
- end
-
- options[:build_modern] = value
- end
-
- add_option '--update',
- 'Update modern indexes with gems added',
- 'since the last update' do |value, options|
- options[:update] = value
- end
-
- add_option :RSS, '--rss-gems-host=GEM_HOST',
- 'Host name where gems are served from,',
- 'used for GUID and enclosure values' do |value, options|
- options[:rss_gems_host] = value
- end
-
- add_option :RSS, '--rss-host=HOST',
- 'Host name for more gems information,',
- 'used for RSS feed link' do |value, options|
- options[:rss_host] = value
- end
-
- add_option :RSS, '--rss-title=TITLE',
- 'Set title for RSS feed' do |value, options|
- options[:rss_title] = value
- end
- end
-
- def defaults_str # :nodoc:
- "--directory . --legacy --modern"
- end
-
- def description # :nodoc:
- <<-EOF
-The generate_index command creates a set of indexes for serving gems
-statically. The command expects a 'gems' directory under the path given to
-the --directory option. The given directory will be the directory you serve
-as the gem repository.
-
-For `gem generate_index --directory /path/to/repo`, expose /path/to/repo via
-your HTTP server configuration (not /path/to/repo/gems).
-
-When done, it will generate a set of files like this:
-
- gems/*.gem # .gem files you want to
- # index
-
- specs.<version>.gz # specs index
- latest_specs.<version>.gz # latest specs index
- prerelease_specs.<version>.gz # prerelease specs index
- quick/Marshal.<version>/<gemname>.gemspec.rz # Marshal quick index file
-
- # these files support legacy RubyGems
- Marshal.<version>
- Marshal.<version>.Z # Marshal full index
-
-The .Z and .rz extension files are compressed with the inflate algorithm.
-The Marshal version number comes from ruby's Marshal::MAJOR_VERSION and
-Marshal::MINOR_VERSION constants. It is used to ensure compatibility.
-
-If --rss-host and --rss-gem-host are given an RSS feed will be generated at
-index.rss containing gems released in the last two days.
- EOF
- end
-
- def execute
- if options[:update] and
- (options[:rss_host] or options[:rss_gems_host]) then
- alert_error '--update not compatible with RSS generation'
- terminate_interaction 1
- end
-
- if not File.exist?(options[:directory]) or
- not File.directory?(options[:directory]) then
- alert_error "unknown directory name #{directory}."
- terminate_interaction 1
- else
- indexer = Gem::Indexer.new options.delete(:directory), options
-
- if options[:update] then
- indexer.update_index
- else
- indexer.generate_index
- end
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/commands/help_command.rb b/ruby_1_9_3/lib/rubygems/commands/help_command.rb
deleted file mode 100644
index 20b52429b2..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/help_command.rb
+++ /dev/null
@@ -1,167 +0,0 @@
-require 'rubygems/command'
-
-class Gem::Commands::HelpCommand < Gem::Command
-
- # :stopdoc:
- EXAMPLES = <<-EOF
-Some examples of 'gem' usage.
-
-* Install 'rake', either from local directory or remote server:
-
- gem install rake
-
-* Install 'rake', only from remote server:
-
- gem install rake --remote
-
-* Install 'rake', but only version 0.3.1, even if dependencies
- are not met, and into a user-specific directory:
-
- gem install rake --version 0.3.1 --force --user-install
-
-* List local gems whose name begins with 'D':
-
- gem list D
-
-* List local and remote gems whose name contains 'log':
-
- gem search log --both
-
-* List only remote gems whose name contains 'log':
-
- gem search log --remote
-
-* Uninstall 'rake':
-
- gem uninstall rake
-
-* Create a gem:
-
- See http://rubygems.rubyforge.org/wiki/wiki.pl?CreateAGemInTenMinutes
-
-* See information about RubyGems:
-
- gem environment
-
-* Update all gems on your system:
-
- gem update
- EOF
-
- PLATFORMS = <<-'EOF'
-RubyGems platforms are composed of three parts, a CPU, an OS, and a
-version. These values are taken from values in rbconfig.rb. You can view
-your current platform by running `gem environment`.
-
-RubyGems matches platforms as follows:
-
- * The CPU must match exactly, unless one of the platforms has
- "universal" as the CPU.
- * The OS must match exactly.
- * The versions must match exactly unless one of the versions is nil.
-
-For commands that install, uninstall and list gems, you can override what
-RubyGems thinks your platform is with the --platform option. The platform
-you pass must match "#{cpu}-#{os}" or "#{cpu}-#{os}-#{version}". On mswin
-platforms, the version is the compiler version, not the OS version. (Ruby
-compiled with VC6 uses "60" as the compiler version, VC8 uses "80".)
-
-Example platforms:
-
- x86-freebsd # Any FreeBSD version on an x86 CPU
- universal-darwin-8 # Darwin 8 only gems that run on any CPU
- x86-mswin32-80 # Windows gems compiled with VC8
-
-When building platform gems, set the platform in the gem specification to
-Gem::Platform::CURRENT. This will correctly mark the gem with your ruby's
-platform.
- EOF
- # :startdoc:
-
- def initialize
- super 'help', "Provide help on the 'gem' command"
- end
-
- def arguments # :nodoc:
- args = <<-EOF
- commands List all 'gem' commands
- examples Show examples of 'gem' usage
- <command> Show specific help for <command>
- EOF
- return args.gsub(/^\s+/, '')
- end
-
- def usage # :nodoc:
- "#{program_name} ARGUMENT"
- end
-
- def execute
- command_manager = Gem::CommandManager.instance
- arg = options[:args][0]
-
- if begins? "commands", arg then
- out = []
- out << "GEM commands are:"
- out << nil
-
- margin_width = 4
-
- desc_width = command_manager.command_names.map { |n| n.size }.max + 4
-
- summary_width = 80 - margin_width - desc_width
- wrap_indent = ' ' * (margin_width + desc_width)
- format = "#{' ' * margin_width}%-#{desc_width}s%s"
-
- command_manager.command_names.each do |cmd_name|
- summary = command_manager[cmd_name].summary
- summary = wrap(summary, summary_width).split "\n"
- out << sprintf(format, cmd_name, summary.shift)
- until summary.empty? do
- out << "#{wrap_indent}#{summary.shift}"
- end
- end
-
- out << nil
- out << "For help on a particular command, use 'gem help COMMAND'."
- out << nil
- out << "Commands may be abbreviated, so long as they are unambiguous."
- out << "e.g. 'gem i rake' is short for 'gem install rake'."
-
- say out.join("\n")
-
- elsif begins? "options", arg then
- say Gem::Command::HELP
-
- elsif begins? "examples", arg then
- say EXAMPLES
-
- elsif begins? "platforms", arg then
- say PLATFORMS
-
- elsif options[:help] then
- command = command_manager[options[:help]]
- if command
- # help with provided command
- command.invoke("--help")
- else
- alert_error "Unknown command #{options[:help]}. Try 'gem help commands'"
- end
-
- elsif arg then
- possibilities = command_manager.find_command_possibilities(arg.downcase)
- if possibilities.size == 1
- command = command_manager[possibilities.first]
- command.invoke("--help")
- elsif possibilities.size > 1
- alert_warning "Ambiguous command #{arg} (#{possibilities.join(', ')})"
- else
- alert_warning "Unknown command #{arg}. Try gem help commands"
- end
-
- else
- say Gem::Command::HELP
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/commands/install_command.rb b/ruby_1_9_3/lib/rubygems/commands/install_command.rb
deleted file mode 100644
index 003ba8601c..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/install_command.rb
+++ /dev/null
@@ -1,165 +0,0 @@
-require 'rubygems/command'
-require 'rubygems/doc_manager'
-require 'rubygems/install_update_options'
-require 'rubygems/dependency_installer'
-require 'rubygems/local_remote_options'
-require 'rubygems/validator'
-require 'rubygems/version_option'
-
-##
-# Gem installer command line tool
-#
-# See `gem help install`
-
-class Gem::Commands::InstallCommand < Gem::Command
-
- include Gem::VersionOption
- include Gem::LocalRemoteOptions
- include Gem::InstallUpdateOptions
-
- def initialize
- defaults = Gem::DependencyInstaller::DEFAULT_OPTIONS.merge({
- :generate_rdoc => true,
- :generate_ri => true,
- :format_executable => false,
- :version => Gem::Requirement.default,
- })
-
- super 'install', 'Install a gem into the local repository', defaults
-
- add_install_update_options
- add_local_remote_options
- add_platform_option
- add_version_option
- add_prerelease_option "to be installed. (Only for listed gems)"
- end
-
- def arguments # :nodoc:
- "GEMNAME name of gem to install"
- end
-
- def defaults_str # :nodoc:
- "--both --version '#{Gem::Requirement.default}' --rdoc --ri --no-force\n" \
- "--install-dir #{Gem.dir}"
- end
-
- def description # :nodoc:
- <<-EOF
-The install command installs local or remote gem into a gem repository.
-
-For gems with executables ruby installs a wrapper file into the executable
-directory by default. This can be overridden with the --no-wrappers option.
-The wrapper allows you to choose among alternate gem versions using _version_.
-
-For example `rake _0.7.3_ --version` will run rake version 0.7.3 if a newer
-version is also installed.
-
-If an extension fails to compile during gem installation the gem
-specification is not written out, but the gem remains unpacked in the
-repository. You may need to specify the path to the library's headers and
-libraries to continue. You can do this by adding a -- between RubyGems'
-options and the extension's build options:
-
- $ gem install some_extension_gem
- [build fails]
- Gem files will remain installed in \\
- /path/to/gems/some_extension_gem-1.0 for inspection.
- Results logged to /path/to/gems/some_extension_gem-1.0/gem_make.out
- $ gem install some_extension_gem -- --with-extension-lib=/path/to/lib
- [build succeeds]
- $ gem list some_extension_gem
-
- *** LOCAL GEMS ***
-
- some_extension_gem (1.0)
- $
-
-If you correct the compilation errors by editing the gem files you will need
-to write the specification by hand. For example:
-
- $ gem install some_extension_gem
- [build fails]
- Gem files will remain installed in \\
- /path/to/gems/some_extension_gem-1.0 for inspection.
- Results logged to /path/to/gems/some_extension_gem-1.0/gem_make.out
- $ [cd /path/to/gems/some_extension_gem-1.0]
- $ [edit files or what-have-you and run make]
- $ gem spec ../../cache/some_extension_gem-1.0.gem --ruby > \\
- ../../specifications/some_extension_gem-1.0.gemspec
- $ gem list some_extension_gem
-
- *** LOCAL GEMS ***
-
- some_extension_gem (1.0)
- $
-
- EOF
- end
-
- def usage # :nodoc:
- "#{program_name} GEMNAME [GEMNAME ...] [options] -- --build-flags"
- end
-
- def execute
- if options[:include_dependencies] then
- alert "`gem install -y` is now default and will be removed"
- alert "use --ignore-dependencies to install only the gems you list"
- end
-
- installed_gems = []
-
- ENV.delete 'GEM_PATH' if options[:install_dir].nil? and RUBY_VERSION > '1.9'
-
- exit_code = 0
-
- get_all_gem_names.each do |gem_name|
- begin
- next if options[:conservative] and
- not Gem::Dependency.new(gem_name, options[:version]).matching_specs.empty?
-
- inst = Gem::DependencyInstaller.new options
- inst.install gem_name, options[:version]
-
- inst.installed_gems.each do |spec|
- say "Successfully installed #{spec.full_name}"
- end
-
- installed_gems.push(*inst.installed_gems)
- rescue Gem::InstallError => e
- alert_error "Error installing #{gem_name}:\n\t#{e.message}"
- exit_code |= 1
- rescue Gem::GemNotFoundException => e
- show_lookup_failure e.name, e.version, e.errors, options[:domain]
-
- exit_code |= 2
- end
- end
-
- unless installed_gems.empty? then
- gems = installed_gems.length == 1 ? 'gem' : 'gems'
- say "#{installed_gems.length} #{gems} installed"
-
- # NOTE: *All* of the RI documents must be generated first. For some
- # reason, RI docs cannot be generated after any RDoc documents are
- # generated.
-
- if options[:generate_ri] then
- installed_gems.each do |gem|
- Gem::DocManager.new(gem, options[:rdoc_args]).generate_ri
- end
-
- Gem::DocManager.update_ri_cache
- end
-
- if options[:generate_rdoc] then
- installed_gems.each do |gem|
- Gem::DocManager.new(gem, options[:rdoc_args]).generate_rdoc
- end
- end
- end
-
- raise Gem::SystemExitException, exit_code
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/commands/list_command.rb b/ruby_1_9_3/lib/rubygems/commands/list_command.rb
deleted file mode 100644
index f3e5da9551..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/list_command.rb
+++ /dev/null
@@ -1,35 +0,0 @@
-require 'rubygems/command'
-require 'rubygems/commands/query_command'
-
-##
-# An alternate to Gem::Commands::QueryCommand that searches for gems starting
-# with the the supplied argument.
-
-class Gem::Commands::ListCommand < Gem::Commands::QueryCommand
-
- def initialize
- super 'list', 'Display gems whose name starts with STRING'
-
- remove_option('--name-matches')
- end
-
- def arguments # :nodoc:
- "STRING start of gem name to look for"
- end
-
- def defaults_str # :nodoc:
- "--local --no-details"
- end
-
- def usage # :nodoc:
- "#{program_name} [STRING]"
- end
-
- def execute
- string = get_one_optional_argument || ''
- options[:name] = /^#{string}/i
- super
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/commands/lock_command.rb b/ruby_1_9_3/lib/rubygems/commands/lock_command.rb
deleted file mode 100644
index a6dca320ef..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/lock_command.rb
+++ /dev/null
@@ -1,110 +0,0 @@
-require 'rubygems/command'
-
-class Gem::Commands::LockCommand < Gem::Command
-
- def initialize
- super 'lock', 'Generate a lockdown list of gems',
- :strict => false
-
- add_option '-s', '--[no-]strict',
- 'fail if unable to satisfy a dependency' do |strict, options|
- options[:strict] = strict
- end
- end
-
- def arguments # :nodoc:
- "GEMNAME name of gem to lock\nVERSION version of gem to lock"
- end
-
- def defaults_str # :nodoc:
- "--no-strict"
- end
-
- def description # :nodoc:
- <<-EOF
-The lock command will generate a list of +gem+ statements that will lock down
-the versions for the gem given in the command line. It will specify exact
-versions in the requirements list to ensure that the gems loaded will always
-be consistent. A full recursive search of all effected gems will be
-generated.
-
-Example:
-
- gemlock rails-1.0.0 > lockdown.rb
-
-will produce in lockdown.rb:
-
- require "rubygems"
- gem 'rails', '= 1.0.0'
- gem 'rake', '= 0.7.0.1'
- gem 'activesupport', '= 1.2.5'
- gem 'activerecord', '= 1.13.2'
- gem 'actionpack', '= 1.11.2'
- gem 'actionmailer', '= 1.1.5'
- gem 'actionwebservice', '= 1.0.0'
-
-Just load lockdown.rb from your application to ensure that the current
-versions are loaded. Make sure that lockdown.rb is loaded *before* any
-other require statements.
-
-Notice that rails 1.0.0 only requires that rake 0.6.2 or better be used.
-Rake-0.7.0.1 is the most recent version installed that satisfies that, so we
-lock it down to the exact version.
- EOF
- end
-
- def usage # :nodoc:
- "#{program_name} GEMNAME-VERSION [GEMNAME-VERSION ...]"
- end
-
- def complain(message)
- if options[:strict] then
- raise Gem::Exception, message
- else
- say "# #{message}"
- end
- end
-
- def execute
- say "require 'rubygems'"
-
- locked = {}
-
- pending = options[:args]
-
- until pending.empty? do
- full_name = pending.shift
-
- spec = Gem::Specification.load spec_path(full_name)
-
- if spec.nil? then
- complain "Could not find gem #{full_name}, try using the full name"
- next
- end
-
- say "gem '#{spec.name}', '= #{spec.version}'" unless locked[spec.name]
- locked[spec.name] = true
-
- spec.runtime_dependencies.each do |dep|
- next if locked[dep.name]
- candidates = dep.matching_specs
-
- if candidates.empty? then
- complain "Unable to satisfy '#{dep}' from currently installed gems"
- else
- pending << candidates.last.full_name
- end
- end
- end
- end
-
- def spec_path(gem_full_name)
- gemspecs = Gem.path.map { |path|
- File.join path, "specifications", "#{gem_full_name}.gemspec"
- }
-
- gemspecs.find { |path| File.exist? path }
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/commands/outdated_command.rb b/ruby_1_9_3/lib/rubygems/commands/outdated_command.rb
deleted file mode 100644
index ea6b9f0abf..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/outdated_command.rb
+++ /dev/null
@@ -1,30 +0,0 @@
-require 'rubygems/command'
-require 'rubygems/local_remote_options'
-require 'rubygems/spec_fetcher'
-require 'rubygems/version_option'
-
-class Gem::Commands::OutdatedCommand < Gem::Command
-
- include Gem::LocalRemoteOptions
- include Gem::VersionOption
-
- def initialize
- super 'outdated', 'Display all gems that need updates'
-
- add_local_remote_options
- add_platform_option
- end
-
- def execute
- Gem::Specification.outdated.sort.each do |name|
- local = Gem::Specification.find_all_by_name(name).max
- dep = Gem::Dependency.new local.name, ">= #{local.version}"
- remotes = Gem::SpecFetcher.fetcher.fetch dep
-
- next if remotes.empty?
-
- remote = remotes.last.first
- say "#{local.name} (#{local.version} < #{remote.version})"
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rubygems/commands/owner_command.rb b/ruby_1_9_3/lib/rubygems/commands/owner_command.rb
deleted file mode 100644
index 6ebf9aa1aa..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/owner_command.rb
+++ /dev/null
@@ -1,76 +0,0 @@
-require 'rubygems/command'
-require 'rubygems/local_remote_options'
-require 'rubygems/gemcutter_utilities'
-
-class Gem::Commands::OwnerCommand < Gem::Command
- include Gem::LocalRemoteOptions
- include Gem::GemcutterUtilities
-
- def description # :nodoc:
- 'Manage gem owners on RubyGems.org.'
- end
-
- def arguments # :nodoc:
- "GEM gem to manage owners for"
- end
-
- def initialize
- super 'owner', description
- add_proxy_option
- add_key_option
- defaults.merge! :add => [], :remove => []
-
- add_option '-a', '--add EMAIL', 'Add an owner' do |value, options|
- options[:add] << value
- end
-
- add_option '-r', '--remove EMAIL', 'Remove an owner' do |value, options|
- options[:remove] << value
- end
- end
-
- def execute
- sign_in
- name = get_one_gem_name
-
- add_owners name, options[:add]
- remove_owners name, options[:remove]
- show_owners name
- end
-
- def show_owners name
- response = rubygems_api_request :get, "api/v1/gems/#{name}/owners.yaml" do |request|
- request.add_field "Authorization", api_key
- end
-
- with_response response do |resp|
- owners = YAML.load resp.body
-
- say "Owners for gem: #{name}"
- owners.each do |owner|
- say "- #{owner['email']}"
- end
- end
- end
-
- def add_owners name, owners
- manage_owners :post, name, owners
- end
-
- def remove_owners name, owners
- manage_owners :delete, name, owners
- end
-
- def manage_owners method, name, owners
- owners.each do |owner|
- response = rubygems_api_request method, "api/v1/gems/#{name}/owners" do |request|
- request.set_form_data 'email' => owner
- request.add_field "Authorization", api_key
- end
-
- with_response response
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/commands/pristine_command.rb b/ruby_1_9_3/lib/rubygems/commands/pristine_command.rb
deleted file mode 100644
index 83e6cc7a67..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/pristine_command.rb
+++ /dev/null
@@ -1,110 +0,0 @@
-require 'rubygems/command'
-require 'rubygems/format'
-require 'rubygems/installer'
-require 'rubygems/version_option'
-
-class Gem::Commands::PristineCommand < Gem::Command
-
- include Gem::VersionOption
-
- def initialize
- super 'pristine',
- 'Restores installed gems to pristine condition from files located in the gem cache',
- :version => Gem::Requirement.default, :extensions => true,
- :all => false
-
- add_option('--all',
- 'Restore all installed gems to pristine',
- 'condition') do |value, options|
- options[:all] = value
- end
-
- add_option('--[no-]extensions',
- 'Restore gems with extensions') do |value, options|
- options[:extensions] = value
- end
-
- add_version_option('restore to', 'pristine condition')
- end
-
- def arguments # :nodoc:
- "GEMNAME gem to restore to pristine condition (unless --all)"
- end
-
- def defaults_str # :nodoc:
- "--all --extensions"
- end
-
- def description # :nodoc:
- <<-EOF
-The pristine command compares the installed gems with the contents of the
-cached gem and restores any files that don't match the cached gem's copy.
-
-If you have made modifications to your installed gems, the pristine command
-will revert them. After all the gem's files have been checked all bin stubs
-for the gem are regenerated.
-
-If the cached gem cannot be found, you will need to use `gem install` to
-revert the gem.
-
-If --no-extensions is provided pristine will not attempt to restore gems with
-extensions.
- EOF
- end
-
- def usage # :nodoc:
- "#{program_name} [args]"
- end
-
- def execute
- specs = if options[:all] then
- Gem::Specification.map
- else
- get_all_gem_names.map do |gem_name|
- Gem::Specification.find_all_by_name gem_name, options[:version]
- end.flatten
- end
-
- if specs.to_a.empty? then
- raise Gem::Exception,
- "Failed to find gems #{options[:args]} #{options[:version]}"
- end
-
- install_dir = Gem.dir # TODO use installer option
-
- raise Gem::FilePermissionError.new(install_dir) unless
- File.writable?(install_dir)
-
- say "Restoring gems to pristine condition..."
-
- specs.each do |spec|
- unless spec.extensions.empty? or options[:extensions] then
- say "Skipped #{spec.full_name}, it needs to compile an extension"
- next
- end
-
- gem = spec.cache_file
-
- unless File.exist? gem then
- require 'rubygems/remote_fetcher'
-
- say "Cached gem for #{spec.full_name} not found, attempting to fetch..."
- dep = Gem::Dependency.new spec.name, spec.version
- Gem::RemoteFetcher.fetcher.download_to_cache dep
- end
-
- # TODO use installer options
- install_defaults = Gem::ConfigFile::PLATFORM_DEFAULTS['install']
- installer_env_shebang = install_defaults.to_s['--env-shebang']
-
- installer = Gem::Installer.new(gem,
- :wrappers => true,
- :force => true,
- :install_dir => spec.base_dir,
- :env_shebang => installer_env_shebang)
- installer.install
-
- say "Restored #{spec.full_name}"
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rubygems/commands/push_command.rb b/ruby_1_9_3/lib/rubygems/commands/push_command.rb
deleted file mode 100644
index a7663edf4a..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/push_command.rb
+++ /dev/null
@@ -1,60 +0,0 @@
-require 'rubygems/command'
-require 'rubygems/local_remote_options'
-require 'rubygems/gemcutter_utilities'
-
-class Gem::Commands::PushCommand < Gem::Command
- include Gem::LocalRemoteOptions
- include Gem::GemcutterUtilities
-
- def description # :nodoc:
- 'Push a gem up to RubyGems.org'
- end
-
- def arguments # :nodoc:
- "GEM built gem to push up"
- end
-
- def usage # :nodoc:
- "#{program_name} GEM"
- end
-
- def initialize
- super 'push', description
- add_proxy_option
- add_key_option
-
- add_option(
- '--host HOST',
- 'Push to another gemcutter-compatible host'
- ) do |value, options|
- options[:host] = value
- end
- end
-
- def execute
- sign_in
- send_gem get_one_gem_name
- end
-
- def send_gem name
- args = [:post, "api/v1/gems"]
-
- args << options[:host] if options[:host]
-
- if Gem.latest_rubygems_version < Gem::Version.new(Gem::VERSION) then
- alert_error "Using beta/unreleased version of rubygems. Not pushing."
- terminate_interaction 1
- end
-
- response = rubygems_api_request(*args) do |request|
- request.body = Gem.read_binary name
- request.add_field "Content-Length", request.body.size
- request.add_field "Content-Type", "application/octet-stream"
- request.add_field "Authorization", api_key
- end
-
- with_response response
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/commands/query_command.rb b/ruby_1_9_3/lib/rubygems/commands/query_command.rb
deleted file mode 100644
index 725da8787b..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/query_command.rb
+++ /dev/null
@@ -1,263 +0,0 @@
-require 'rubygems/command'
-require 'rubygems/local_remote_options'
-require 'rubygems/spec_fetcher'
-require 'rubygems/version_option'
-require 'rubygems/text'
-
-class Gem::Commands::QueryCommand < Gem::Command
-
- include Gem::Text
- include Gem::LocalRemoteOptions
- include Gem::VersionOption
-
- def initialize(name = 'query',
- summary = 'Query gem information in local or remote repositories')
- super name, summary,
- :name => //, :domain => :local, :details => false, :versions => true,
- :installed => false, :version => Gem::Requirement.default
-
- add_option('-i', '--[no-]installed',
- 'Check for installed gem') do |value, options|
- options[:installed] = value
- end
-
- add_version_option command, "for use with --installed"
-
- add_option('-n', '--name-matches REGEXP',
- 'Name of gem(s) to query on matches the',
- 'provided REGEXP') do |value, options|
- options[:name] = /#{value}/i
- end
-
- add_option('-d', '--[no-]details',
- 'Display detailed information of gem(s)') do |value, options|
- options[:details] = value
- end
-
- add_option( '--[no-]versions',
- 'Display only gem names') do |value, options|
- options[:versions] = value
- options[:details] = false unless value
- end
-
- add_option('-a', '--all',
- 'Display all gem versions') do |value, options|
- options[:all] = value
- end
-
- add_option( '--[no-]prerelease',
- 'Display prerelease versions') do |value, options|
- options[:prerelease] = value
- end
-
- add_local_remote_options
- end
-
- def defaults_str # :nodoc:
- "--local --name-matches // --no-details --versions --no-installed"
- end
-
- def execute
- exit_code = 0
-
- name = options[:name]
- prerelease = options[:prerelease]
-
- if options[:installed] then
- if name.source.empty? then
- alert_error "You must specify a gem name"
- exit_code |= 4
- elsif installed? name, options[:version] then
- say "true"
- else
- say "false"
- exit_code |= 1
- end
-
- terminate_interaction exit_code
- end
-
- req = Gem::Requirement.default
- # TODO: deprecate for real
- dep = Gem::Deprecate.skip_during { Gem::Dependency.new name, req }
-
- if local? then
- if prerelease and not both? then
- alert_warning "prereleases are always shown locally"
- end
-
- if ui.outs.tty? or both? then
- say
- say "*** LOCAL GEMS ***"
- say
- end
-
- specs = Gem::Specification.find_all { |s|
- s.name =~ name and req =~ s.version
- }
-
- spec_tuples = specs.map do |spec|
- [[spec.name, spec.version, spec.original_platform, spec], :local]
- end
-
- output_query_results spec_tuples
- end
-
- if remote? then
- if ui.outs.tty? or both? then
- say
- say "*** REMOTE GEMS ***"
- say
- end
-
- all = options[:all]
-
- fetcher = Gem::SpecFetcher.fetcher
- spec_tuples = fetcher.find_matching dep, all, false, prerelease
-
- spec_tuples += fetcher.find_matching dep, false, false, true if
- prerelease and all
-
- output_query_results spec_tuples
- end
- end
-
- private
-
- ##
- # Check if gem +name+ version +version+ is installed.
-
- def installed?(name, req = Gem::Requirement.default)
- Gem::Specification.any? { |s| s.name =~ name and req =~ s.version }
- end
-
- def output_query_results(spec_tuples)
- output = []
- versions = Hash.new { |h,name| h[name] = [] }
-
- spec_tuples.each do |spec_tuple, source_uri|
- versions[spec_tuple.first] << [spec_tuple, source_uri]
- end
-
- versions = versions.sort_by do |(name,_),_|
- name.downcase
- end
-
- versions.each do |gem_name, matching_tuples|
- matching_tuples = matching_tuples.sort_by do |(_, version,_),_|
- version
- end.reverse
-
- platforms = Hash.new { |h,version| h[version] = [] }
-
- matching_tuples.map do |(_, version, platform,_),_|
- platforms[version] << platform if platform
- end
-
- seen = {}
-
- matching_tuples.delete_if do |(_, version,_),_|
- if seen[version] then
- true
- else
- seen[version] = true
- false
- end
- end
-
- entry = gem_name.dup
-
- if options[:versions] then
- list = if platforms.empty? or options[:details] then
- matching_tuples.map { |(_, version,_),_| version }.uniq
- else
- platforms.sort.reverse.map do |version, pls|
- if pls == [Gem::Platform::RUBY] then
- version
- else
- ruby = pls.delete Gem::Platform::RUBY
- platform_list = [ruby, *pls.sort].compact
- "#{version} #{platform_list.join ' '}"
- end
- end
- end.join ', '
-
- entry << " (#{list})"
- end
-
- if options[:details] then
- detail_tuple = matching_tuples.first
-
- spec = if detail_tuple.first.length == 4 then
- detail_tuple.first.last
- else
- uri = URI.parse detail_tuple.last
- Gem::SpecFetcher.fetcher.fetch_spec detail_tuple.first, uri
- end
-
- entry << "\n"
-
- non_ruby = platforms.any? do |_, pls|
- pls.any? { |pl| pl != Gem::Platform::RUBY }
- end
-
- if non_ruby then
- if platforms.length == 1 then
- title = platforms.values.length == 1 ? 'Platform' : 'Platforms'
- entry << " #{title}: #{platforms.values.sort.join ', '}\n"
- else
- entry << " Platforms:\n"
- platforms.sort_by do |version,|
- version
- end.each do |version, pls|
- label = " #{version}: "
- data = format_text pls.sort.join(', '), 68, label.length
- data[0, label.length] = label
- entry << data << "\n"
- end
- end
- end
-
- authors = "Author#{spec.authors.length > 1 ? 's' : ''}: "
- authors << spec.authors.join(', ')
- entry << format_text(authors, 68, 4)
-
- if spec.rubyforge_project and not spec.rubyforge_project.empty? then
- rubyforge = "Rubyforge: http://rubyforge.org/projects/#{spec.rubyforge_project}"
- entry << "\n" << format_text(rubyforge, 68, 4)
- end
-
- if spec.homepage and not spec.homepage.empty? then
- entry << "\n" << format_text("Homepage: #{spec.homepage}", 68, 4)
- end
-
- if spec.license and not spec.license.empty? then
- licenses = "License#{spec.licenses.length > 1 ? 's' : ''}: "
- licenses << spec.licenses.join(', ')
- entry << "\n" << format_text(licenses, 68, 4)
- end
-
- if spec.loaded_from then
- if matching_tuples.length == 1 then
- loaded_from = File.dirname File.dirname(spec.loaded_from)
- entry << "\n" << " Installed at: #{loaded_from}"
- else
- label = 'Installed at'
- matching_tuples.each do |(_,version,_,s),|
- loaded_from = File.dirname File.dirname(s.loaded_from)
- entry << "\n" << " #{label} (#{version}): #{loaded_from}"
- label = ' ' * label.length
- end
- end
- end
-
- entry << "\n\n" << format_text(spec.summary, 68, 4)
- end
- output << entry
- end
-
- say output.join(options[:details] ? "\n\n" : "\n")
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/commands/rdoc_command.rb b/ruby_1_9_3/lib/rubygems/commands/rdoc_command.rb
deleted file mode 100644
index ea0f3ad592..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/rdoc_command.rb
+++ /dev/null
@@ -1,91 +0,0 @@
-require 'rubygems/command'
-require 'rubygems/version_option'
-require 'rubygems/doc_manager'
-
-class Gem::Commands::RdocCommand < Gem::Command
- include Gem::VersionOption
-
- def initialize
- super 'rdoc', 'Generates RDoc for pre-installed gems',
- :version => Gem::Requirement.default,
- :include_rdoc => true, :include_ri => true, :overwrite => false
-
- add_option('--all',
- 'Generate RDoc/RI documentation for all',
- 'installed gems') do |value, options|
- options[:all] = value
- end
-
- add_option('--[no-]rdoc',
- 'Generate RDoc HTML') do |value, options|
- options[:include_rdoc] = value
- end
-
- add_option('--[no-]ri',
- 'Generate RI data') do |value, options|
- options[:include_ri] = value
- end
-
- add_option('--[no-]overwrite',
- 'Overwrite installed documents') do |value, options|
- options[:overwrite] = value
- end
-
- add_version_option
- end
-
- def arguments # :nodoc:
- "GEMNAME gem to generate documentation for (unless --all)"
- end
-
- def defaults_str # :nodoc:
- "--version '#{Gem::Requirement.default}' --rdoc --ri --no-overwrite"
- end
-
- def description # :nodoc:
- <<-DESC
-The rdoc command builds RDoc and RI documentation for installed gems. Use
---overwrite to force rebuilding of documentation.
- DESC
- end
-
- def usage # :nodoc:
- "#{program_name} [args]"
- end
-
- def execute
- if options[:all] then
- specs = Gem::SourceIndex.from_installed_gems.collect { |name, spec|
- spec
- }
- else
- gem_name = get_one_gem_name
- dep = Gem::Dependency.new gem_name, options[:version]
- specs = Gem::SourceIndex.from_installed_gems.search dep
- end
-
- if specs.empty?
- raise "Failed to find gem #{gem_name} to generate RDoc for #{options[:version]}"
- end
-
- if options[:include_ri]
- specs.sort.each do |spec|
- doc = Gem::DocManager.new(spec)
- doc.generate_ri if options[:overwrite] || !doc.ri_installed?
- end
-
- Gem::DocManager.update_ri_cache
- end
-
- if options[:include_rdoc]
- specs.sort.each do |spec|
- doc = Gem::DocManager.new(spec)
- doc.generate_rdoc if options[:overwrite] || !doc.rdoc_installed?
- end
- end
-
- true
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/commands/search_command.rb b/ruby_1_9_3/lib/rubygems/commands/search_command.rb
deleted file mode 100644
index 52e96fd1ef..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/search_command.rb
+++ /dev/null
@@ -1,31 +0,0 @@
-require 'rubygems/command'
-require 'rubygems/commands/query_command'
-
-class Gem::Commands::SearchCommand < Gem::Commands::QueryCommand
-
- def initialize
- super 'search', 'Display all gems whose name contains STRING'
-
- remove_option '--name-matches'
- end
-
- def arguments # :nodoc:
- "STRING fragment of gem name to search for"
- end
-
- def defaults_str # :nodoc:
- "--local --no-details"
- end
-
- def usage # :nodoc:
- "#{program_name} [STRING]"
- end
-
- def execute
- string = get_one_optional_argument
- options[:name] = /#{string}/i
- super
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/commands/server_command.rb b/ruby_1_9_3/lib/rubygems/commands/server_command.rb
deleted file mode 100644
index b65d48c4fc..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/server_command.rb
+++ /dev/null
@@ -1,86 +0,0 @@
-require 'rubygems/command'
-require 'rubygems/server'
-
-class Gem::Commands::ServerCommand < Gem::Command
-
- def initialize
- super 'server', 'Documentation and gem repository HTTP server',
- :port => 8808, :gemdir => [], :daemon => false
-
- OptionParser.accept :Port do |port|
- if port =~ /\A\d+\z/ then
- port = Integer port
- raise OptionParser::InvalidArgument, "#{port}: not a port number" if
- port > 65535
-
- port
- else
- begin
- Socket.getservbyname port
- rescue SocketError
- raise OptionParser::InvalidArgument, "#{port}: no such named service"
- end
- end
- end
-
- add_option '-p', '--port=PORT', :Port,
- 'port to listen on' do |port, options|
- options[:port] = port
- end
-
- add_option '-d', '--dir=GEMDIR',
- 'directories from which to serve gems',
- 'multiple directories may be provided' do |gemdir, options|
- options[:gemdir] << File.expand_path(gemdir)
- end
-
- add_option '--[no-]daemon', 'run as a daemon' do |daemon, options|
- options[:daemon] = daemon
- end
-
- add_option '-b', '--bind=HOST,HOST',
- 'addresses to bind', Array do |address, options|
- options[:addresses] ||= []
- options[:addresses].push(*address)
- end
-
- add_option '-l', '--launch[=COMMAND]',
- 'launches a browser window',
- "COMMAND defaults to 'start' on Windows",
- "and 'open' on all other platforms" do |launch, options|
- launch ||= Gem.win_platform? ? 'start' : 'open'
- options[:launch] = launch
- end
- end
-
- def defaults_str # :nodoc:
- "--port 8808 --dir #{Gem.dir} --no-daemon"
- end
-
- def description # :nodoc:
- <<-EOF
-The server command starts up a web server that hosts the RDoc for your
-installed gems and can operate as a server for installation of gems on other
-machines.
-
-The cache files for installed gems must exist to use the server as a source
-for gem installation.
-
-To install gems from a running server, use `gem install GEMNAME --source
-http://gem_server_host:8808`
-
-You can set up a shortcut to gem server documentation using the URL:
-
- http://localhost:8808/rdoc?q=%s - Firefox
- http://localhost:8808/rdoc?q=* - LaunchBar
-
- EOF
- end
-
- def execute
- options[:gemdir] << Gem.dir if options[:gemdir].empty?
- Gem::Server.run options
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/commands/setup_command.rb b/ruby_1_9_3/lib/rubygems/commands/setup_command.rb
deleted file mode 100644
index 0c957393d9..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/setup_command.rb
+++ /dev/null
@@ -1,358 +0,0 @@
-require 'rubygems/command'
-
-##
-# Installs RubyGems itself. This command is ordinarily only available from a
-# RubyGems checkout or tarball.
-
-class Gem::Commands::SetupCommand < Gem::Command
-
- def initialize
- require 'tmpdir'
-
- super 'setup', 'Install RubyGems',
- :format_executable => true, :rdoc => true, :ri => true,
- :site_or_vendor => :sitelibdir,
- :destdir => '', :prefix => ''
-
- add_option '--prefix=PREFIX',
- 'Prefix path for installing RubyGems',
- 'Will not affect gem repository location' do |prefix, options|
- options[:prefix] = File.expand_path prefix
- end
-
- add_option '--destdir=DESTDIR',
- 'Root directory to install RubyGems into',
- 'Mainly used for packaging RubyGems' do |destdir, options|
- options[:destdir] = File.expand_path destdir
- end
-
- add_option '--[no-]vendor',
- 'Install into vendorlibdir not sitelibdir' do |vendor, options|
- options[:site_or_vendor] = vendor ? :vendorlibdir : :sitelibdir
- end
-
- add_option '--[no-]format-executable',
- 'Makes `gem` match ruby',
- 'If ruby is ruby18, gem will be gem18' do |value, options|
- options[:format_executable] = value
- end
-
- add_option '--[no-]rdoc',
- 'Generate RDoc documentation for RubyGems' do |value, options|
- options[:rdoc] = value
- end
-
- add_option '--[no-]ri',
- 'Generate RI documentation for RubyGems' do |value, options|
- options[:ri] = value
- end
- end
-
- def check_ruby_version
- required_version = Gem::Requirement.new '>= 1.8.7'
-
- unless required_version.satisfied_by? Gem.ruby_version then
- alert_error "Expected Ruby version #{required_version}, is #{Gem.ruby_version}"
- terminate_interaction 1
- end
- end
-
- def defaults_str # :nodoc:
- "--format-executable --rdoc --ri"
- end
-
- def description # :nodoc:
- <<-EOF
-Installs RubyGems itself.
-
-RubyGems installs RDoc for itself in GEM_HOME. By default this is:
- #{Gem.dir}
-
-If you prefer a different directory, set the GEM_HOME environment variable.
-
-RubyGems will install the gem command with a name matching ruby's
-prefix and suffix. If ruby was installed as `ruby18`, gem will be
-installed as `gem18`.
-
-By default, this RubyGems will install gem as:
- #{Gem.default_exec_format % 'gem'}
- EOF
- end
-
- def execute
- @verbose = Gem.configuration.really_verbose
-
- install_destdir = options[:destdir]
-
- unless install_destdir.empty? then
- ENV['GEM_HOME'] ||= File.join(install_destdir,
- Gem.default_dir.gsub(/^[a-zA-Z]:/, ''))
- end
-
- check_ruby_version
-
- require 'fileutils'
- if Gem.configuration.really_verbose then
- extend FileUtils::Verbose
- else
- extend FileUtils
- end
-
- lib_dir, bin_dir = make_destination_dirs install_destdir
-
- install_lib lib_dir
-
- install_executables bin_dir
-
- remove_old_bin_files bin_dir
-
- say "RubyGems #{Gem::VERSION} installed"
-
- uninstall_old_gemcutter
-
- install_rdoc
-
- say
- if @verbose then
- say "-" * 78
- say
- end
-
- release_notes = File.join Dir.pwd, 'History.txt'
-
- release_notes = if File.exist? release_notes then
- open release_notes do |io|
- text = io.gets '==='
- text << io.gets('===')
- text[0...-3].sub(/^# coding:.*?^=/m, '')
- end
- else
- "Oh-no! Unable to find release notes!"
- end
-
- say release_notes
-
- say
- say "-" * 78
- say
-
- say "RubyGems installed the following executables:"
- say @bin_file_names.map { |name| "\t#{name}\n" }
- say
-
- unless @bin_file_names.grep(/#{File::SEPARATOR}gem$/) then
- say "If `gem` was installed by a previous RubyGems installation, you may need"
- say "to remove it by hand."
- say
- end
- end
-
- def install_executables(bin_dir)
- say "Installing gem executable" if @verbose
-
- @bin_file_names = []
-
- Dir.chdir 'bin' do
- bin_files = Dir['*']
-
- bin_files.delete 'update_rubygems'
-
- bin_files.each do |bin_file|
- bin_file_formatted = if options[:format_executable] then
- Gem.default_exec_format % bin_file
- else
- bin_file
- end
-
- dest_file = File.join bin_dir, bin_file_formatted
- bin_tmp_file = File.join Dir.tmpdir, bin_file
-
- begin
- bin = File.readlines bin_file
- bin[0] = "#!#{Gem.ruby}\n"
-
- File.open bin_tmp_file, 'w' do |fp|
- fp.puts bin.join
- end
-
- install bin_tmp_file, dest_file, :mode => 0755
- @bin_file_names << dest_file
- ensure
- rm bin_tmp_file
- end
-
- next unless Gem.win_platform?
-
- begin
- bin_cmd_file = File.join Dir.tmpdir, "#{bin_file}.bat"
-
- File.open bin_cmd_file, 'w' do |file|
- file.puts <<-TEXT
-@ECHO OFF
-IF NOT "%~f0" == "~f0" GOTO :WinNT
-@"#{File.basename(Gem.ruby).chomp('"')}" "#{dest_file}" %1 %2 %3 %4 %5 %6 %7 %8 %9
-GOTO :EOF
-:WinNT
-@"#{File.basename(Gem.ruby).chomp('"')}" "%~dpn0" %*
-TEXT
- end
-
- install bin_cmd_file, "#{dest_file}.bat", :mode => 0755
- ensure
- rm bin_cmd_file
- end
- end
- end
- end
-
- def install_lib(lib_dir)
- say "Installing RubyGems" if @verbose
-
- Dir.chdir 'lib' do
- lib_files = Dir[File.join('**', '*rb')]
-
- lib_files.each do |lib_file|
- dest_file = File.join lib_dir, lib_file
- dest_dir = File.dirname dest_file
- mkdir_p dest_dir unless File.directory? dest_dir
-
- install lib_file, dest_file, :mode => 0644
- end
- end
- end
-
- def install_rdoc
- gem_doc_dir = File.join Gem.dir, 'doc'
- rubygems_name = "rubygems-#{Gem::VERSION}"
- rubygems_doc_dir = File.join gem_doc_dir, rubygems_name
-
- if File.writable? gem_doc_dir and
- (not File.exist? rubygems_doc_dir or
- File.writable? rubygems_doc_dir) then
- say "Removing old RubyGems RDoc and ri" if @verbose
- Dir[File.join(Gem.dir, 'doc', 'rubygems-[0-9]*')].each do |dir|
- rm_rf dir
- end
-
- if options[:ri] then
- ri_dir = File.join rubygems_doc_dir, 'ri'
- say "Installing #{rubygems_name} ri into #{ri_dir}" if @verbose
- run_rdoc '--ri', '--op', ri_dir
- end
-
- if options[:rdoc] then
- rdoc_dir = File.join rubygems_doc_dir, 'rdoc'
- say "Installing #{rubygems_name} rdoc into #{rdoc_dir}" if @verbose
- run_rdoc '--op', rdoc_dir
- end
- elsif @verbose then
- say "Skipping RDoc generation, #{gem_doc_dir} not writable"
- say "Set the GEM_HOME environment variable if you want RDoc generated"
- end
- end
-
- def make_destination_dirs(install_destdir)
- lib_dir, bin_dir = Gem.default_rubygems_dirs
-
- unless lib_dir
- lib_dir, bin_dir = generate_default_dirs(install_destdir)
- end
-
- mkdir_p lib_dir
- mkdir_p bin_dir
-
- return lib_dir, bin_dir
- end
-
- def generate_default_dirs(install_destdir)
- prefix = options[:prefix]
- site_or_vendor = options[:site_or_vendor]
-
- if prefix.empty? then
- lib_dir = Gem::ConfigMap[site_or_vendor]
- bin_dir = Gem::ConfigMap[:bindir]
- else
- # Apple installed RubyGems into libdir, and RubyGems <= 1.1.0 gets
- # confused about installation location, so switch back to
- # sitelibdir/vendorlibdir.
- if defined?(APPLE_GEM_HOME) and
- # just in case Apple and RubyGems don't get this patched up proper.
- (prefix == Gem::ConfigMap[:libdir] or
- # this one is important
- prefix == File.join(Gem::ConfigMap[:libdir], 'ruby')) then
- lib_dir = Gem::ConfigMap[site_or_vendor]
- bin_dir = Gem::ConfigMap[:bindir]
- else
- lib_dir = File.join prefix, 'lib'
- bin_dir = File.join prefix, 'bin'
- end
- end
-
- unless install_destdir.empty? then
- lib_dir = File.join install_destdir, lib_dir.gsub(/^[a-zA-Z]:/, '')
- bin_dir = File.join install_destdir, bin_dir.gsub(/^[a-zA-Z]:/, '')
- end
-
- [lib_dir, bin_dir]
- end
-
- def remove_old_bin_files(bin_dir)
- old_bin_files = {
- 'gem_mirror' => 'gem mirror',
- 'gem_server' => 'gem server',
- 'gemlock' => 'gem lock',
- 'gemri' => 'ri',
- 'gemwhich' => 'gem which',
- 'index_gem_repository.rb' => 'gem generate_index',
- }
-
- old_bin_files.each do |old_bin_file, new_name|
- old_bin_path = File.join bin_dir, old_bin_file
- next unless File.exist? old_bin_path
-
- deprecation_message = "`#{old_bin_file}` has been deprecated. Use `#{new_name}` instead."
-
- File.open old_bin_path, 'w' do |fp|
- fp.write <<-EOF
-#!#{Gem.ruby}
-
-abort "#{deprecation_message}"
- EOF
- end
-
- next unless Gem.win_platform?
-
- File.open "#{old_bin_path}.bat", 'w' do |fp|
- fp.puts %{@ECHO.#{deprecation_message}}
- end
- end
- end
-
- def run_rdoc(*args)
- begin
- gem 'rdoc'
- rescue Gem::LoadError
- end
-
- require 'rdoc/rdoc'
-
- args << '--main' << 'README.rdoc' << '--quiet'
- args << '.'
- args << 'README.rdoc' << 'UPGRADING.rdoc'
- args << 'LICENSE.txt' << 'MIT.txt' << 'History.txt'
-
- r = RDoc::RDoc.new
- r.document args
- end
-
- def uninstall_old_gemcutter
- require 'rubygems/uninstaller'
-
- ui = Gem::Uninstaller.new('gemcutter', :all => true, :ignore => true,
- :version => '< 0.4')
- ui.uninstall
- rescue Gem::InstallError
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/commands/sources_command.rb b/ruby_1_9_3/lib/rubygems/commands/sources_command.rb
deleted file mode 100644
index ac14313e9d..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/sources_command.rb
+++ /dev/null
@@ -1,136 +0,0 @@
-require 'rubygems/command'
-require 'rubygems/remote_fetcher'
-require 'rubygems/spec_fetcher'
-require 'rubygems/local_remote_options'
-
-class Gem::Commands::SourcesCommand < Gem::Command
-
- include Gem::LocalRemoteOptions
-
- def initialize
- require 'fileutils'
-
- super 'sources',
- 'Manage the sources and cache file RubyGems uses to search for gems'
-
- add_option '-a', '--add SOURCE_URI', 'Add source' do |value, options|
- options[:add] = value
- end
-
- add_option '-l', '--list', 'List sources' do |value, options|
- options[:list] = value
- end
-
- add_option '-r', '--remove SOURCE_URI', 'Remove source' do |value, options|
- options[:remove] = value
- end
-
- add_option '-c', '--clear-all',
- 'Remove all sources (clear the cache)' do |value, options|
- options[:clear_all] = value
- end
-
- add_option '-u', '--update', 'Update source cache' do |value, options|
- options[:update] = value
- end
-
- add_proxy_option
- end
-
- def defaults_str
- '--list'
- end
-
- def execute
- options[:list] = !(options[:add] ||
- options[:clear_all] ||
- options[:remove] ||
- options[:update])
-
- if options[:clear_all] then
- path = Gem::SpecFetcher.fetcher.dir
- FileUtils.rm_rf path
-
- unless File.exist? path then
- say "*** Removed specs cache ***"
- else
- unless File.writable? path then
- say "*** Unable to remove source cache (write protected) ***"
- else
- say "*** Unable to remove source cache ***"
- end
-
- terminate_interaction 1
- end
- end
-
- if options[:add] then
- source_uri = options[:add]
- uri = URI.parse source_uri
-
- begin
- Gem::SpecFetcher.fetcher.load_specs uri, 'specs'
- Gem.sources << source_uri
- Gem.configuration.write
-
- say "#{source_uri} added to sources"
- rescue URI::Error, ArgumentError
- say "#{source_uri} is not a URI"
- terminate_interaction 1
- rescue Gem::RemoteFetcher::FetchError => e
- say "Error fetching #{source_uri}:\n\t#{e.message}"
- terminate_interaction 1
- end
- end
-
- if options[:remove] then
- source_uri = options[:remove]
-
- unless Gem.sources.include? source_uri then
- say "source #{source_uri} not present in cache"
- else
- Gem.sources.delete source_uri
- Gem.configuration.write
-
- say "#{source_uri} removed from sources"
- end
- end
-
- if options[:update] then
- fetcher = Gem::SpecFetcher.fetcher
-
- Gem.sources.each do |update_uri|
- update_uri = URI.parse update_uri
- fetcher.load_specs update_uri, 'specs'
- fetcher.load_specs update_uri, 'latest_specs'
- end
-
- say "source cache successfully updated"
- end
-
- if options[:list] then
- say "*** CURRENT SOURCES ***"
- say
-
- Gem.sources.each do |source|
- say source
- end
- end
- end
-
- private
-
- def remove_cache_file(desc, path)
- FileUtils.rm_rf path
-
- if not File.exist?(path) then
- say "*** Removed #{desc} source cache ***"
- elsif not File.writable?(path) then
- say "*** Unable to remove #{desc} source cache (write protected) ***"
- else
- say "*** Unable to remove #{desc} source cache ***"
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/commands/specification_command.rb b/ruby_1_9_3/lib/rubygems/commands/specification_command.rb
deleted file mode 100644
index 566a9cc66e..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/specification_command.rb
+++ /dev/null
@@ -1,131 +0,0 @@
-require 'rubygems/command'
-require 'rubygems/local_remote_options'
-require 'rubygems/version_option'
-require 'rubygems/format'
-
-class Gem::Commands::SpecificationCommand < Gem::Command
-
- include Gem::LocalRemoteOptions
- include Gem::VersionOption
-
- def initialize
- Gem.load_yaml
-
- super 'specification', 'Display gem specification (in yaml)',
- :domain => :local, :version => Gem::Requirement.default,
- :format => :yaml
-
- add_version_option('examine')
- add_platform_option
-
- add_option('--all', 'Output specifications for all versions of',
- 'the gem') do |value, options|
- options[:all] = true
- end
-
- add_option('--ruby', 'Output ruby format') do |value, options|
- options[:format] = :ruby
- end
-
- add_option('--yaml', 'Output RUBY format') do |value, options|
- options[:format] = :yaml
- end
-
- add_option('--marshal', 'Output Marshal format') do |value, options|
- options[:format] = :marshal
- end
-
- add_local_remote_options
- end
-
- def arguments # :nodoc:
- <<-ARGS
-GEMFILE name of gem to show the gemspec for
-FIELD name of gemspec field to show
- ARGS
- end
-
- def defaults_str # :nodoc:
- "--local --version '#{Gem::Requirement.default}' --yaml"
- end
-
- def usage # :nodoc:
- "#{program_name} [GEMFILE] [FIELD]"
- end
-
- def execute
- specs = []
- gem = options[:args].shift
-
- unless gem then
- raise Gem::CommandLineError,
- "Please specify a gem name or file on the command line"
- end
-
- case options[:version]
- when String
- req = Gem::Requirement.parse options[:version]
- when Gem::Requirement
- req = options[:version]
- else
- raise Gem::CommandLineError, "Unsupported version type: #{options[:version]}"
- end
-
- if !req.none? and options[:all]
- alert_error "Specify --all or -v, not both"
- terminate_interaction 1
- end
-
- if options[:all]
- dep = Gem::Dependency.new gem
- else
- dep = Gem::Dependency.new gem, options[:version]
- end
-
- field = get_one_optional_argument
-
- raise Gem::CommandLineError, "--ruby and FIELD are mutually exclusive" if
- field and options[:format] == :ruby
-
- if local? then
- if File.exist? gem then
- specs << Gem::Format.from_file_by_path(gem).spec rescue nil
- end
-
- if specs.empty? then
- specs.push(*dep.matching_specs)
- end
- end
-
- if remote? then
- found = Gem::SpecFetcher.fetcher.fetch dep, true
-
- if dep.prerelease? or options[:prerelease]
- found += Gem::SpecFetcher.fetcher.fetch dep, false, true, true
- end
-
- specs.push(*found.map { |spec,| spec })
- end
-
- if specs.empty? then
- alert_error "Unknown gem '#{gem}'"
- terminate_interaction 1
- end
-
- unless options[:all] then
- specs = [specs.sort_by { |s| s.version }.last]
- end
-
- specs.each do |s|
- s = s.send field if field
-
- say case options[:format]
- when :ruby then s.to_ruby
- when :marshal then Marshal.dump s
- else s.to_yaml
- end
-
- say "\n"
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rubygems/commands/stale_command.rb b/ruby_1_9_3/lib/rubygems/commands/stale_command.rb
deleted file mode 100644
index 36c517e27c..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/stale_command.rb
+++ /dev/null
@@ -1,28 +0,0 @@
-require 'rubygems/command'
-
-class Gem::Commands::StaleCommand < Gem::Command
- def initialize
- super('stale', 'List gems along with access times')
- end
-
- def usage # :nodoc:
- "#{program_name}"
- end
-
- def execute
- gem_to_atime = {}
- Gem::Specification.each do |spec|
- name = spec.full_name
- Dir["#{spec.full_gem_path}/**/*.*"].each do |file|
- next if File.directory?(file)
- stat = File.stat(file)
- gem_to_atime[name] ||= stat.atime
- gem_to_atime[name] = stat.atime if gem_to_atime[name] < stat.atime
- end
- end
-
- gem_to_atime.sort_by { |_, atime| atime }.each do |name, atime|
- say "#{name} at #{atime.strftime '%c'}"
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rubygems/commands/uninstall_command.rb b/ruby_1_9_3/lib/rubygems/commands/uninstall_command.rb
deleted file mode 100644
index aaadb762b5..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/uninstall_command.rb
+++ /dev/null
@@ -1,94 +0,0 @@
-require 'rubygems/command'
-require 'rubygems/version_option'
-require 'rubygems/uninstaller'
-
-##
-# Gem uninstaller command line tool
-#
-# See `gem help uninstall`
-
-class Gem::Commands::UninstallCommand < Gem::Command
-
- include Gem::VersionOption
-
- def initialize
- super 'uninstall', 'Uninstall gems from the local repository',
- :version => Gem::Requirement.default, :user_install => true
-
- add_option('-a', '--[no-]all',
- 'Uninstall all matching versions'
- ) do |value, options|
- options[:all] = value
- end
-
- add_option('-I', '--[no-]ignore-dependencies',
- 'Ignore dependency requirements while',
- 'uninstalling') do |value, options|
- options[:ignore] = value
- end
-
- add_option('-x', '--[no-]executables',
- 'Uninstall applicable executables without',
- 'confirmation') do |value, options|
- options[:executables] = value
- end
-
- add_option('-i', '--install-dir DIR',
- 'Directory to uninstall gem from') do |value, options|
- options[:install_dir] = File.expand_path(value)
- end
-
- add_option('-n', '--bindir DIR',
- 'Directory to remove binaries from') do |value, options|
- options[:bin_dir] = File.expand_path(value)
- end
-
- add_option('--[no-]user-install',
- 'Uninstall from user\'s home directory',
- 'in addition to GEM_HOME.') do |value, options|
- options[:user_install] = value
- end
-
- add_option('--[no-]format-executable',
- 'Assume executable names match Ruby\'s prefix and suffix.') do |value, options|
- options[:format_executable] = value
- end
-
- add_version_option
- add_platform_option
- end
-
- def arguments # :nodoc:
- "GEMNAME name of gem to uninstall"
- end
-
- def defaults_str # :nodoc:
- "--version '#{Gem::Requirement.default}' --no-force " \
- "--install-dir #{Gem.dir}\n" \
- "--user-install"
- end
-
- def usage # :nodoc:
- "#{program_name} GEMNAME [GEMNAME ...]"
- end
-
- def execute
- original_path = Gem.path
-
- get_all_gem_names.each do |gem_name|
- begin
- Gem::Uninstaller.new(gem_name, options).uninstall
- rescue Gem::InstallError => e
- alert e.message
- rescue Gem::GemNotInHomeException => e
- spec = e.spec
- alert("In order to remove #{spec.name}, please execute:\n" \
- "\tgem uninstall #{spec.name} --install-dir=#{spec.installation_path}")
- ensure
- Gem.use_paths(*original_path)
- end
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/commands/unpack_command.rb b/ruby_1_9_3/lib/rubygems/commands/unpack_command.rb
deleted file mode 100644
index 64b8ad64f8..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/unpack_command.rb
+++ /dev/null
@@ -1,160 +0,0 @@
-require 'rubygems/command'
-require 'rubygems/installer'
-require 'rubygems/version_option'
-require 'rubygems/remote_fetcher'
-
-class Gem::Commands::UnpackCommand < Gem::Command
-
- include Gem::VersionOption
-
- def initialize
- require 'fileutils'
-
- super 'unpack', 'Unpack an installed gem to the current directory',
- :version => Gem::Requirement.default,
- :target => Dir.pwd
-
- add_option('--target=DIR',
- 'target directory for unpacking') do |value, options|
- options[:target] = value
- end
-
- add_option('--spec', 'unpack the gem specification') do |value, options|
- options[:spec] = true
- end
-
- add_version_option
- end
-
- def arguments # :nodoc:
- "GEMNAME name of gem to unpack"
- end
-
- def defaults_str # :nodoc:
- "--version '#{Gem::Requirement.default}'"
- end
-
- def usage # :nodoc:
- "#{program_name} GEMNAME"
- end
-
- #--
- # TODO: allow, e.g., 'gem unpack rake-0.3.1'. Find a general solution for
- # this, so that it works for uninstall as well. (And check other commands
- # at the same time.)
-
- def execute
- get_all_gem_names.each do |name|
- dependency = Gem::Dependency.new name, options[:version]
- path = get_path dependency
-
- unless path then
- alert_error "Gem '#{name}' not installed nor fetchable."
- next
- end
-
- if @options[:spec] then
- spec, metadata = get_metadata path
-
- if metadata.nil? then
- alert_error "--spec is unsupported on '#{name}' (old format gem)"
- next
- end
-
- spec_file = File.basename spec.spec_file
-
- open spec_file, 'w' do |io|
- io.write metadata
- end
- else
- basename = File.basename path, '.gem'
- target_dir = File.expand_path basename, options[:target]
- FileUtils.mkdir_p target_dir
- Gem::Installer.new(path, :unpack => true).unpack target_dir
- say "Unpacked gem: '#{target_dir}'"
- end
- end
- end
-
- ##
- #
- # Find cached filename in Gem.path. Returns nil if the file cannot be found.
- #
- #--
- # TODO: see comments in get_path() about general service.
-
- def find_in_cache(filename)
- Gem.path.each do |path|
- this_path = File.join(path, "cache", filename)
- return this_path if File.exist? this_path
- end
-
- return nil
- end
-
- ##
- # Return the full path to the cached gem file matching the given
- # name and version requirement. Returns 'nil' if no match.
- #
- # Example:
- #
- # get_path 'rake', '> 0.4' # "/usr/lib/ruby/gems/1.8/cache/rake-0.4.2.gem"
- # get_path 'rake', '< 0.1' # nil
- # get_path 'rak' # nil (exact name required)
- #--
- # TODO: This should be refactored so that it's a general service. I don't
- # think any of our existing classes are the right place though. Just maybe
- # 'Cache'?
- #
- # TODO: It just uses Gem.dir for now. What's an easy way to get the list of
- # source directories?
-
- def get_path dependency
- return dependency.name if dependency.name =~ /\.gem$/i
-
- specs = dependency.matching_specs
-
- selected = specs.sort_by { |s| s.version }.last # HACK: hunt last down
-
- return Gem::RemoteFetcher.fetcher.download_to_cache(dependency) unless
- selected
-
- return unless dependency.name =~ /^#{selected.name}$/i
-
- # We expect to find (basename).gem in the 'cache' directory. Furthermore,
- # the name match must be exact (ignoring case).
-
- path = find_in_cache File.basename selected.cache_file
-
- return Gem::RemoteFetcher.fetcher.download_to_cache(dependency) unless path
-
- path
- end
-
- ##
- # Extracts the Gem::Specification and raw metadata from the .gem file at
- # +path+.
-
- def get_metadata path
- format = Gem::Format.from_file_by_path path
- spec = format.spec
-
- metadata = nil
-
- open path, Gem.binary_mode do |io|
- tar = Gem::Package::TarReader.new io
- tar.each_entry do |entry|
- case entry.full_name
- when 'metadata' then
- metadata = entry.read
- when 'metadata.gz' then
- metadata = Gem.gunzip entry.read
- end
- end
- end
-
- return spec, metadata
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/commands/update_command.rb b/ruby_1_9_3/lib/rubygems/commands/update_command.rb
deleted file mode 100644
index d63b943c56..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/update_command.rb
+++ /dev/null
@@ -1,232 +0,0 @@
-require 'rubygems/command'
-require 'rubygems/command_manager'
-require 'rubygems/install_update_options'
-require 'rubygems/local_remote_options'
-require 'rubygems/spec_fetcher'
-require 'rubygems/version_option'
-require 'rubygems/commands/install_command'
-
-class Gem::Commands::UpdateCommand < Gem::Command
-
- include Gem::InstallUpdateOptions
- include Gem::LocalRemoteOptions
- include Gem::VersionOption
-
- def initialize
- super 'update',
- 'Update the named gems (or all installed gems) in the local repository',
- :generate_rdoc => true,
- :generate_ri => true,
- :force => false
-
- add_install_update_options
-
- OptionParser.accept Gem::Version do |value|
- Gem::Version.new value
-
- value
- end
-
- add_option('--system [VERSION]', Gem::Version,
- 'Update the RubyGems system software') do |value, options|
- value = true unless value
-
- options[:system] = value
- end
-
- add_local_remote_options
- add_platform_option
- add_prerelease_option "as update targets"
- end
-
- def arguments # :nodoc:
- "GEMNAME name of gem to update"
- end
-
- def defaults_str # :nodoc:
- "--rdoc --ri --no-force --install-dir #{Gem.dir}"
- end
-
- def usage # :nodoc:
- "#{program_name} GEMNAME [GEMNAME ...]"
- end
-
- def execute
- @installer = Gem::DependencyInstaller.new options
- @updated = []
-
- hig = {}
-
- if options[:system] then
- update_rubygems
- return
- else
- say "Updating installed gems"
-
- hig = {} # highest installed gems
-
- Gem::Specification.each do |spec|
- if hig[spec.name].nil? or hig[spec.name].version < spec.version then
- hig[spec.name] = spec
- end
- end
- end
-
- gems_to_update = which_to_update hig, options[:args].uniq
-
- updated = update_gems gems_to_update
-
- if updated.empty? then
- say "Nothing to update"
- else
- say "Gems updated: #{updated.map { |spec| spec.name }.join ', '}"
-
- if options[:generate_ri] then
- updated.each do |gem|
- Gem::DocManager.new(gem, options[:rdoc_args]).generate_ri
- end
-
- Gem::DocManager.update_ri_cache
- end
-
- if options[:generate_rdoc] then
- updated.each do |gem|
- Gem::DocManager.new(gem, options[:rdoc_args]).generate_rdoc
- end
- end
- end
- end
-
- def update_gem name, version = Gem::Requirement.default
- return if @updated.any? { |spec| spec.name == name }
- success = false
-
- say "Updating #{name}"
- begin
- @installer.install name, version
- success = true
- rescue Gem::InstallError => e
- alert_error "Error installing #{name}:\n\t#{e.message}"
- success = false
- end
-
- @installer.installed_gems.each do |spec|
- @updated << spec
- say "Successfully installed #{spec.full_name}" if success
- end
- end
-
- def update_gems gems_to_update
- gems_to_update.uniq.sort.each do |(name, version)|
- update_gem name, version
- end
-
- @updated
- end
-
- ##
- # Update RubyGems software to the latest version.
-
- def update_rubygems
- unless options[:args].empty? then
- alert_error "Gem names are not allowed with the --system option"
- terminate_interaction 1
- end
-
- options[:user_install] = false
-
- # TODO: rename version and other variable name conflicts
- # TODO: get rid of all this indirection on name and other BS
-
- version = options[:system]
- if version == true then
- version = Gem::Version.new Gem::VERSION
- requirement = Gem::Requirement.new ">= #{Gem::VERSION}"
- else
- version = Gem::Version.new version
- requirement = Gem::Requirement.new version
- end
-
- rubygems_update = Gem::Specification.new
- rubygems_update.name = 'rubygems-update'
- rubygems_update.version = version
-
- hig = {
- 'rubygems-update' => rubygems_update
- }
-
- gems_to_update = which_to_update hig, options[:args], :system
- name, up_ver = gems_to_update.first
- current_ver = Gem::Version.new Gem::VERSION
-
- target = if options[:system] == true then
- up_ver
- else
- version
- end
-
- if current_ver == target then
- # if options[:system] != true and version == current_ver then
- say "Latest version currently installed. Aborting."
- terminate_interaction
- end
-
- update_gem name, target
-
- installed_gems = Gem::Specification.find_all_by_name 'rubygems-update', requirement
- version = installed_gems.last.version
-
- args = []
- args << '--prefix' << Gem.prefix if Gem.prefix
- args << '--no-rdoc' unless options[:generate_rdoc]
- args << '--no-ri' unless options[:generate_ri]
- args << '--no-format-executable' if options[:no_format_executable]
-
- update_dir = File.join Gem.dir, 'gems', "rubygems-update-#{version}"
-
- Dir.chdir update_dir do
- say "Installing RubyGems #{version}"
- setup_cmd = "#{Gem.ruby} setup.rb #{args.join ' '}"
-
- # Make sure old rubygems isn't loaded
- old = ENV["RUBYOPT"]
- ENV.delete("RUBYOPT") if old
- installed = system setup_cmd
- say "RubyGems system software updated" if installed
- ENV["RUBYOPT"] = old if old
- end
- end
-
- def which_to_update highest_installed_gems, gem_names, system = false
- result = []
-
- highest_installed_gems.each do |l_name, l_spec|
- next if not gem_names.empty? and
- gem_names.all? { |name| /#{name}/ !~ l_spec.name }
-
- dependency = Gem::Dependency.new l_spec.name, "> #{l_spec.version}"
-
- fetcher = Gem::SpecFetcher.fetcher
- spec_tuples = fetcher.find_matching dependency
-
- matching_gems = spec_tuples.select do |(name, _, platform),|
- name == l_name and Gem::Platform.match platform
- end
-
- highest_remote_gem = matching_gems.sort_by do |(_, version),|
- version
- end.last
-
- highest_remote_gem ||= [[nil, Gem::Version.new(0), nil]] # "null" object
- highest_remote_ver = highest_remote_gem.first[1]
-
- if system or (l_spec.version < highest_remote_ver) then
- result << [l_spec.name, [l_spec.version, highest_remote_ver].max]
- end
- end
-
- result
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/commands/which_command.rb b/ruby_1_9_3/lib/rubygems/commands/which_command.rb
deleted file mode 100644
index 6495278a87..0000000000
--- a/ruby_1_9_3/lib/rubygems/commands/which_command.rb
+++ /dev/null
@@ -1,82 +0,0 @@
-require 'rubygems/command'
-
-class Gem::Commands::WhichCommand < Gem::Command
- def initialize
- super 'which', 'Find the location of a library file you can require',
- :search_gems_first => false, :show_all => false
-
- add_option '-a', '--[no-]all', 'show all matching files' do |show_all, options|
- options[:show_all] = show_all
- end
-
- add_option '-g', '--[no-]gems-first',
- 'search gems before non-gems' do |gems_first, options|
- options[:search_gems_first] = gems_first
- end
- end
-
- def arguments # :nodoc:
- "FILE name of file to find"
- end
-
- def defaults_str # :nodoc:
- "--no-gems-first --no-all"
- end
-
- def execute
- found = false
-
- options[:args].each do |arg|
- arg = arg.sub(/#{Regexp.union(*Gem.suffixes)}$/, '')
- dirs = $LOAD_PATH
-
- spec = Gem::Specification.find_by_path arg
-
- if spec then
- if options[:search_gems_first] then
- dirs = gem_paths(spec) + $LOAD_PATH
- else
- dirs = $LOAD_PATH + gem_paths(spec)
- end
- end
-
- # TODO: this is totally redundant and stupid
- paths = find_paths arg, dirs
-
- if paths.empty? then
- alert_error "Can't find ruby library file or shared library #{arg}"
- else
- say paths
- found = true
- end
- end
-
- terminate_interaction 1 unless found
- end
-
- def find_paths(package_name, dirs)
- result = []
-
- dirs.each do |dir|
- Gem.suffixes.each do |ext|
- full_path = File.join dir, "#{package_name}#{ext}"
- if File.exist? full_path and not File.directory? full_path then
- result << full_path
- return result unless options[:show_all]
- end
- end
- end
-
- result
- end
-
- def gem_paths(spec)
- spec.require_paths.collect { |d| File.join spec.full_gem_path, d }
- end
-
- def usage # :nodoc:
- "#{program_name} FILE [FILE ...]"
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/config_file.rb b/ruby_1_9_3/lib/rubygems/config_file.rb
deleted file mode 100644
index 136e8b4610..0000000000
--- a/ruby_1_9_3/lib/rubygems/config_file.rb
+++ /dev/null
@@ -1,375 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-##
-# Gem::ConfigFile RubyGems options and gem command options from ~/.gemrc.
-#
-# ~/.gemrc is a YAML file that uses strings to match gem command arguments and
-# symbols to match RubyGems options.
-#
-# Gem command arguments use a String key that matches the command name and
-# allow you to specify default arguments:
-#
-# install: --no-rdoc --no-ri
-# update: --no-rdoc --no-ri
-#
-# You can use <tt>gem:</tt> to set default arguments for all commands.
-#
-# RubyGems options use symbol keys. Valid options are:
-#
-# +:backtrace+:: See #backtrace
-# +:benchmark+:: See #benchmark
-# +:sources+:: Sets Gem::sources
-# +:verbose+:: See #verbose
-
-require 'rbconfig'
-
-class Gem::ConfigFile
-
- DEFAULT_BACKTRACE = false
- DEFAULT_BENCHMARK = false
- DEFAULT_BULK_THRESHOLD = 1000
- DEFAULT_VERBOSITY = true
- DEFAULT_UPDATE_SOURCES = true
-
- ##
- # For Ruby packagers to set configuration defaults. Set in
- # rubygems/defaults/operating_system.rb
-
- OPERATING_SYSTEM_DEFAULTS = {}
-
- ##
- # For Ruby implementers to set configuration defaults. Set in
- # rubygems/defaults/#{RUBY_ENGINE}.rb
-
- PLATFORM_DEFAULTS = {}
-
- system_config_path =
- begin
- require "etc"
- Etc.sysconfdir
- rescue LoadError, NoMethodError
- begin
- # TODO: remove after we drop 1.8.7 and 1.9.1
- require 'Win32API'
-
- CSIDL_COMMON_APPDATA = 0x0023
- path = 0.chr * 260
- if RUBY_VERSION > '1.9' then
- SHGetFolderPath = Win32API.new 'shell32', 'SHGetFolderPath', 'PLPLP',
- 'L', :stdcall
- SHGetFolderPath.call nil, CSIDL_COMMON_APPDATA, nil, 1, path
- else
- SHGetFolderPath = Win32API.new 'shell32', 'SHGetFolderPath', 'LLLLP',
- 'L'
- SHGetFolderPath.call 0, CSIDL_COMMON_APPDATA, 0, 1, path
- end
-
- path.strip
- rescue LoadError
- RbConfig::CONFIG["sysconfdir"] || "/etc"
- end
- end
-
- SYSTEM_WIDE_CONFIG_FILE = File.join system_config_path, 'gemrc'
-
- ##
- # List of arguments supplied to the config file object.
-
- attr_reader :args
-
- ##
- # Where to look for gems (deprecated)
-
- attr_accessor :path
-
- ##
- # Where to install gems (deprecated)
-
- attr_accessor :home
-
- ##
- # True if we print backtraces on errors.
-
- attr_writer :backtrace
-
- ##
- # True if we are benchmarking this run.
-
- attr_accessor :benchmark
-
- ##
- # Bulk threshold value. If the number of missing gems are above this
- # threshold value, then a bulk download technique is used. (deprecated)
-
- attr_accessor :bulk_threshold
-
- ##
- # Verbose level of output:
- # * false -- No output
- # * true -- Normal output
- # * :loud -- Extra output
-
- attr_accessor :verbose
-
- ##
- # True if we want to update the SourceInfoCache every time, false otherwise
-
- attr_accessor :update_sources
-
- ##
- # API key for RubyGems.org
-
- attr_reader :rubygems_api_key
-
- ##
- # Hash of RubyGems.org and alternate API keys
-
- attr_reader :api_keys
-
- ##
- # openssl verify mode value, used for remote https connection
-
- attr_reader :ssl_verify_mode
-
- ##
- # Path name of directory or file of openssl CA certificate, used for remote https connection
-
- attr_reader :ssl_ca_cert
-
- ##
- # Create the config file object. +args+ is the list of arguments
- # from the command line.
- #
- # The following command line options are handled early here rather
- # than later at the time most command options are processed.
- #
- # <tt>--config-file</tt>, <tt>--config-file==NAME</tt>::
- # Obviously these need to be handled by the ConfigFile object to ensure we
- # get the right config file.
- #
- # <tt>--backtrace</tt>::
- # Backtrace needs to be turned on early so that errors before normal
- # option parsing can be properly handled.
- #
- # <tt>--debug</tt>::
- # Enable Ruby level debug messages. Handled early for the same reason as
- # --backtrace.
-
- def initialize(arg_list)
- @config_file_name = nil
- need_config_file_name = false
-
- arg_list = arg_list.map do |arg|
- if need_config_file_name then
- @config_file_name = arg
- need_config_file_name = false
- nil
- elsif arg =~ /^--config-file=(.*)/ then
- @config_file_name = $1
- nil
- elsif arg =~ /^--config-file$/ then
- need_config_file_name = true
- nil
- else
- arg
- end
- end.compact
-
- @backtrace = DEFAULT_BACKTRACE
- @benchmark = DEFAULT_BENCHMARK
- @bulk_threshold = DEFAULT_BULK_THRESHOLD
- @verbose = DEFAULT_VERBOSITY
- @update_sources = DEFAULT_UPDATE_SOURCES
-
- operating_system_config = Marshal.load Marshal.dump(OPERATING_SYSTEM_DEFAULTS)
- platform_config = Marshal.load Marshal.dump(PLATFORM_DEFAULTS)
- system_config = load_file SYSTEM_WIDE_CONFIG_FILE
- user_config = load_file config_file_name.dup.untaint
-
- @hash = operating_system_config.merge platform_config
- @hash = @hash.merge system_config
- @hash = @hash.merge user_config
-
- # HACK these override command-line args, which is bad
- @backtrace = @hash[:backtrace] if @hash.key? :backtrace
- @benchmark = @hash[:benchmark] if @hash.key? :benchmark
- @bulk_threshold = @hash[:bulk_threshold] if @hash.key? :bulk_threshold
- @home = @hash[:gemhome] if @hash.key? :gemhome
- @path = @hash[:gempath] if @hash.key? :gempath
- @update_sources = @hash[:update_sources] if @hash.key? :update_sources
- @verbose = @hash[:verbose] if @hash.key? :verbose
- @ssl_verify_mode = @hash[:ssl_verify_mode] if @hash.key? :ssl_verify_mode
- @ssl_ca_cert = @hash[:ssl_ca_cert] if @hash.key? :ssl_ca_cert
-
- load_api_keys
-
- Gem.sources = @hash[:sources] if @hash.key? :sources
- handle_arguments arg_list
- end
-
- ##
- # Location of RubyGems.org credentials
-
- def credentials_path
- File.join Gem.user_home, '.gem', 'credentials'
- end
-
- def load_api_keys
- @api_keys = if File.exist? credentials_path then
- load_file(credentials_path)
- else
- @hash
- end
- if @api_keys.key? :rubygems_api_key then
- @rubygems_api_key = @api_keys[:rubygems_api_key]
- @api_keys[:rubygems] = @api_keys.delete :rubygems_api_key unless @api_keys.key? :rubygems
- end
- end
-
- def rubygems_api_key=(api_key)
- config = load_file(credentials_path).merge(:rubygems_api_key => api_key)
-
- dirname = File.dirname credentials_path
- Dir.mkdir(dirname) unless File.exist? dirname
-
- Gem.load_yaml
-
- File.open(credentials_path, 'w') do |f|
- f.write config.to_yaml
- end
-
- @rubygems_api_key = api_key
- end
-
- def load_file(filename)
- Gem.load_yaml
-
- return {} unless filename and File.exist? filename
- begin
- YAML.load(File.read(filename))
- rescue ArgumentError
- warn "Failed to load #{config_file_name}"
- rescue Errno::EACCES
- warn "Failed to load #{config_file_name} due to permissions problem."
- end or {}
- end
-
- # True if the backtrace option has been specified, or debug is on.
- def backtrace
- @backtrace or $DEBUG
- end
-
- # The name of the configuration file.
- def config_file_name
- @config_file_name || Gem.config_file
- end
-
- # Delegates to @hash
- def each(&block)
- hash = @hash.dup
- hash.delete :update_sources
- hash.delete :verbose
- hash.delete :benchmark
- hash.delete :backtrace
- hash.delete :bulk_threshold
-
- yield :update_sources, @update_sources
- yield :verbose, @verbose
- yield :benchmark, @benchmark
- yield :backtrace, @backtrace
- yield :bulk_threshold, @bulk_threshold
-
- yield 'config_file_name', @config_file_name if @config_file_name
-
- hash.each(&block)
- end
-
- # Handle the command arguments.
- def handle_arguments(arg_list)
- @args = []
-
- arg_list.each do |arg|
- case arg
- when /^--(backtrace|traceback)$/ then
- @backtrace = true
- when /^--bench(mark)?$/ then
- @benchmark = true
- when /^--debug$/ then
- $DEBUG = true
- else
- @args << arg
- end
- end
- end
-
- # Really verbose mode gives you extra output.
- def really_verbose
- case verbose
- when true, false, nil then false
- else true
- end
- end
-
- # to_yaml only overwrites things you can't override on the command line.
- def to_yaml # :nodoc:
- yaml_hash = {}
- yaml_hash[:backtrace] = @hash.key?(:backtrace) ? @hash[:backtrace] :
- DEFAULT_BACKTRACE
- yaml_hash[:benchmark] = @hash.key?(:benchmark) ? @hash[:benchmark] :
- DEFAULT_BENCHMARK
- yaml_hash[:bulk_threshold] = @hash.key?(:bulk_threshold) ?
- @hash[:bulk_threshold] : DEFAULT_BULK_THRESHOLD
- yaml_hash[:sources] = Gem.sources
- yaml_hash[:update_sources] = @hash.key?(:update_sources) ?
- @hash[:update_sources] : DEFAULT_UPDATE_SOURCES
- yaml_hash[:verbose] = @hash.key?(:verbose) ? @hash[:verbose] :
- DEFAULT_VERBOSITY
-
- keys = yaml_hash.keys.map { |key| key.to_s }
- keys << 'debug'
- re = Regexp.union(*keys)
-
- @hash.each do |key, value|
- key = key.to_s
- next if key =~ re
- yaml_hash[key.to_s] = value
- end
-
- yaml_hash.to_yaml
- end
-
- # Writes out this config file, replacing its source.
- def write
- open config_file_name, 'w' do |io|
- io.write to_yaml
- end
- end
-
- # Return the configuration information for +key+.
- def [](key)
- @hash[key.to_s]
- end
-
- # Set configuration option +key+ to +value+.
- def []=(key, value)
- @hash[key.to_s] = value
- end
-
- def ==(other) # :nodoc:
- self.class === other and
- @backtrace == other.backtrace and
- @benchmark == other.benchmark and
- @bulk_threshold == other.bulk_threshold and
- @verbose == other.verbose and
- @update_sources == other.update_sources and
- @hash == other.hash
- end
-
- protected
-
- attr_reader :hash
-end
diff --git a/ruby_1_9_3/lib/rubygems/custom_require.rb b/ruby_1_9_3/lib/rubygems/custom_require.rb
deleted file mode 100644
index c813e3aaa2..0000000000
--- a/ruby_1_9_3/lib/rubygems/custom_require.rb
+++ /dev/null
@@ -1,69 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-module Kernel
-
- if defined?(gem_original_require) then
- # Ruby ships with a custom_require, override its require
- remove_method :require
- else
- ##
- # The Kernel#require from before RubyGems was loaded.
-
- alias gem_original_require require
- private :gem_original_require
- end
-
- ##
- # When RubyGems is required, Kernel#require is replaced with our own which
- # is capable of loading gems on demand.
- #
- # When you call <tt>require 'x'</tt>, this is what happens:
- # * If the file can be loaded from the existing Ruby loadpath, it
- # is.
- # * Otherwise, installed gems are searched for a file that matches.
- # If it's found in gem 'y', that gem is activated (added to the
- # loadpath).
- #
- # The normal <tt>require</tt> functionality of returning false if
- # that file has already been loaded is preserved.
-
- def require path
- if Gem.unresolved_deps.empty? then
- gem_original_require path
- else
- spec = Gem::Specification.find { |s|
- s.activated? and s.contains_requirable_file? path
- }
-
- unless spec then
- found_specs = Gem::Specification.find_in_unresolved path
- unless found_specs.empty? then
- found_specs = [found_specs.last]
- else
- found_specs = Gem::Specification.find_in_unresolved_tree path
- end
-
- found_specs.each do |found_spec|
- found_spec.activate
- end
- end
-
- return gem_original_require path
- end
- rescue LoadError => load_error
- if load_error.message.start_with?("Could not find") or
- (load_error.message.end_with?(path) and Gem.try_activate(path)) then
- return gem_original_require(path)
- end
-
- raise load_error
- end
-
- private :require
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/defaults.rb b/ruby_1_9_3/lib/rubygems/defaults.rb
deleted file mode 100644
index d6732adbfa..0000000000
--- a/ruby_1_9_3/lib/rubygems/defaults.rb
+++ /dev/null
@@ -1,124 +0,0 @@
-module Gem
-
- # TODO: move this whole file back into rubygems.rb
-
- @post_install_hooks ||= []
- @post_uninstall_hooks ||= []
- @pre_uninstall_hooks ||= []
- @pre_install_hooks ||= []
-
- ##
- # An Array of the default sources that come with RubyGems
-
- def self.default_sources
- %w[http://rubygems.org/]
- end
-
- ##
- # Default home directory path to be used if an alternate value is not
- # specified in the environment
-
- def self.default_dir
- path = if defined? RUBY_FRAMEWORK_VERSION then
- [
- File.dirname(ConfigMap[:sitedir]),
- 'Gems',
- ConfigMap[:ruby_version]
- ]
- elsif ConfigMap[:rubylibprefix] then
- [
- ConfigMap[:rubylibprefix],
- 'gems',
- ConfigMap[:ruby_version]
- ]
- else
- [
- ConfigMap[:libdir],
- ruby_engine,
- 'gems',
- ConfigMap[:ruby_version]
- ]
- end
-
- @default_dir ||= File.join(*path)
- end
-
- ##
- # Paths where RubyGems' .rb files and bin files are installed
-
- def self.default_rubygems_dirs
- nil # default to standard layout
- end
-
- ##
- # Path for gems in the user's home directory
-
- def self.user_dir
- File.join Gem.user_home, '.gem', ruby_engine, ConfigMap[:ruby_version]
- end
-
- ##
- # Default gem load path
-
- def self.default_path
- if File.exist? Gem.user_home then
- [user_dir, default_dir]
- else
- [default_dir]
- end
- end
-
- ##
- # Deduce Ruby's --program-prefix and --program-suffix from its install name
-
- def self.default_exec_format
- exec_format = ConfigMap[:ruby_install_name].sub('ruby', '%s') rescue '%s'
-
- unless exec_format =~ /%s/ then
- raise Gem::Exception,
- "[BUG] invalid exec_format #{exec_format.inspect}, no %s"
- end
-
- exec_format
- end
-
- ##
- # The default directory for binaries
-
- def self.default_bindir
- if defined? RUBY_FRAMEWORK_VERSION then # mac framework support
- '/usr/bin'
- else # generic install
- ConfigMap[:bindir]
- end
- end
-
- ##
- # The default system-wide source info cache directory
-
- def self.default_system_source_cache_dir
- File.join(Gem.dir, 'source_cache')
- end
-
- ##
- # The default user-specific source info cache directory
-
- def self.default_user_source_cache_dir
- #
- # NOTE Probably an argument for moving this to per-ruby supported dirs like
- # user_dir
- #
- File.join(Gem.user_home, '.gem', 'source_cache')
- end
-
- ##
- # A wrapper around RUBY_ENGINE const that may not be defined
-
- def self.ruby_engine
- if defined? RUBY_ENGINE then
- RUBY_ENGINE
- else
- 'ruby'
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rubygems/dependency.rb b/ruby_1_9_3/lib/rubygems/dependency.rb
deleted file mode 100644
index 0caf65c6c4..0000000000
--- a/ruby_1_9_3/lib/rubygems/dependency.rb
+++ /dev/null
@@ -1,260 +0,0 @@
-require "rubygems/requirement"
-
-##
-# The Dependency class holds a Gem name and a Gem::Requirement.
-
-class Gem::Dependency
-
- ##
- # Valid dependency types.
- #--
- # When this list is updated, be sure to change
- # Gem::Specification::CURRENT_SPECIFICATION_VERSION as well.
-
- TYPES = [
- :development,
- :runtime,
- ]
-
- ##
- # Dependency name or regular expression.
-
- attr_accessor :name
-
- ##
- # Allows you to force this dependency to be a prerelease.
-
- attr_writer :prerelease
-
- ##
- # Constructs a dependency with +name+ and +requirements+. The last
- # argument can optionally be the dependency type, which defaults to
- # <tt>:runtime</tt>.
-
- def initialize name, *requirements
- if Regexp === name then
- msg = ["NOTE: Dependency.new w/ a regexp is deprecated.",
- "Dependency.new called from #{Gem.location_of_caller.join(":")}"]
- warn msg.join("\n") unless Gem::Deprecate.skip
- end
-
- type = Symbol === requirements.last ? requirements.pop : :runtime
- requirements = requirements.first if 1 == requirements.length # unpack
-
- unless TYPES.include? type
- raise ArgumentError, "Valid types are #{TYPES.inspect}, "
- + "not #{type.inspect}"
- end
-
- @name = name
- @requirement = Gem::Requirement.create requirements
- @type = type
- @prerelease = false
-
- # This is for Marshal backwards compatibility. See the comments in
- # +requirement+ for the dirty details.
-
- @version_requirements = @requirement
- end
-
- ##
- # A dependency's hash is the XOR of the hashes of +name+, +type+,
- # and +requirement+.
-
- def hash # :nodoc:
- name.hash ^ type.hash ^ requirement.hash
- end
-
- def inspect # :nodoc:
- "<%s type=%p name=%p requirements=%p>" %
- [self.class, self.type, self.name, requirement.to_s]
- end
-
- ##
- # Does this dependency require a prerelease?
-
- def prerelease?
- @prerelease || requirement.prerelease?
- end
-
- def pretty_print q # :nodoc:
- q.group 1, 'Gem::Dependency.new(', ')' do
- q.pp name
- q.text ','
- q.breakable
-
- q.pp requirement
-
- q.text ','
- q.breakable
-
- q.pp type
- end
- end
-
- ##
- # What does this dependency require?
-
- def requirement
- return @requirement if defined?(@requirement) and @requirement
-
- # @version_requirements and @version_requirement are legacy ivar
- # names, and supported here because older gems need to keep
- # working and Dependency doesn't implement marshal_dump and
- # marshal_load. In a happier world, this would be an
- # attr_accessor. The horrifying instance_variable_get you see
- # below is also the legacy of some old restructurings.
- #
- # Note also that because of backwards compatibility (loading new
- # gems in an old RubyGems installation), we can't add explicit
- # marshaling to this class until we want to make a big
- # break. Maybe 2.0.
- #
- # Children, define explicit marshal and unmarshal behavior for
- # public classes. Marshal formats are part of your public API.
-
- if defined?(@version_requirement) && @version_requirement
- version = @version_requirement.instance_variable_get :@version
- @version_requirement = nil
- @version_requirements = Gem::Requirement.new version
- end
-
- @requirement = @version_requirements if defined?(@version_requirements)
- end
-
- def requirements_list
- requirement.as_list
- end
-
- def to_s # :nodoc:
- if type != :runtime then
- "#{name} (#{requirement}, #{type})"
- else
- "#{name} (#{requirement})"
- end
- end
-
- ##
- # Dependency type.
-
- def type
- @type ||= :runtime
- end
-
- def == other # :nodoc:
- Gem::Dependency === other &&
- self.name == other.name &&
- self.type == other.type &&
- self.requirement == other.requirement
- end
-
- ##
- # Dependencies are ordered by name.
-
- def <=> other
- self.name <=> other.name
- end
-
- ##
- # Uses this dependency as a pattern to compare to +other+. This
- # dependency will match if the name matches the other's name, and
- # other has only an equal version requirement that satisfies this
- # dependency.
-
- def =~ other
- unless Gem::Dependency === other
- return unless other.respond_to?(:name) && other.respond_to?(:version)
- other = Gem::Dependency.new other.name, other.version
- end
-
- return false unless name === other.name
-
- reqs = other.requirement.requirements
-
- return false unless reqs.length == 1
- return false unless reqs.first.first == '='
-
- version = reqs.first.last
-
- requirement.satisfied_by? version
- end
-
- def match? name, version
- return false unless self.name === name
- return true if requirement.none?
-
- requirement.satisfied_by? Gem::Version.new(version)
- end
-
- def matches_spec? spec
- return false unless name === spec.name
- return true if requirement.none?
-
- requirement.satisfied_by?(spec.version)
- end
-
- ##
- # Merges the requirements of +other+ into this dependency
-
- def merge other
- unless name == other.name then
- raise ArgumentError,
- "#{self} and #{other} have different names"
- end
-
- default = Gem::Requirement.default
- self_req = self.requirement
- other_req = other.requirement
-
- return self.class.new name, self_req if other_req == default
- return self.class.new name, other_req if self_req == default
-
- self.class.new name, self_req.as_list.concat(other_req.as_list)
- end
-
- def matching_specs platform_only = false
- matches = Gem::Specification.find_all { |spec|
- self.name === spec.name and # TODO: == instead of ===
- requirement.satisfied_by? spec.version
- }
-
- if platform_only
- matches.reject! { |spec|
- not Gem::Platform.match spec.platform
- }
- end
-
- matches = matches.sort_by { |s| s.sort_obj } # HACK: shouldn't be needed
- end
-
- ##
- # True if the dependency will not always match the latest version.
-
- def specific?
- @requirement.specific?
- end
-
- def to_specs
- matches = matching_specs true
-
- # TODO: check Gem.activated_spec[self.name] in case matches falls outside
-
- if matches.empty? then
- specs = Gem::Specification.all_names.join ", "
- error = Gem::LoadError.new "Could not find #{name} (#{requirement}) amongst [#{specs}]"
- error.name = self.name
- error.requirement = self.requirement
- raise error
- end
-
- # TODO: any other resolver validations should go here
-
- matches
- end
-
- def to_spec
- matches = self.to_specs
-
- matches.find { |spec| spec.activated? } or matches.last
- end
-end
diff --git a/ruby_1_9_3/lib/rubygems/dependency_installer.rb b/ruby_1_9_3/lib/rubygems/dependency_installer.rb
deleted file mode 100644
index 6303e8e9ac..0000000000
--- a/ruby_1_9_3/lib/rubygems/dependency_installer.rb
+++ /dev/null
@@ -1,304 +0,0 @@
-require 'rubygems'
-require 'rubygems/dependency_list'
-require 'rubygems/installer'
-require 'rubygems/spec_fetcher'
-require 'rubygems/user_interaction'
-
-##
-# Installs a gem along with all its dependencies from local and remote gems.
-
-class Gem::DependencyInstaller
-
- include Gem::UserInteraction
-
- attr_reader :gems_to_install
- attr_reader :installed_gems
-
- DEFAULT_OPTIONS = {
- :env_shebang => false,
- :domain => :both, # HACK dup
- :force => false,
- :format_executable => false, # HACK dup
- :ignore_dependencies => false,
- :prerelease => false,
- :security_policy => nil, # HACK NoSecurity requires OpenSSL. AlmostNo? Low?
- :wrappers => true,
- }
-
- ##
- # Creates a new installer instance.
- #
- # Options are:
- # :cache_dir:: Alternate repository path to store .gem files in.
- # :domain:: :local, :remote, or :both. :local only searches gems in the
- # current directory. :remote searches only gems in Gem::sources.
- # :both searches both.
- # :env_shebang:: See Gem::Installer::new.
- # :force:: See Gem::Installer#install.
- # :format_executable:: See Gem::Installer#initialize.
- # :ignore_dependencies:: Don't install any dependencies.
- # :install_dir:: See Gem::Installer#install.
- # :prerelease:: Allow prerelease versions. See #install.
- # :security_policy:: See Gem::Installer::new and Gem::Security.
- # :user_install:: See Gem::Installer.new
- # :wrappers:: See Gem::Installer::new
-
- def initialize(options = {})
- if options[:install_dir] then
- @gem_home = options[:install_dir]
-
- Gem::Specification.dirs = @gem_home
- Gem.ensure_gem_subdirectories @gem_home
- options[:install_dir] = @gem_home # FIX: because we suck and reuse below
- end
-
- options = DEFAULT_OPTIONS.merge options
-
- @bin_dir = options[:bin_dir]
- @development = options[:development]
- @domain = options[:domain]
- @env_shebang = options[:env_shebang]
- @force = options[:force]
- @format_executable = options[:format_executable]
- @ignore_dependencies = options[:ignore_dependencies]
- @prerelease = options[:prerelease]
- @security_policy = options[:security_policy]
- @user_install = options[:user_install]
- @wrappers = options[:wrappers]
-
- @installed_gems = []
-
- @install_dir = options[:install_dir] || Gem.dir
- @cache_dir = options[:cache_dir] || @install_dir
-
- # Set with any errors that SpecFetcher finds while search through
- # gemspecs for a dep
- @errors = nil
- end
-
- ##
- # Returns a list of pairs of gemspecs and source_uris that match
- # Gem::Dependency +dep+ from both local (Dir.pwd) and remote (Gem.sources)
- # sources. Gems are sorted with newer gems preferred over older gems, and
- # local gems preferred over remote gems.
-
- def find_gems_with_sources(dep)
- # Reset the errors
- @errors = nil
- gems_and_sources = []
-
- if @domain == :both or @domain == :local then
- Dir[File.join(Dir.pwd, "#{dep.name}-[0-9]*.gem")].each do |gem_file|
- spec = Gem::Format.from_file_by_path(gem_file).spec
- gems_and_sources << [spec, gem_file] if spec.name == dep.name
- end
- end
-
- if @domain == :both or @domain == :remote then
- begin
- # REFACTOR: all = dep.requirement.needs_all?
- requirements = dep.requirement.requirements.map do |req, ver|
- req
- end
-
- all = !dep.prerelease? &&
- # we only need latest if there's one requirement and it is
- # guaranteed to match the newest specs
- (requirements.length > 1 or
- (requirements.first != ">=" and requirements.first != ">"))
-
- found, @errors = Gem::SpecFetcher.fetcher.fetch_with_errors dep, all, true, dep.prerelease?
-
- gems_and_sources.push(*found)
-
- rescue Gem::RemoteFetcher::FetchError => e
- if Gem.configuration.really_verbose then
- say "Error fetching remote data:\t\t#{e.message}"
- say "Falling back to local-only install"
- end
- @domain = :local
- end
- end
-
- gems_and_sources.sort_by do |gem, source|
- [gem, source =~ /^http:\/\// ? 0 : 1] # local gems win
- end
- end
-
- ##
- # Gathers all dependencies necessary for the installation from local and
- # remote sources unless the ignore_dependencies was given.
-
- def gather_dependencies
- specs = @specs_and_sources.map { |spec,_| spec }
-
- # these gems were listed by the user, always install them
- keep_names = specs.map { |spec| spec.full_name }
-
- dependency_list = Gem::DependencyList.new @development
- dependency_list.add(*specs)
- to_do = specs.dup
-
- add_found_dependencies to_do, dependency_list unless @ignore_dependencies
-
- dependency_list.specs.reject! { |spec|
- not keep_names.include?(spec.full_name) and
- Gem::Specification.include?(spec)
- }
-
- unless dependency_list.ok? or @ignore_dependencies or @force then
- reason = dependency_list.why_not_ok?.map { |k,v|
- "#{k} requires #{v.join(", ")}"
- }.join("; ")
- raise Gem::DependencyError, "Unable to resolve dependencies: #{reason}"
- end
-
- @gems_to_install = dependency_list.dependency_order.reverse
- end
-
- def add_found_dependencies to_do, dependency_list
- seen = {}
- dependencies = Hash.new { |h, name| h[name] = Gem::Dependency.new name }
-
- until to_do.empty? do
- spec = to_do.shift
- next if spec.nil? or seen[spec.name]
- seen[spec.name] = true
-
- deps = spec.runtime_dependencies
- deps |= spec.development_dependencies if @development
-
- deps.each do |dep|
- dependencies[dep.name] = dependencies[dep.name].merge dep
-
- results = find_gems_with_sources(dep).reverse
-
- results.reject! do |dep_spec,|
- to_do.push dep_spec
-
- # already locally installed
- Gem::Specification.any? do |installed_spec|
- dep.name == installed_spec.name and
- dep.requirement.satisfied_by? installed_spec.version
- end
- end
-
- results.each do |dep_spec, source_uri|
- @specs_and_sources << [dep_spec, source_uri]
-
- dependency_list.add dep_spec
- end
- end
- end
-
- dependency_list.remove_specs_unsatisfied_by dependencies
- end
-
- ##
- # Finds a spec and the source_uri it came from for gem +gem_name+ and
- # +version+. Returns an Array of specs and sources required for
- # installation of the gem.
-
- def find_spec_by_name_and_version(gem_name,
- version = Gem::Requirement.default,
- prerelease = false)
- spec_and_source = nil
-
- glob = if File::ALT_SEPARATOR then
- gem_name.gsub File::ALT_SEPARATOR, File::SEPARATOR
- else
- gem_name
- end
-
- local_gems = Dir["#{glob}*"].sort.reverse
-
- local_gems.each do |gem_file|
- next unless gem_file =~ /gem$/
- begin
- spec = Gem::Format.from_file_by_path(gem_file).spec
- spec_and_source = [spec, gem_file]
- break
- rescue SystemCallError, Gem::Package::FormatError
- end
- end
-
- unless spec_and_source then
- dep = Gem::Dependency.new gem_name, version
- dep.prerelease = true if prerelease
- spec_and_sources = find_gems_with_sources(dep).reverse
- spec_and_source = spec_and_sources.find { |spec, source|
- Gem::Platform.match spec.platform
- }
- end
-
- if spec_and_source.nil? then
- raise Gem::GemNotFoundException.new(
- "Could not find a valid gem '#{gem_name}' (#{version}) locally or in a repository",
- gem_name, version, @errors)
- end
-
- @specs_and_sources = [spec_and_source]
- end
-
- ##
- # Installs the gem +dep_or_name+ and all its dependencies. Returns an Array
- # of installed gem specifications.
- #
- # If the +:prerelease+ option is set and there is a prerelease for
- # +dep_or_name+ the prerelease version will be installed.
- #
- # Unless explicitly specified as a prerelease dependency, prerelease gems
- # that +dep_or_name+ depend on will not be installed.
- #
- # If c-1.a depends on b-1 and a-1.a and there is a gem b-1.a available then
- # c-1.a, b-1 and a-1.a will be installed. b-1.a will need to be installed
- # separately.
-
- def install dep_or_name, version = Gem::Requirement.default
- if String === dep_or_name then
- find_spec_by_name_and_version dep_or_name, version, @prerelease
- else
- dep_or_name.prerelease = @prerelease
- @specs_and_sources = [find_gems_with_sources(dep_or_name).last]
- end
-
- @installed_gems = []
-
- gather_dependencies
-
- last = @gems_to_install.size - 1
- @gems_to_install.each_with_index do |spec, index|
- next if Gem::Specification.include?(spec) and index != last
-
- # TODO: make this sorta_verbose so other users can benefit from it
- say "Installing gem #{spec.full_name}" if Gem.configuration.really_verbose
-
- _, source_uri = @specs_and_sources.assoc spec
- begin
- local_gem_path = Gem::RemoteFetcher.fetcher.download spec, source_uri,
- @cache_dir
- rescue Gem::RemoteFetcher::FetchError
- next if @force
- raise
- end
-
- inst = Gem::Installer.new local_gem_path,
- :bin_dir => @bin_dir,
- :development => @development,
- :env_shebang => @env_shebang,
- :force => @force,
- :format_executable => @format_executable,
- :ignore_dependencies => @ignore_dependencies,
- :install_dir => @install_dir,
- :security_policy => @security_policy,
- :user_install => @user_install,
- :wrappers => @wrappers
-
- spec = inst.install
-
- @installed_gems << spec
- end
-
- @installed_gems
- end
-end
diff --git a/ruby_1_9_3/lib/rubygems/dependency_list.rb b/ruby_1_9_3/lib/rubygems/dependency_list.rb
deleted file mode 100644
index 9f1da9166c..0000000000
--- a/ruby_1_9_3/lib/rubygems/dependency_list.rb
+++ /dev/null
@@ -1,252 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-require 'tsort'
-require 'rubygems/deprecate'
-
-##
-# Gem::DependencyList is used for installing and uninstalling gems in the
-# correct order to avoid conflicts.
-
-class Gem::DependencyList
- attr_reader :specs
-
- include Enumerable
- include TSort
-
- ##
- # Allows enabling/disabling use of development dependencies
-
- attr_accessor :development
-
- ##
- # Creates a DependencyList from the current specs.
-
- def self.from_specs
- list = new
- list.add(*Gem::Specification.map)
- list
- end
-
- ##
- # Creates a DependencyList from a Gem::SourceIndex +source_index+
-
- def self.from_source_index(ignored=nil)
- warn "NOTE: DependencyList.from_source_index ignores it's arg" if ignored
-
- from_specs
- end
-
- ##
- # Creates a new DependencyList. If +development+ is true, development
- # dependencies will be included.
-
- def initialize development = false
- @specs = []
-
- @development = development
- end
-
- ##
- # Adds +gemspecs+ to the dependency list.
-
- def add(*gemspecs)
- @specs.push(*gemspecs)
- end
-
- def clear
- @specs.clear
- end
-
- ##
- # Return a list of the gem specifications in the dependency list, sorted in
- # order so that no gemspec in the list depends on a gemspec earlier in the
- # list.
- #
- # This is useful when removing gems from a set of installed gems. By
- # removing them in the returned order, you don't get into as many dependency
- # issues.
- #
- # If there are circular dependencies (yuck!), then gems will be returned in
- # order until only the circular dependents and anything they reference are
- # left. Then arbitrary gemspecs will be returned until the circular
- # dependency is broken, after which gems will be returned in dependency
- # order again.
-
- def dependency_order
- sorted = strongly_connected_components.flatten
-
- result = []
- seen = {}
-
- sorted.each do |spec|
- if index = seen[spec.name] then
- if result[index].version < spec.version then
- result[index] = spec
- end
- else
- seen[spec.name] = result.length
- result << spec
- end
- end
-
- result.reverse
- end
-
- ##
- # Iterator over dependency_order
-
- def each(&block)
- dependency_order.each(&block)
- end
-
- def find_name(full_name)
- @specs.find { |spec| spec.full_name == full_name }
- end
-
- def inspect # :nodoc:
- "#<%s:0x%x %p>" % [self.class, object_id, map { |s| s.full_name }]
- end
-
- ##
- # Are all the dependencies in the list satisfied?
-
- def ok?
- why_not_ok?(:quick).empty?
- end
-
- def why_not_ok? quick = false
- unsatisfied = Hash.new { |h,k| h[k] = [] }
- each do |spec|
- spec.runtime_dependencies.each do |dep|
- inst = Gem::Specification.any? { |installed_spec|
- dep.name == installed_spec.name and
- dep.requirement.satisfied_by? installed_spec.version
- }
-
- unless inst or @specs.find { |s| s.satisfies_requirement? dep } then
- unsatisfied[spec.name] << dep
- return unsatisfied if quick
- end
- end
- end
-
- unsatisfied
- end
-
- ##
- # Is is ok to remove a gemspec from the dependency list?
- #
- # If removing the gemspec creates breaks a currently ok dependency, then it
- # is NOT ok to remove the gemspec.
-
- def ok_to_remove?(full_name)
- gem_to_remove = find_name full_name
-
- siblings = @specs.find_all { |s|
- s.name == gem_to_remove.name &&
- s.full_name != gem_to_remove.full_name
- }
-
- deps = []
-
- @specs.each do |spec|
- spec.dependencies.each do |dep|
- deps << dep if gem_to_remove.satisfies_requirement?(dep)
- end
- end
-
- deps.all? { |dep|
- siblings.any? { |s|
- s.satisfies_requirement? dep
- }
- }
- end
-
- ##
- # Remove everything in the DependencyList that matches but doesn't
- # satisfy items in +dependencies+ (a hash of gem names to arrays of
- # dependencies).
-
- def remove_specs_unsatisfied_by dependencies
- specs.reject! { |spec|
- dep = dependencies[spec.name]
- dep and not dep.requirement.satisfied_by? spec.version
- }
- end
-
- ##
- # Removes the gemspec matching +full_name+ from the dependency list
-
- def remove_by_name(full_name)
- @specs.delete_if { |spec| spec.full_name == full_name }
- end
-
- ##
- # Return a hash of predecessors. <tt>result[spec]</tt> is an Array of
- # gemspecs that have a dependency satisfied by the named gemspec.
-
- def spec_predecessors
- result = Hash.new { |h,k| h[k] = [] }
-
- specs = @specs.sort.reverse
-
- specs.each do |spec|
- specs.each do |other|
- next if spec == other
-
- other.dependencies.each do |dep|
- if spec.satisfies_requirement? dep then
- result[spec] << other
- end
- end
- end
- end
-
- result
- end
-
- def tsort_each_node(&block)
- @specs.each(&block)
- end
-
- def tsort_each_child(node, &block)
- specs = @specs.sort.reverse
-
- dependencies = node.runtime_dependencies
- dependencies.push(*node.development_dependencies) if @development
-
- dependencies.each do |dep|
- specs.each do |spec|
- if spec.satisfies_requirement? dep then
- begin
- yield spec
- rescue TSort::Cyclic
- # do nothing
- end
- break
- end
- end
- end
- end
-
- private
-
- ##
- # Count the number of gemspecs in the list +specs+ that are not in
- # +ignored+.
-
- def active_count(specs, ignored)
- specs.count { |spec| ignored[spec.full_name].nil? }
- end
-end
-
-class Gem::DependencyList
- class << self
- extend Gem::Deprecate
- deprecate :from_source_index, "from_specs", 2011, 11
- end
-end
diff --git a/ruby_1_9_3/lib/rubygems/deprecate.rb b/ruby_1_9_3/lib/rubygems/deprecate.rb
deleted file mode 100644
index a78208ec24..0000000000
--- a/ruby_1_9_3/lib/rubygems/deprecate.rb
+++ /dev/null
@@ -1,70 +0,0 @@
-##
-# Provides a single method +deprecate+ to be used to declare when
-# something is going away.
-#
-# class Legacy
-# def self.klass_method
-# # ...
-# end
-#
-# def instance_method
-# # ...
-# end
-#
-# extend Gem::Deprecate
-# deprecate :instance_method, "X.z", 2011, 4
-#
-# class << self
-# extend Gem::Deprecate
-# deprecate :klass_method, :none, 2011, 4
-# end
-# end
-
-module Gem
- module Deprecate
-
- def self.skip # :nodoc:
- @skip ||= false
- end
-
- def self.skip= v # :nodoc:
- @skip = v
- end
-
- ##
- # Temporarily turn off warnings. Intended for tests only.
-
- def skip_during
- Gem::Deprecate.skip, original = true, Gem::Deprecate.skip
- yield
- ensure
- Gem::Deprecate.skip = original
- end
-
- ##
- # Simple deprecation method that deprecates +name+ by wrapping it up
- # in a dummy method. It warns on each call to the dummy method
- # telling the user of +repl+ (unless +repl+ is :none) and the
- # year/month that it is planned to go away.
-
- def deprecate name, repl, year, month
- class_eval {
- old = "_deprecated_#{name}"
- alias_method old, name
- define_method name do |*args, &block| # TODO: really works on 1.8.7?
- klass = self.kind_of? Module
- target = klass ? "#{self}." : "#{self.class}#"
- msg = [ "NOTE: #{target}#{name} is deprecated",
- repl == :none ? " with no replacement" : ", use #{repl}",
- ". It will be removed on or after %4d-%02d-01." % [year, month],
- "\n#{target}#{name} called from #{Gem.location_of_caller.join(":")}",
- ]
- warn "#{msg.join}." unless Gem::Deprecate.skip
- send old, *args, &block
- end
- }
- end
-
- module_function :deprecate, :skip_during
- end
-end
diff --git a/ruby_1_9_3/lib/rubygems/doc_manager.rb b/ruby_1_9_3/lib/rubygems/doc_manager.rb
deleted file mode 100644
index 826f57d9dd..0000000000
--- a/ruby_1_9_3/lib/rubygems/doc_manager.rb
+++ /dev/null
@@ -1,243 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-require 'rubygems'
-
-##
-# The documentation manager generates RDoc and RI for RubyGems.
-
-class Gem::DocManager
-
- include Gem::UserInteraction
-
- @configured_args = []
-
- def self.configured_args
- @configured_args ||= []
- end
-
- def self.configured_args=(args)
- case args
- when Array
- @configured_args = args
- when String
- @configured_args = args.split
- end
- end
-
- ##
- # Load RDoc from a gem if it is available, otherwise from Ruby's stdlib
-
- def self.load_rdoc
- begin
- gem 'rdoc'
- rescue Gem::LoadError
- # use built-in RDoc
- end
-
- begin
- require 'rdoc/rdoc'
-
- @rdoc_version = if defined? RDoc::VERSION then
- Gem::Version.new RDoc::VERSION
- else
- Gem::Version.new '1.0.1' # HACK parsing is hard
- end
-
- rescue LoadError => e
- raise Gem::DocumentError,
- "ERROR: RDoc documentation generator not installed: #{e}"
- end
- end
-
- def self.rdoc_version
- @rdoc_version
- end
-
- ##
- # Updates the RI cache for RDoc 2 if it is installed
-
- def self.update_ri_cache
- load_rdoc rescue return
-
- return unless defined? RDoc::VERSION # RDoc 1 does not have VERSION
-
- require 'rdoc/ri/driver'
-
- options = {
- :use_cache => true,
- :use_system => true,
- :use_site => true,
- :use_home => true,
- :use_gems => true,
- :formatter => RDoc::RI::Formatter,
- }
-
- RDoc::RI::Driver.new(options).class_cache
- end
-
- ##
- # Create a document manager for +spec+. +rdoc_args+ contains arguments for
- # RDoc (template etc.) as a String.
-
- def initialize(spec, rdoc_args="")
- require 'fileutils'
- @spec = spec
- @doc_dir = spec.doc_dir
- @rdoc_args = rdoc_args.nil? ? [] : rdoc_args.split
- end
-
- ##
- # Is the RDoc documentation installed?
-
- def rdoc_installed?
- File.exist?(File.join(@doc_dir, "rdoc"))
- end
-
- ##
- # Is the RI documentation installed?
-
- def ri_installed?
- File.exist?(File.join(@doc_dir, "ri"))
- end
-
- ##
- # Generate the RI documents for this gem spec.
- #
- # Note that if both RI and RDoc documents are generated from the same
- # process, the RI docs should be done first (a likely bug in RDoc will cause
- # RI docs generation to fail if run after RDoc).
-
- def generate_ri
- setup_rdoc
- install_ri # RDoc bug, ri goes first
-
- FileUtils.mkdir_p @doc_dir unless File.exist?(@doc_dir)
- end
-
- ##
- # Generate the RDoc documents for this gem spec.
- #
- # Note that if both RI and RDoc documents are generated from the same
- # process, the RI docs should be done first (a likely bug in RDoc will cause
- # RI docs generation to fail if run after RDoc).
-
- def generate_rdoc
- setup_rdoc
- install_rdoc
-
- FileUtils.mkdir_p @doc_dir unless File.exist?(@doc_dir)
- end
-
- ##
- # Generate and install RDoc into the documentation directory
-
- def install_rdoc
- rdoc_dir = File.join @doc_dir, 'rdoc'
-
- FileUtils.rm_rf rdoc_dir
-
- say "Installing RDoc documentation for #{@spec.full_name}..."
- run_rdoc '--op', rdoc_dir
- end
-
- ##
- # Generate and install RI into the documentation directory
-
- def install_ri
- ri_dir = File.join @doc_dir, 'ri'
-
- FileUtils.rm_rf ri_dir
-
- say "Installing ri documentation for #{@spec.full_name}..."
- run_rdoc '--ri', '--op', ri_dir
- end
-
- ##
- # Run RDoc with +args+, which is an ARGV style argument list
-
- def run_rdoc(*args)
- args << @spec.rdoc_options
- args << self.class.configured_args
- args << @spec.require_paths.clone
- args << @spec.extra_rdoc_files
- args << '--title' << "#{@spec.full_name} Documentation"
- args << '--quiet'
- args = args.flatten.map do |arg| arg.to_s end
-
- if self.class.rdoc_version >= Gem::Version.new('2.4.0') then
- args.delete '--inline-source'
- args.delete '--promiscuous'
- args.delete '-p'
- args.delete '--one-file'
- # HACK more
- end
-
- debug_args = args.dup
-
- r = RDoc::RDoc.new
-
- old_pwd = Dir.pwd
- Dir.chdir @spec.full_gem_path
-
- say "rdoc #{args.join ' '}" if Gem.configuration.really_verbose
-
- begin
- r.document args
- rescue Errno::EACCES => e
- dirname = File.dirname e.message.split("-")[1].strip
- raise Gem::FilePermissionError.new(dirname)
- rescue Interrupt => e
- raise e
- rescue Exception => ex
- alert_error "While generating documentation for #{@spec.full_name}"
- ui.errs.puts "... MESSAGE: #{ex}"
- ui.errs.puts "... RDOC args: #{debug_args.join(' ')}"
- ui.errs.puts "\t#{ex.backtrace.join "\n\t"}" if
- Gem.configuration.backtrace
- terminate_interaction 1
- ensure
- Dir.chdir old_pwd
- end
- end
-
- def setup_rdoc
- if File.exist?(@doc_dir) && !File.writable?(@doc_dir) then
- raise Gem::FilePermissionError.new(@doc_dir)
- end
-
- FileUtils.mkdir_p @doc_dir unless File.exist?(@doc_dir)
-
- self.class.load_rdoc
- end
-
- ##
- # Remove RDoc and RI documentation
-
- def uninstall_doc
- base_dir = @spec.base_dir
- raise Gem::FilePermissionError.new base_dir unless File.writable? base_dir
-
- # TODO: ok... that's twice... ugh
- old_name = [
- @spec.name, @spec.version, @spec.original_platform].join '-'
-
- doc_dir = @spec.doc_dir
- unless File.directory? doc_dir then
- doc_dir = File.join File.dirname(doc_dir), old_name
- end
-
- ri_dir = @spec.ri_dir
- unless File.directory? ri_dir then
- ri_dir = File.join File.dirname(ri_dir), old_name
- end
-
- FileUtils.rm_rf doc_dir
- FileUtils.rm_rf ri_dir
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/errors.rb b/ruby_1_9_3/lib/rubygems/errors.rb
deleted file mode 100644
index 950b34d744..0000000000
--- a/ruby_1_9_3/lib/rubygems/errors.rb
+++ /dev/null
@@ -1,35 +0,0 @@
-class Gem::ErrorReason; end
-
-# Generated when trying to lookup a gem to indicate that the gem
-# was found, but that it isn't usable on the current platform.
-#
-# fetch and install read these and report them to the user to aid
-# in figuring out why a gem couldn't be installed.
-#
-class Gem::PlatformMismatch < Gem::ErrorReason
-
- attr_reader :name
- attr_reader :version
- attr_reader :platforms
-
- def initialize(name, version)
- @name = name
- @version = version
- @platforms = []
- end
-
- def add_platform(platform)
- @platforms << platform
- end
-
- def wordy
- prefix = "Found #{@name} (#{@version})"
-
- if @platforms.size == 1
- "#{prefix}, but was for platform #{@platforms[0]}"
- else
- "#{prefix}, but was for platforms #{@platforms.join(' ,')}"
- end
- end
-
-end
diff --git a/ruby_1_9_3/lib/rubygems/exceptions.rb b/ruby_1_9_3/lib/rubygems/exceptions.rb
deleted file mode 100644
index 55d67f9125..0000000000
--- a/ruby_1_9_3/lib/rubygems/exceptions.rb
+++ /dev/null
@@ -1,91 +0,0 @@
-##
-# Base exception class for RubyGems. All exception raised by RubyGems are a
-# subclass of this one.
-class Gem::Exception < RuntimeError; end
-
-class Gem::CommandLineError < Gem::Exception; end
-
-class Gem::DependencyError < Gem::Exception; end
-
-class Gem::DependencyRemovalException < Gem::Exception; end
-
-##
-# Raised when attempting to uninstall a gem that isn't in GEM_HOME.
-
-class Gem::GemNotInHomeException < Gem::Exception
- attr_accessor :spec
-end
-
-class Gem::DocumentError < Gem::Exception; end
-
-##
-# Potentially raised when a specification is validated.
-class Gem::EndOfYAMLException < Gem::Exception; end
-
-##
-# Signals that a file permission error is preventing the user from
-# installing in the requested directories.
-class Gem::FilePermissionError < Gem::Exception
- def initialize(path)
- super("You don't have write permissions into the #{path} directory.")
- end
-end
-
-##
-# Used to raise parsing and loading errors
-class Gem::FormatException < Gem::Exception
- attr_accessor :file_path
-end
-
-class Gem::GemNotFoundException < Gem::Exception
- def initialize(msg, name=nil, version=nil, errors=nil)
- super msg
- @name = name
- @version = version
- @errors = errors
- end
-
- attr_reader :name, :version, :errors
-end
-
-class Gem::InstallError < Gem::Exception; end
-
-##
-# Potentially raised when a specification is validated.
-class Gem::InvalidSpecificationException < Gem::Exception; end
-
-class Gem::OperationNotSupportedError < Gem::Exception; end
-
-##
-# Signals that a remote operation cannot be conducted, probably due to not
-# being connected (or just not finding host).
-#--
-# TODO: create a method that tests connection to the preferred gems server.
-# All code dealing with remote operations will want this. Failure in that
-# method should raise this error.
-class Gem::RemoteError < Gem::Exception; end
-
-class Gem::RemoteInstallationCancelled < Gem::Exception; end
-
-class Gem::RemoteInstallationSkipped < Gem::Exception; end
-
-##
-# Represents an error communicating via HTTP.
-class Gem::RemoteSourceException < Gem::Exception; end
-
-class Gem::VerificationError < Gem::Exception; end
-
-##
-# Raised to indicate that a system exit should occur with the specified
-# exit_code
-
-class Gem::SystemExitException < SystemExit
- attr_accessor :exit_code
-
- def initialize(exit_code)
- @exit_code = exit_code
-
- super "Exiting RubyGems with exit_code #{exit_code}"
- end
-
-end
diff --git a/ruby_1_9_3/lib/rubygems/ext.rb b/ruby_1_9_3/lib/rubygems/ext.rb
deleted file mode 100644
index 97ee762a4a..0000000000
--- a/ruby_1_9_3/lib/rubygems/ext.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-require 'rubygems'
-
-##
-# Classes for building C extensions live here.
-
-module Gem::Ext; end
-
-require 'rubygems/ext/builder'
-require 'rubygems/ext/configure_builder'
-require 'rubygems/ext/ext_conf_builder'
-require 'rubygems/ext/rake_builder'
-
diff --git a/ruby_1_9_3/lib/rubygems/ext/builder.rb b/ruby_1_9_3/lib/rubygems/ext/builder.rb
deleted file mode 100644
index 5e518962ce..0000000000
--- a/ruby_1_9_3/lib/rubygems/ext/builder.rb
+++ /dev/null
@@ -1,56 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-class Gem::Ext::Builder
-
- def self.class_name
- name =~ /Ext::(.*)Builder/
- $1.downcase
- end
-
- def self.make(dest_path, results)
- unless File.exist? 'Makefile' then
- raise Gem::InstallError, "Makefile not found:\n\n#{results.join "\n"}"
- end
-
- mf = File.read('Makefile')
- mf = mf.gsub(/^RUBYARCHDIR\s*=\s*\$[^$]*/, "RUBYARCHDIR = #{dest_path}")
- mf = mf.gsub(/^RUBYLIBDIR\s*=\s*\$[^$]*/, "RUBYLIBDIR = #{dest_path}")
-
- File.open('Makefile', 'wb') {|f| f.print mf}
-
- # try to find make program from Ruby configure arguments first
- RbConfig::CONFIG['configure_args'] =~ /with-make-prog\=(\w+)/
- make_program = $1 || ENV['make']
- unless make_program then
- make_program = (/mswin/ =~ RUBY_PLATFORM) ? 'nmake' : 'make'
- end
-
- ['', ' install'].each do |target|
- cmd = "#{make_program}#{target}"
- results << cmd
- results << `#{cmd} #{redirector}`
-
- raise Gem::InstallError, "make#{target} failed:\n\n#{results}" unless
- $?.success?
- end
- end
-
- def self.redirector
- '2>&1'
- end
-
- def self.run(command, results)
- results << command
- results << `#{command} #{redirector}`
-
- unless $?.success? then
- raise Gem::InstallError, "#{class_name} failed:\n\n#{results.join "\n"}"
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/ext/configure_builder.rb b/ruby_1_9_3/lib/rubygems/ext/configure_builder.rb
deleted file mode 100644
index c2087eb5ad..0000000000
--- a/ruby_1_9_3/lib/rubygems/ext/configure_builder.rb
+++ /dev/null
@@ -1,25 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-require 'rubygems/ext/builder'
-
-class Gem::Ext::ConfigureBuilder < Gem::Ext::Builder
-
- def self.build(extension, directory, dest_path, results)
- unless File.exist?('Makefile') then
- cmd = "sh ./configure --prefix=#{dest_path}"
- cmd << " #{Gem::Command.build_args.join ' '}" unless Gem::Command.build_args.empty?
-
- run cmd, results
- end
-
- make dest_path, results
-
- results
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/ext/ext_conf_builder.rb b/ruby_1_9_3/lib/rubygems/ext/ext_conf_builder.rb
deleted file mode 100644
index b3d588dc9c..0000000000
--- a/ruby_1_9_3/lib/rubygems/ext/ext_conf_builder.rb
+++ /dev/null
@@ -1,24 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-require 'rubygems/ext/builder'
-require 'rubygems/command'
-
-class Gem::Ext::ExtConfBuilder < Gem::Ext::Builder
-
- def self.build(extension, directory, dest_path, results)
- cmd = "#{Gem.ruby} #{File.basename extension}"
- cmd << " #{Gem::Command.build_args.join ' '}" unless Gem::Command.build_args.empty?
-
- run cmd, results
-
- make dest_path, results
-
- results
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/ext/rake_builder.rb b/ruby_1_9_3/lib/rubygems/ext/rake_builder.rb
deleted file mode 100644
index a1df694366..0000000000
--- a/ruby_1_9_3/lib/rubygems/ext/rake_builder.rb
+++ /dev/null
@@ -1,39 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-require 'rubygems/ext/builder'
-require 'rubygems/command'
-
-class Gem::Ext::RakeBuilder < Gem::Ext::Builder
-
- def self.build(extension, directory, dest_path, results)
- if File.basename(extension) =~ /mkrf_conf/i then
- cmd = "#{Gem.ruby} #{File.basename extension}"
- cmd << " #{Gem::Command.build_args.join " "}" unless Gem::Command.build_args.empty?
- run cmd, results
- end
-
- # Deal with possible spaces in the path, e.g. C:/Program Files
- dest_path = '"' + dest_path.to_s + '"' if dest_path.to_s.include?(' ')
-
- rake = ENV['rake']
-
- rake ||= begin
- "\"#{Gem.ruby}\" -rubygems #{Gem.bin_path('rake', 'rake')}"
- rescue Gem::Exception
- end
-
- rake ||= Gem.default_exec_format % 'rake'
-
- cmd = "#{rake} RUBYARCHDIR=#{dest_path} RUBYLIBDIR=#{dest_path}" # ENV is frozen
-
- run cmd, results
-
- results
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/format.rb b/ruby_1_9_3/lib/rubygems/format.rb
deleted file mode 100644
index 9644f6ab8e..0000000000
--- a/ruby_1_9_3/lib/rubygems/format.rb
+++ /dev/null
@@ -1,82 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-require 'rubygems/package'
-
-##
-# Gem::Format knows the guts of the RubyGem .gem file format and provides the
-# capability to read gem files
-
-class Gem::Format
-
- attr_accessor :spec
- attr_accessor :file_entries
- attr_accessor :gem_path
-
- ##
- # Constructs a Format representing the gem's data which came from +gem_path+
-
- def initialize(gem_path)
- @gem_path = gem_path
- end
-
- ##
- # Reads the gem +file_path+ using +security_policy+ and returns a Format
- # representing the data in the gem
-
- def self.from_file_by_path(file_path, security_policy = nil)
- unless File.file?(file_path)
- raise Gem::Exception, "Cannot load gem at [#{file_path}] in #{Dir.pwd}"
- end
-
- start = File.read file_path, 20
-
- if start.nil? or start.length < 20 then
- nil
- elsif start.include?("MD5SUM =") # old version gems
- require 'rubygems/old_format'
-
- Gem::OldFormat.from_file_by_path file_path
- else
- begin
- open file_path, Gem.binary_mode do |io|
- from_io io, file_path, security_policy
- end
- rescue Gem::Package::TarInvalidError => e
- message = "corrupt gem (#{e.class}: #{e.message})"
- raise Gem::Package::FormatError.new(message, file_path)
- end
- end
- end
-
- ##
- # Reads a gem from +io+ at +gem_path+ using +security_policy+ and returns a
- # Format representing the data from the gem
-
- def self.from_io(io, gem_path="(io)", security_policy = nil)
- format = new gem_path
-
- Gem::Package.open io, 'r', security_policy do |pkg|
- format.spec = pkg.metadata
- format.file_entries = []
-
- pkg.each do |entry|
- size = entry.header.size
- mode = entry.header.mode
-
- format.file_entries << [{
- "size" => size, "mode" => mode, "path" => entry.full_name,
- },
- entry.read
- ]
- end
- end
-
- format
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/gem_openssl.rb b/ruby_1_9_3/lib/rubygems/gem_openssl.rb
deleted file mode 100644
index 682058f2c1..0000000000
--- a/ruby_1_9_3/lib/rubygems/gem_openssl.rb
+++ /dev/null
@@ -1,90 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-#--
-# Some system might not have OpenSSL installed, therefore the core
-# library file openssl might not be available. We localize testing
-# for the presence of OpenSSL in this file.
-#++
-
-module Gem
- class << self
- ##
- # Is SSL (used by the signing commands) available on this
- # platform?
-
- def ssl_available?
- @ssl_available
- end
-
- ##
- # Is SSL available?
-
- attr_writer :ssl_available
-
- ##
- # Ensure that SSL is available. Throw an exception if it is not.
-
- def ensure_ssl_available
- unless ssl_available?
- raise Gem::Exception, "SSL is not installed on this system"
- end
- end
- end
-end
-
-# :stopdoc:
-
-begin
- require 'openssl'
-
- # Reference a constant defined in the .rb portion of ssl (just to
- # make sure that part is loaded too).
-
- Gem.ssl_available = !!OpenSSL::Digest::SHA1
-
- class OpenSSL::X509::Certificate
- # Check the validity of this certificate.
- def check_validity(issuer_cert = nil, time = Time.now)
- ret = if @not_before && @not_before > time
- [false, :expired, "not valid before '#@not_before'"]
- elsif @not_after && @not_after < time
- [false, :expired, "not valid after '#@not_after'"]
- elsif issuer_cert && !verify(issuer_cert.public_key)
- [false, :issuer, "#{issuer_cert.subject} is not issuer"]
- else
- [true, :ok, 'Valid certificate']
- end
-
- # return hash
- { :is_valid => ret[0], :error => ret[1], :desc => ret[2] }
- end
- end
-
-rescue LoadError, StandardError
- Gem.ssl_available = false
-end
-
-module Gem::SSL
-
- # We make our own versions of the constants here. This allows us
- # to reference the constants, even though some systems might not
- # have SSL installed in the Ruby core package.
- #
- # These constants are only used during load time. At runtime, any
- # method that makes a direct reference to SSL software must be
- # protected with a Gem.ensure_ssl_available call.
-
- if Gem.ssl_available? then
- PKEY_RSA = OpenSSL::PKey::RSA
- DIGEST_SHA1 = OpenSSL::Digest::SHA1
- else
- PKEY_RSA = :rsa
- DIGEST_SHA1 = :sha1
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/gem_path_searcher.rb b/ruby_1_9_3/lib/rubygems/gem_path_searcher.rb
deleted file mode 100644
index 814b5fb0e5..0000000000
--- a/ruby_1_9_3/lib/rubygems/gem_path_searcher.rb
+++ /dev/null
@@ -1,172 +0,0 @@
-require "rubygems"
-require "rubygems/deprecate"
-
-##
-# GemPathSearcher has the capability to find loadable files inside
-# gems. It generates data up front to speed up searches later.
-
-class Gem::GemPathSearcher
-
- ##
- # Initialise the data we need to make searches later.
-
- def initialize
- # We want a record of all the installed gemspecs, in the order we wish to
- # examine them.
- # TODO: remove this stupid method
- @gemspecs = init_gemspecs
-
- # Map gem spec to glob of full require_path directories. Preparing this
- # information may speed up searches later.
- @lib_dirs = {}
-
- @gemspecs.each do |spec|
- @lib_dirs[spec.object_id] = lib_dirs_for spec
- end
- end
-
- ##
- # Look in all the installed gems until a matching +glob+ is found.
- # Return the _gemspec_ of the gem where it was found. If no match
- # is found, return nil.
- #
- # The gems are searched in alphabetical order, and in reverse
- # version order.
- #
- # For example:
- #
- # find('log4r') # -> (log4r-1.1 spec)
- # find('log4r.rb') # -> (log4r-1.1 spec)
- # find('rake/rdoctask') # -> (rake-0.4.12 spec)
- # find('foobarbaz') # -> nil
- #
- # Matching paths can have various suffixes ('.rb', '.so', and
- # others), which may or may not already be attached to _file_.
- # This method doesn't care about the full filename that matches;
- # only that there is a match.
-
- def find(glob)
- # HACK violation of encapsulation
- @gemspecs.find do |spec|
- # TODO: inverted responsibility
- matching_file? spec, glob
- end
- end
-
- # Looks through the available gemspecs and finds the first
- # one that contains +file+ as a requirable file.
-
- def find_spec_for_file(file)
- @gemspecs.find do |spec|
- return spec if spec.contains_requirable_file?(file)
- end
- end
-
- def find_active(glob)
- # HACK violation of encapsulation
- @gemspecs.find do |spec|
- # TODO: inverted responsibility
- spec.loaded? and matching_file? spec, glob
- end
- end
-
- ##
- # Works like #find, but finds all gemspecs matching +glob+.
-
- def find_all(glob)
- # HACK violation of encapsulation
- @gemspecs.select do |spec|
- # TODO: inverted responsibility
- matching_file? spec, glob
- end || []
- end
-
- def find_in_unresolved(glob)
- # HACK violation
- specs = Gem.unresolved_deps.values.map { |dep|
- Gem.source_index.search dep, true
- }.flatten
-
- specs.select do |spec|
- # TODO: inverted responsibility
- matching_file? spec, glob
- end || []
- end
-
- def find_in_unresolved_tree glob
- # HACK violation
- # TODO: inverted responsibility
- specs = Gem.unresolved_deps.values.map { |dep|
- Gem.source_index.search dep, true
- }.flatten
-
- specs.reverse_each do |spec|
- trails = matching_paths(spec, glob)
- next if trails.empty?
- return trails.map(&:reverse).sort.first.reverse
- end
-
- []
- end
-
- ##
- # Attempts to find a matching path using the require_paths of the given
- # +spec+.
-
- def matching_file?(spec, path)
- not matching_files(spec, path).empty?
- end
-
- def matching_paths(spec, path)
- trails = []
-
- spec.traverse do |from_spec, dep, to_spec, trail|
- next unless to_spec.conflicts.empty?
- trails << trail unless matching_files(to_spec, path).empty?
- end
-
- trails
- end
-
- ##
- # Returns files matching +path+ in +spec+.
- #--
- # Some of the intermediate results are cached in @lib_dirs for speed.
-
- def matching_files(spec, path)
- return [] unless @lib_dirs[spec.object_id] # case no paths
- glob = File.join @lib_dirs[spec.object_id], "#{path}#{Gem.suffix_pattern}"
- Dir[glob].select { |f| File.file? f.untaint }
- end
-
- ##
- # Return a list of all installed gemspecs, sorted by alphabetical order and
- # in reverse version order. (bar-2, bar-1, foo-2)
-
- def init_gemspecs
- Gem::Specification.sort { |a, b|
- names = a.name <=> b.name
- next names if names.nonzero?
- b.version <=> a.version
- }
- end
-
- ##
- # Returns library directories glob for a gemspec. For example,
- # '/usr/local/lib/ruby/gems/1.8/gems/foobar-1.0/{lib,ext}'
-
- def lib_dirs_for(spec)
- "#{spec.full_gem_path}/{#{spec.require_paths.join(',')}}" if
- spec.require_paths
- end
-
- extend Gem::Deprecate
-
- deprecate :initialize, :none, 2011, 10
- deprecate :find, :none, 2011, 10
- deprecate :find_active, :none, 2011, 10
- deprecate :find_all, :none, 2011, 10
- deprecate :find_in_unresolved, :none, 2011, 10
- deprecate :find_in_unresolved_tree, :none, 2011, 10
- deprecate :find_spec_for_file, :none, 2011, 10
-end
diff --git a/ruby_1_9_3/lib/rubygems/gem_runner.rb b/ruby_1_9_3/lib/rubygems/gem_runner.rb
deleted file mode 100644
index 6197036f81..0000000000
--- a/ruby_1_9_3/lib/rubygems/gem_runner.rb
+++ /dev/null
@@ -1,86 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-require "rubygems"
-require 'rubygems/command_manager'
-require 'rubygems/config_file'
-require 'rubygems/doc_manager'
-
-##
-# Load additional plugins from $LOAD_PATH
-
-Gem.load_env_plugins rescue nil
-
-##
-# Run an instance of the gem program.
-#
-# Gem::GemRunner is only intended for internal use by RubyGems itself. It
-# does not form any public API and may change at any time for any reason.
-#
-# If you would like to duplicate functionality of `gem` commands, use the
-# classes they call directly.
-
-class Gem::GemRunner
-
- def initialize(options={})
- # TODO: nuke these options
- @command_manager_class = options[:command_manager] || Gem::CommandManager
- @config_file_class = options[:config_file] || Gem::ConfigFile
- @doc_manager_class = options[:doc_manager] || Gem::DocManager
- end
-
- ##
- # Run the gem command with the following arguments.
-
- def run(args)
- start_time = Time.now
-
- if args.include?('--')
- # We need to preserve the original ARGV to use for passing gem options
- # to source gems. If there is a -- in the line, strip all options after
- # it...its for the source building process.
- build_args = args[args.index("--") + 1...args.length]
- args = args[0...args.index("--")]
- end
-
- Gem::Command.build_args = build_args if build_args
-
- do_configuration args
- cmd = @command_manager_class.instance
-
- cmd.command_names.each do |command_name|
- config_args = Gem.configuration[command_name]
- config_args = case config_args
- when String
- config_args.split ' '
- else
- Array(config_args)
- end
- Gem::Command.add_specific_extra_args command_name, config_args
- end
-
- cmd.run Gem.configuration.args
- end_time = Time.now
-
- if Gem.configuration.benchmark then
- printf "\nExecution time: %0.2f seconds.\n", end_time - start_time
- puts "Press Enter to finish"
- STDIN.gets
- end
- end
-
- private
-
- def do_configuration(args)
- Gem.configuration = @config_file_class.new(args)
- Gem.use_paths Gem.configuration[:gemhome], Gem.configuration[:gempath]
- Gem::Command.extra_args = Gem.configuration[:gem]
- @doc_manager_class.configured_args = Gem.configuration[:rdoc]
- end
-
-end
-
-Gem.load_plugins
diff --git a/ruby_1_9_3/lib/rubygems/gemcutter_utilities.rb b/ruby_1_9_3/lib/rubygems/gemcutter_utilities.rb
deleted file mode 100644
index c0e7ee99e9..0000000000
--- a/ruby_1_9_3/lib/rubygems/gemcutter_utilities.rb
+++ /dev/null
@@ -1,82 +0,0 @@
-require 'rubygems/remote_fetcher'
-
-module Gem::GemcutterUtilities
- OptionParser.accept Symbol do |value|
- value.to_sym
- end
-
- ##
- # Add the --key option
-
- def add_key_option
- add_option('-k', '--key KEYNAME', Symbol,
- 'Use the given API key',
- 'from ~/.gem/credentials') do |value,options|
- options[:key] = value
- end
- end
-
- def api_key
- if options[:key] then
- verify_api_key options[:key]
- else
- Gem.configuration.rubygems_api_key
- end
- end
-
- def sign_in
- return if Gem.configuration.rubygems_api_key
-
- say "Enter your RubyGems.org credentials."
- say "Don't have an account yet? Create one at http://rubygems.org/sign_up"
-
- email = ask " Email: "
- password = ask_for_password "Password: "
- say "\n"
-
- response = rubygems_api_request :get, "api/v1/api_key" do |request|
- request.basic_auth email, password
- end
-
- with_response response do |resp|
- say "Signed in."
- Gem.configuration.rubygems_api_key = resp.body
- end
- end
-
- def rubygems_api_request(method, path, host = Gem.host, &block)
- require 'net/http'
- host = ENV['RUBYGEMS_HOST'] if ENV['RUBYGEMS_HOST']
- uri = URI.parse "#{host}/#{path}"
-
- say "Pushing gem to #{host}..."
-
- request_method = Net::HTTP.const_get method.to_s.capitalize
-
- Gem::RemoteFetcher.fetcher.request(uri, request_method, &block)
- end
-
- def with_response(resp)
- case resp
- when Net::HTTPSuccess then
- if block_given? then
- yield resp
- else
- say resp.body
- end
- else
- say resp.body
- terminate_interaction 1
- end
- end
-
- def verify_api_key(key)
- if Gem.configuration.api_keys.key? key then
- Gem.configuration.api_keys[key]
- else
- alert_error "No such API key. You can add it with gem keys --add #{key}"
- terminate_interaction 1
- end
- end
-
-end
diff --git a/ruby_1_9_3/lib/rubygems/indexer.rb b/ruby_1_9_3/lib/rubygems/indexer.rb
deleted file mode 100644
index e87e5a3632..0000000000
--- a/ruby_1_9_3/lib/rubygems/indexer.rb
+++ /dev/null
@@ -1,644 +0,0 @@
-require 'rubygems'
-require 'rubygems/format'
-require 'time'
-
-begin
- gem 'builder'
- require 'builder/xchar'
-rescue LoadError
-end
-
-##
-# Top level class for building the gem repository index.
-
-class Gem::Indexer
-
- include Gem::UserInteraction
-
- ##
- # Build indexes for RubyGems older than 1.2.0 when true
-
- attr_accessor :build_legacy
-
- ##
- # Build indexes for RubyGems 1.2.0 and newer when true
-
- attr_accessor :build_modern
-
- ##
- # Index install location
-
- attr_reader :dest_directory
-
- ##
- # Specs index install location
-
- attr_reader :dest_specs_index
-
- ##
- # Latest specs index install location
-
- attr_reader :dest_latest_specs_index
-
- ##
- # Prerelease specs index install location
-
- attr_reader :dest_prerelease_specs_index
-
- ##
- # Index build directory
-
- attr_reader :directory
-
- ##
- # Create an indexer that will index the gems in +directory+.
-
- def initialize(directory, options = {})
- require 'fileutils'
- require 'tmpdir'
- require 'zlib'
-
- unless defined?(Builder::XChar) then
- raise "Gem::Indexer requires that the XML Builder library be installed:" \
- "\n\tgem install builder"
- end
-
- options = { :build_legacy => true, :build_modern => true }.merge options
-
- @build_legacy = options[:build_legacy]
- @build_modern = options[:build_modern]
-
- @rss_title = options[:rss_title]
- @rss_host = options[:rss_host]
- @rss_gems_host = options[:rss_gems_host]
-
- @dest_directory = directory
- @directory = File.join(Dir.tmpdir, "gem_generate_index_#{$$}")
-
- marshal_name = "Marshal.#{Gem.marshal_version}"
-
- @master_index = File.join @directory, 'yaml'
- @marshal_index = File.join @directory, marshal_name
-
- @quick_dir = File.join @directory, 'quick'
- @quick_marshal_dir = File.join @quick_dir, marshal_name
- @quick_marshal_dir_base = File.join "quick", marshal_name # FIX: UGH
-
- @quick_index = File.join @quick_dir, 'index'
- @latest_index = File.join @quick_dir, 'latest_index'
-
- @specs_index = File.join @directory, "specs.#{Gem.marshal_version}"
- @latest_specs_index =
- File.join(@directory, "latest_specs.#{Gem.marshal_version}")
- @prerelease_specs_index =
- File.join(@directory, "prerelease_specs.#{Gem.marshal_version}")
- @dest_specs_index =
- File.join(@dest_directory, "specs.#{Gem.marshal_version}")
- @dest_latest_specs_index =
- File.join(@dest_directory, "latest_specs.#{Gem.marshal_version}")
- @dest_prerelease_specs_index =
- File.join(@dest_directory, "prerelease_specs.#{Gem.marshal_version}")
-
- @rss_index = File.join @directory, 'index.rss'
-
- @files = []
- end
-
- ##
- # Abbreviate the spec for downloading. Abbreviated specs are only used for
- # searching, downloading and related activities and do not need deployment
- # specific information (e.g. list of files). So we abbreviate the spec,
- # making it much smaller for quicker downloads.
-
- def abbreviate(spec)
- spec.files = []
- spec.test_files = []
- spec.rdoc_options = []
- spec.extra_rdoc_files = []
- spec.cert_chain = []
- spec
- end
-
- ##
- # Build various indicies
-
- def build_indicies
- # Marshal gemspecs are used by both modern and legacy RubyGems
-
- Gem::Specification.dirs = []
- Gem::Specification.add_specs(*map_gems_to_specs(gem_file_list))
-
- build_marshal_gemspecs
- build_legacy_indicies if @build_legacy
- build_modern_indicies if @build_modern
- build_rss
-
- compress_indicies
- end
-
- ##
- # Builds indicies for RubyGems older than 1.2.x
-
- def build_legacy_indicies
- index = collect_specs
-
- say "Generating Marshal master index"
-
- Gem.time 'Generated Marshal master index' do
- open @marshal_index, 'wb' do |io|
- io.write index.dump
- end
- end
-
- @files << @marshal_index
- @files << "#{@marshal_index}.Z"
- end
-
- ##
- # Builds Marshal quick index gemspecs.
-
- def build_marshal_gemspecs
- count = Gem::Specification.count
- progress = ui.progress_reporter count,
- "Generating Marshal quick index gemspecs for #{count} gems",
- "Complete"
-
- files = []
-
- Gem.time 'Generated Marshal quick index gemspecs' do
- Gem::Specification.each do |spec|
- spec_file_name = "#{spec.original_name}.gemspec.rz"
- marshal_name = File.join @quick_marshal_dir, spec_file_name
-
- marshal_zipped = Gem.deflate Marshal.dump(spec)
- open marshal_name, 'wb' do |io| io.write marshal_zipped end
-
- files << marshal_name
-
- progress.updated spec.original_name
- end
-
- progress.done
- end
-
- @files << @quick_marshal_dir
-
- files
- end
-
- ##
- # Build a single index for RubyGems 1.2 and newer
-
- def build_modern_index(index, file, name)
- say "Generating #{name} index"
-
- Gem.time "Generated #{name} index" do
- open(file, 'wb') do |io|
- specs = index.map do |*spec|
- # We have to splat here because latest_specs is an array, while the
- # others are hashes.
- spec = spec.flatten.last
- platform = spec.original_platform
-
- # win32-api-1.0.4-x86-mswin32-60
- unless String === platform then
- alert_warning "Skipping invalid platform in gem: #{spec.full_name}"
- next
- end
-
- platform = Gem::Platform::RUBY if platform.nil? or platform.empty?
- [spec.name, spec.version, platform]
- end
-
- specs = compact_specs(specs)
- Marshal.dump(specs, io)
- end
- end
- end
-
- ##
- # Builds indicies for RubyGems 1.2 and newer. Handles full, latest, prerelease
-
- def build_modern_indicies
- prerelease, released = Gem::Specification.partition { |s|
- s.version.prerelease?
- }
- latest_specs = Gem::Specification.latest_specs
-
- build_modern_index(released.sort, @specs_index, 'specs')
- build_modern_index(latest_specs.sort, @latest_specs_index, 'latest specs')
- build_modern_index(prerelease.sort, @prerelease_specs_index,
- 'prerelease specs')
-
- @files += [@specs_index,
- "#{@specs_index}.gz",
- @latest_specs_index,
- "#{@latest_specs_index}.gz",
- @prerelease_specs_index,
- "#{@prerelease_specs_index}.gz"]
- end
-
- ##
- # Builds an RSS feed for past two days gem releases according to the gem's
- # date.
-
- def build_rss
- if @rss_host.nil? or @rss_gems_host.nil? then
- if Gem.configuration.really_verbose then
- alert_warning "no --rss-host or --rss-gems-host, RSS generation disabled"
- end
- return
- end
-
- require 'cgi'
- require 'rubygems/text'
-
- extend Gem::Text
-
- Gem.time 'Generated rss' do
- open @rss_index, 'wb' do |io|
- rss_host = CGI.escapeHTML @rss_host
- rss_title = CGI.escapeHTML(@rss_title || 'gems')
-
- io.puts <<-HEADER
-<?xml version="1.0"?>
-<rss version="2.0">
- <channel>
- <title>#{rss_title}</title>
- <link>http://#{rss_host}</link>
- <description>Recently released gems from http://#{rss_host}</description>
- <generator>RubyGems v#{Gem::VERSION}</generator>
- <docs>http://cyber.law.harvard.edu/rss/rss.html</docs>
- HEADER
-
- today = Gem::Specification::TODAY
- yesterday = today - 86400
-
- index = Gem::Specification.select do |spec|
- spec_date = spec.date
- # TODO: remove this and make YAML based specs properly normalized
- spec_date = Time.parse(spec_date.to_s) if Date === spec_date
-
- spec_date >= yesterday && spec_date <= today
- end
-
- index.sort_by { |spec| [-spec.date.to_i, spec] }.each do |spec|
- file_name = File.basename spec.cache_file
- gem_path = CGI.escapeHTML "http://#{@rss_gems_host}/gems/#{file_name}"
- size = File.stat(spec.loaded_from).size # rescue next
-
- description = spec.description || spec.summary || ''
- authors = Array spec.authors
- emails = Array spec.email
- authors = emails.zip(authors).map do |email, author|
- email += " (#{author})" if author and not author.empty?
- end.join ', '
-
- description = description.split(/\n\n+/).map do |chunk|
- format_text chunk, 78
- end
-
- description = description.join "\n\n"
-
- item = ''
-
- item << <<-ITEM
- <item>
- <title>#{CGI.escapeHTML spec.full_name}</title>
- <description>
-&lt;pre&gt;#{CGI.escapeHTML description.chomp}&lt;/pre&gt;
- </description>
- <author>#{CGI.escapeHTML authors}</author>
- <guid>#{CGI.escapeHTML spec.full_name}</guid>
- <enclosure url=\"#{gem_path}\"
- length=\"#{size}\" type=\"application/octet-stream\" />
- <pubDate>#{spec.date.rfc2822}</pubDate>
- ITEM
-
- item << <<-ITEM if spec.homepage
- <link>#{CGI.escapeHTML spec.homepage}</link>
- ITEM
-
- item << <<-ITEM
- </item>
- ITEM
-
- io.puts item
- end
-
- io.puts <<-FOOTER
- </channel>
-</rss>
- FOOTER
- end
- end
-
- @files << @rss_index
- end
-
- def map_gems_to_specs gems
- gems.map { |gemfile|
- if File.size(gemfile) == 0 then
- alert_warning "Skipping zero-length gem: #{gemfile}"
- next
- end
-
- begin
- spec = Gem::Format.from_file_by_path(gemfile).spec
- spec.loaded_from = gemfile
-
- # HACK: fuck this shit - borks all tests that use pl1
- # if File.basename(gemfile, ".gem") != spec.original_name then
- # exp = spec.full_name
- # exp << " (#{spec.original_name})" if
- # spec.original_name != spec.full_name
- # msg = "Skipping misnamed gem: #{gemfile} should be named #{exp}"
- # alert_warning msg
- # next
- # end
-
- abbreviate spec
- sanitize spec
-
- spec
- rescue SignalException => e
- alert_error "Received signal, exiting"
- raise
- rescue Exception => e
- msg = ["Unable to process #{gemfile}",
- "#{e.message} (#{e.class})",
- "\t#{e.backtrace.join "\n\t"}"].join("\n")
- alert_error msg
- end
- }.compact
- end
-
- ##
- # Collect specifications from .gem files from the gem directory.
-
- def collect_specs(gems = gem_file_list)
- Gem::Deprecate.skip_during do
- index = Gem::SourceIndex.new
-
- map_gems_to_specs(gems).each do |spec|
- index.add_spec spec, spec.original_name
- end
-
- index
- end
- end
-
- ##
- # Compresses indicies on disk
- #--
- # All future files should be compressed using gzip, not deflate
-
- def compress_indicies
- say "Compressing indicies"
-
- Gem.time 'Compressed indicies' do
- if @build_legacy then
- compress @marshal_index, 'Z'
- paranoid @marshal_index, 'Z'
- end
-
- if @build_modern then
- gzip @specs_index
- gzip @latest_specs_index
- gzip @prerelease_specs_index
- end
- end
- end
-
- ##
- # Compacts Marshal output for the specs index data source by using identical
- # objects as much as possible.
-
- def compact_specs(specs)
- names = {}
- versions = {}
- platforms = {}
-
- specs.map do |(name, version, platform)|
- names[name] = name unless names.include? name
- versions[version] = version unless versions.include? version
- platforms[platform] = platform unless platforms.include? platform
-
- [names[name], versions[version], platforms[platform]]
- end
- end
-
- ##
- # Compress +filename+ with +extension+.
-
- def compress(filename, extension)
- data = Gem.read_binary filename
-
- zipped = Gem.deflate data
-
- open "#{filename}.#{extension}", 'wb' do |io|
- io.write zipped
- end
- end
-
- ##
- # List of gem file names to index.
-
- def gem_file_list
- Dir[File.join(@dest_directory, "gems", '*.gem')]
- end
-
- ##
- # Builds and installs indicies.
-
- def generate_index
- make_temp_directories
- build_indicies
- install_indicies
- rescue SignalException
- ensure
- FileUtils.rm_rf @directory
- end
-
- ##
- # Zlib::GzipWriter wrapper that gzips +filename+ on disk.
-
- def gzip(filename)
- Zlib::GzipWriter.open "#{filename}.gz" do |io|
- io.write Gem.read_binary(filename)
- end
- end
-
- ##
- # Install generated indicies into the destination directory.
-
- def install_indicies
- verbose = Gem.configuration.really_verbose
-
- say "Moving index into production dir #{@dest_directory}" if verbose
-
- files = @files
- files.delete @quick_marshal_dir if files.include? @quick_dir
-
- if files.include? @quick_marshal_dir and not files.include? @quick_dir then
- files.delete @quick_marshal_dir
-
- dst_name = File.join(@dest_directory, @quick_marshal_dir_base)
-
- FileUtils.mkdir_p File.dirname(dst_name), :verbose => verbose
- FileUtils.rm_rf dst_name, :verbose => verbose
- FileUtils.mv(@quick_marshal_dir, dst_name,
- :verbose => verbose, :force => true)
- end
-
- files = files.map do |path|
- path.sub(/^#{Regexp.escape @directory}\/?/, '') # HACK?
- end
-
- files.each do |file|
- src_name = File.join @directory, file
- dst_name = File.join @dest_directory, file
-
- FileUtils.rm_rf dst_name, :verbose => verbose
- FileUtils.mv(src_name, @dest_directory,
- :verbose => verbose, :force => true)
- end
- end
-
- ##
- # Make directories for index generation
-
- def make_temp_directories
- FileUtils.rm_rf @directory
- FileUtils.mkdir_p @directory, :mode => 0700
- FileUtils.mkdir_p @quick_marshal_dir
- end
-
- ##
- # Ensure +path+ and path with +extension+ are identical.
-
- def paranoid(path, extension)
- data = Gem.read_binary path
- compressed_data = Gem.read_binary "#{path}.#{extension}"
-
- unless data == Gem.inflate(compressed_data) then
- raise "Compressed file #{compressed_path} does not match uncompressed file #{path}"
- end
- end
-
- ##
- # Sanitize the descriptive fields in the spec. Sometimes non-ASCII
- # characters will garble the site index. Non-ASCII characters will
- # be replaced by their XML entity equivalent.
-
- def sanitize(spec)
- spec.summary = sanitize_string(spec.summary)
- spec.description = sanitize_string(spec.description)
- spec.post_install_message = sanitize_string(spec.post_install_message)
- spec.authors = spec.authors.collect { |a| sanitize_string(a) }
-
- spec
- end
-
- ##
- # Sanitize a single string.
-
- def sanitize_string(string)
- return string unless string
-
- # HACK the #to_s is in here because RSpec has an Array of Arrays of
- # Strings for authors. Need a way to disallow bad values on gemspec
- # generation. (Probably won't happen.)
- string = string.to_s
-
- begin
- Builder::XChar.encode string
- rescue NameError, NoMethodError
- string.to_xs
- end
- end
-
- ##
- # Perform an in-place update of the repository from newly added gems. Only
- # works for modern indicies, and sets #build_legacy to false when run.
-
- def update_index
- @build_legacy = false
-
- make_temp_directories
-
- specs_mtime = File.stat(@dest_specs_index).mtime
- newest_mtime = Time.at 0
-
- updated_gems = gem_file_list.select do |gem|
- gem_mtime = File.stat(gem).mtime
- newest_mtime = gem_mtime if gem_mtime > newest_mtime
- gem_mtime >= specs_mtime
- end
-
- if updated_gems.empty? then
- say 'No new gems'
- terminate_interaction 0
- end
-
- specs = map_gems_to_specs updated_gems
- prerelease, released = specs.partition { |s| s.version.prerelease? }
-
- files = build_marshal_gemspecs
-
- Gem.time 'Updated indexes' do
- update_specs_index released, @dest_specs_index, @specs_index
- update_specs_index released, @dest_latest_specs_index, @latest_specs_index
- update_specs_index(prerelease,
- @dest_prerelease_specs_index,
- @prerelease_specs_index)
- end
-
- compress_indicies
-
- verbose = Gem.configuration.really_verbose
-
- say "Updating production dir #{@dest_directory}" if verbose
-
- files << @specs_index
- files << "#{@specs_index}.gz"
- files << @latest_specs_index
- files << "#{@latest_specs_index}.gz"
- files << @prerelease_specs_index
- files << "#{@prerelease_specs_index}.gz"
-
- files = files.map do |path|
- path.sub(/^#{Regexp.escape @directory}\/?/, '') # HACK?
- end
-
- files.each do |file|
- src_name = File.join @directory, file
- dst_name = File.join @dest_directory, file # REFACTOR: duped above
-
- FileUtils.mv src_name, dst_name, :verbose => verbose,
- :force => true
-
- File.utime newest_mtime, newest_mtime, dst_name
- end
- end
-
- ##
- # Combines specs in +index+ and +source+ then writes out a new copy to
- # +dest+. For a latest index, does not ensure the new file is minimal.
-
- def update_specs_index(index, source, dest)
- specs_index = Marshal.load Gem.read_binary(source)
-
- index.each do |spec|
- platform = spec.original_platform
- platform = Gem::Platform::RUBY if platform.nil? or platform.empty?
- specs_index << [spec.name, spec.version, platform]
- end
-
- specs_index = compact_specs specs_index.uniq.sort
-
- open dest, 'wb' do |io|
- Marshal.dump specs_index, io
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rubygems/install_update_options.rb b/ruby_1_9_3/lib/rubygems/install_update_options.rb
deleted file mode 100644
index 3ee6432b4c..0000000000
--- a/ruby_1_9_3/lib/rubygems/install_update_options.rb
+++ /dev/null
@@ -1,128 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-require 'rubygems'
-
-# forward-declare
-
-module Gem::Security # :nodoc:
- class Policy # :nodoc:
- end
-end
-
-##
-# Mixin methods for install and update options for Gem::Commands
-
-module Gem::InstallUpdateOptions
-
- ##
- # Add the install/update options to the option parser.
-
- def add_install_update_options
- OptionParser.accept Gem::Security::Policy do |value|
- require 'rubygems/security'
-
- value = Gem::Security::Policies[value]
- valid = Gem::Security::Policies.keys.sort
- message = "#{value} (#{valid.join ', '} are valid)"
- raise OptionParser::InvalidArgument, message if value.nil?
- value
- end
-
- add_option(:"Install/Update", '-i', '--install-dir DIR',
- 'Gem repository directory to get installed',
- 'gems') do |value, options|
- options[:install_dir] = File.expand_path(value)
- end
-
- add_option(:"Install/Update", '-n', '--bindir DIR',
- 'Directory where binary files are',
- 'located') do |value, options|
- options[:bin_dir] = File.expand_path(value)
- end
-
- add_option(:"Install/Update", '-d', '--[no-]rdoc',
- 'Generate RDoc documentation for the gem on',
- 'install') do |value, options|
- options[:generate_rdoc] = value
- end
-
- add_option(:"Install/Update", '--[no-]ri',
- 'Generate RI documentation for the gem on',
- 'install') do |value, options|
- options[:generate_ri] = value
- end
-
- add_option(:"Install/Update", '-E', '--[no-]env-shebang',
- "Rewrite the shebang line on installed",
- "scripts to use /usr/bin/env") do |value, options|
- options[:env_shebang] = value
- end
-
- add_option(:"Install/Update", '-f', '--[no-]force',
- 'Force gem to install, bypassing dependency',
- 'checks') do |value, options|
- options[:force] = value
- end
-
- add_option(:"Install/Update", '-w', '--[no-]wrappers',
- 'Use bin wrappers for executables',
- 'Not available on dosish platforms') do |value, options|
- options[:wrappers] = value
- end
-
- add_option(:"Install/Update", '-P', '--trust-policy POLICY',
- Gem::Security::Policy,
- 'Specify gem trust policy') do |value, options|
- options[:security_policy] = value
- end
-
- add_option(:"Install/Update", '--ignore-dependencies',
- 'Do not install any required dependent gems') do |value, options|
- options[:ignore_dependencies] = value
- end
-
- add_option(:"Install/Update", '-y', '--include-dependencies',
- 'Unconditionally install the required',
- 'dependent gems') do |value, options|
- options[:include_dependencies] = value
- end
-
- add_option(:"Install/Update", '--[no-]format-executable',
- 'Make installed executable names match ruby.',
- 'If ruby is ruby18, foo_exec will be',
- 'foo_exec18') do |value, options|
- options[:format_executable] = value
- end
-
- add_option(:"Install/Update", '--[no-]user-install',
- 'Install in user\'s home directory instead',
- 'of GEM_HOME.') do |value, options|
- options[:user_install] = value
- end
-
- add_option(:"Install/Update", "--development",
- "Install any additional development",
- "dependencies") do |value, options|
- options[:development] = true
- end
-
- add_option(:"Install/Update", "--conservative",
- "Don't attempt to upgrade gems already",
- "meeting version requirement") do |value, options|
- options[:conservative] = true
- end
- end
-
- ##
- # Default options for the gem install command.
-
- def install_update_defaults_str
- '--rdoc --no-force --wrappers'
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/installer.rb b/ruby_1_9_3/lib/rubygems/installer.rb
deleted file mode 100644
index 514316f099..0000000000
--- a/ruby_1_9_3/lib/rubygems/installer.rb
+++ /dev/null
@@ -1,626 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-require 'rubygems/format'
-require 'rubygems/exceptions'
-require 'rubygems/ext'
-require 'rubygems/require_paths_builder'
-require 'rubygems/user_interaction'
-
-##
-# The installer class processes RubyGem .gem files and installs the files
-# contained in the .gem into the Gem.path.
-#
-# Gem::Installer does the work of putting files in all the right places on the
-# filesystem including unpacking the gem into its gem dir, installing the
-# gemspec in the specifications dir, storing the cached gem in the cache dir,
-# and installing either wrappers or symlinks for executables.
-#
-# The installer invokes pre and post install hooks. Hooks can be added either
-# through a rubygems_plugin.rb file in an installed gem or via a
-# rubygems/defaults/#{RUBY_ENGINE}.rb or rubygems/defaults/operating_system.rb
-# file. See Gem.pre_install and Gem.post_install for details.
-
-class Gem::Installer
-
- ##
- # Paths where env(1) might live. Some systems are broken and have it in
- # /bin
-
- ENV_PATHS = %w[/usr/bin/env /bin/env]
-
- ##
- # Raised when there is an error while building extensions.
- #
- class ExtensionBuildError < Gem::InstallError; end
-
- include Gem::UserInteraction
-
- include Gem::RequirePathsBuilder if Gem::QUICKLOADER_SUCKAGE
-
- attr_reader :gem
-
- ##
- # The directory a gem's executables will be installed into
-
- attr_reader :bin_dir
-
- ##
- # The gem repository the gem will be installed into
-
- attr_reader :gem_home
-
- ##
- # The options passed when the Gem::Installer was instantiated.
-
- attr_reader :options
-
- @path_warning = false
-
- class << self
-
- ##
- # True if we've warned about PATH not including Gem.bindir
-
- attr_accessor :path_warning
-
- attr_writer :exec_format
-
- # Defaults to use Ruby's program prefix and suffix.
- def exec_format
- @exec_format ||= Gem.default_exec_format
- end
-
- end
-
- ##
- # Constructs an Installer instance that will install the gem located at
- # +gem+. +options+ is a Hash with the following keys:
- #
- # :env_shebang:: Use /usr/bin/env in bin wrappers.
- # :force:: Overrides all version checks and security policy checks, except
- # for a signed-gems-only policy.
- # :ignore_dependencies:: Don't raise if a dependency is missing.
- # :install_dir:: The directory to install the gem into.
- # :format_executable:: Format the executable the same as the ruby executable.
- # If your ruby is ruby18, foo_exec will be installed as
- # foo_exec18.
- # :security_policy:: Use the specified security policy. See Gem::Security
- # :wrappers:: Install wrappers if true, symlinks if false.
-
- def initialize(gem, options={})
- require 'fileutils'
-
- @gem = gem
- @options = options
- process_options
-
- if options[:user_install] and not options[:unpack] then
- @gem_home = Gem.user_dir
- check_that_user_bin_dir_is_in_path
- end
- end
-
- ##
- # Lazy accessor for the spec's gem directory.
-
- def gem_dir
- @gem_dir ||= spec.gem_dir.dup.untaint
- end
-
- ##
- # Lazy accessor for the installer's Gem::Format instance.
-
- def format
- begin
- @format ||= Gem::Format.from_file_by_path gem, @security_policy
- rescue Gem::Package::FormatError
- raise Gem::InstallError, "invalid gem format for #{gem}"
- end
- end
-
- ##
- # Lazy accessor for the installer's spec.
-
- def spec
- @spec ||= format.spec
- end
-
- ##
- # Installs the gem and returns a loaded Gem::Specification for the installed
- # gem.
- #
- # The gem will be installed with the following structure:
- #
- # @gem_home/
- # cache/<gem-version>.gem #=> a cached copy of the installed gem
- # gems/<gem-version>/... #=> extracted files
- # specifications/<gem-version>.gemspec #=> the Gem::Specification
-
- def install
- current_home = Gem.dir
- current_path = Gem.paths.path
-
- verify_gem_home(options[:unpack])
- Gem.use_paths gem_home, current_path # HACK: shouldn't need Gem.paths.path
-
- # If we're forcing the install then disable security unless the security
- # policy says that we only install signed gems.
- @security_policy = nil if @force and @security_policy and
- not @security_policy.only_signed
-
- unless @force
- ensure_required_ruby_version_met
- ensure_required_rubygems_version_met
- ensure_dependencies_met unless @ignore_dependencies
- end
-
- Gem.pre_install_hooks.each do |hook|
- result = hook.call self
-
- if result == false then
- location = " at #{$1}" if hook.inspect =~ /@(.*:\d+)/
-
- message = "pre-install hook#{location} failed for #{spec.full_name}"
- raise Gem::InstallError, message
- end
- end
-
- Gem.ensure_gem_subdirectories gem_home
-
- # Completely remove any previous gem files
- FileUtils.rm_rf(gem_dir) if File.exist? gem_dir
-
- FileUtils.mkdir_p gem_dir
-
- extract_files
- build_extensions
-
- Gem.post_build_hooks.each do |hook|
- result = hook.call self
-
- if result == false then
- FileUtils.rm_rf gem_dir
-
- location = " at #{$1}" if hook.inspect =~ /@(.*:\d+)/
-
- message = "post-build hook#{location} failed for #{spec.full_name}"
- raise Gem::InstallError, message
- end
- end
-
- generate_bin
- write_spec
-
- write_require_paths_file_if_needed if Gem::QUICKLOADER_SUCKAGE
-
- cache_file = spec.cache_file
- FileUtils.cp gem, cache_file unless File.exist? cache_file
-
- say spec.post_install_message unless spec.post_install_message.nil?
-
- spec.loaded_from = spec.spec_file
-
- Gem::Specification.add_spec spec unless Gem::Specification.include? spec
-
- Gem.post_install_hooks.each do |hook|
- hook.call self
- end
-
- return spec
- rescue Zlib::GzipFile::Error
- raise Gem::InstallError, "gzip error installing #{gem}"
- ensure
- # conditional since we might be here because we're erroring out early.
- if current_path
- Gem.use_paths current_home, current_path
- end
- end
-
- ##
- # Ensure that the dependency is satisfied by the current installation of
- # gem. If it is not an exception is raised.
- #
- # spec :: Gem::Specification
- # dependency :: Gem::Dependency
-
- def ensure_dependency(spec, dependency)
- unless installation_satisfies_dependency? dependency then
- raise Gem::InstallError, "#{spec.name} requires #{dependency}"
- end
- true
- end
-
- ##
- # True if the gems in the source_index satisfy +dependency+.
-
- def installation_satisfies_dependency?(dependency)
- not dependency.matching_specs.empty?
- end
-
- ##
- # Unpacks the gem into the given directory.
-
- def unpack(directory)
- @gem_dir = directory
- @format = Gem::Format.from_file_by_path gem, @security_policy
- extract_files
- end
-
- ##
- # Writes the .gemspec specification (in Ruby) to the gem home's
- # specifications directory.
-
- def write_spec
- file_name = spec.spec_file.untaint
-
- File.open(file_name, "w") do |file|
- file.puts spec.to_ruby_for_cache
- end
- end
-
- ##
- # Creates windows .bat files for easy running of commands
-
- def generate_windows_script(filename, bindir)
- if Gem.win_platform? then
- script_name = filename + ".bat"
- script_path = File.join bindir, File.basename(script_name)
- File.open script_path, 'w' do |file|
- file.puts windows_stub_script(bindir, filename)
- end
-
- say script_path if Gem.configuration.really_verbose
- end
- end
-
- def generate_bin
- return if spec.executables.nil? or spec.executables.empty?
-
- # If the user has asked for the gem to be installed in a directory that is
- # the system gem directory, then use the system bin directory, else create
- # (or use) a new bin dir under the gem_home.
- bindir = @bin_dir || Gem.bindir(gem_home)
-
- Dir.mkdir bindir unless File.exist? bindir
- raise Gem::FilePermissionError.new(bindir) unless File.writable? bindir
-
- spec.executables.each do |filename|
- filename.untaint
- bin_path = File.expand_path File.join(gem_dir, spec.bindir, filename)
-
- unless File.exist? bin_path
- warn "Hey?!?! Where did #{bin_path} go??"
- next
- end
-
- mode = File.stat(bin_path).mode | 0111
- FileUtils.chmod mode, bin_path
-
- if @wrappers then
- generate_bin_script filename, bindir
- else
- generate_bin_symlink filename, bindir
- end
- end
- end
-
- ##
- # Creates the scripts to run the applications in the gem.
- #--
- # The Windows script is generated in addition to the regular one due to a
- # bug or misfeature in the Windows shell's pipe. See
- # http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/193379
-
- def generate_bin_script(filename, bindir)
- bin_script_path = File.join bindir, formatted_program_filename(filename)
-
- FileUtils.rm_f bin_script_path # prior install may have been --no-wrappers
-
- File.open bin_script_path, 'wb', 0755 do |file|
- file.print app_script_text(filename)
- end
-
- say bin_script_path if Gem.configuration.really_verbose
-
- generate_windows_script filename, bindir
- end
-
- ##
- # Creates the symlinks to run the applications in the gem. Moves
- # the symlink if the gem being installed has a newer version.
-
- def generate_bin_symlink(filename, bindir)
- if Gem.win_platform? then
- alert_warning "Unable to use symlinks on Windows, installing wrapper"
- generate_bin_script filename, bindir
- return
- end
-
- src = File.join gem_dir, spec.bindir, filename
- dst = File.join bindir, formatted_program_filename(filename)
-
- if File.exist? dst then
- if File.symlink? dst then
- link = File.readlink(dst).split File::SEPARATOR
- cur_version = Gem::Version.create(link[-3].sub(/^.*-/, ''))
- return if spec.version < cur_version
- end
- File.unlink dst
- end
-
- FileUtils.symlink src, dst, :verbose => Gem.configuration.really_verbose
- end
-
- ##
- # Generates a #! line for +bin_file_name+'s wrapper copying arguments if
- # necessary.
-
- def shebang(bin_file_name)
- ruby_name = Gem::ConfigMap[:ruby_install_name] if @env_shebang
- path = spec.bin_file bin_file_name
- first_line = File.open(path, "rb") {|file| file.gets}
-
- if /\A#!/ =~ first_line then
- # Preserve extra words on shebang line, like "-w". Thanks RPA.
- shebang = first_line.sub(/\A\#!.*?ruby\S*((\s+\S+)+)/, "#!#{Gem.ruby}")
- opts = $1
- shebang.strip! # Avoid nasty ^M issues.
- end
-
- if not ruby_name then
- "#!#{Gem.ruby}#{opts}"
- elsif opts then
- "#!/bin/sh\n'exec' #{ruby_name.dump} '-x' \"$0\" \"$@\"\n#{shebang}"
- else
- # Create a plain shebang line.
- @env_path ||= ENV_PATHS.find {|env_path| File.executable? env_path }
- "#!#{@env_path} #{ruby_name}"
- end
- end
-
- def ensure_required_ruby_version_met
- if rrv = spec.required_ruby_version then
- unless rrv.satisfied_by? Gem.ruby_version then
- raise Gem::InstallError, "#{spec.name} requires Ruby version #{rrv}."
- end
- end
- end
-
- def ensure_required_rubygems_version_met
- if rrgv = spec.required_rubygems_version then
- unless rrgv.satisfied_by? Gem::Version.new(Gem::VERSION) then
- raise Gem::InstallError,
- "#{spec.name} requires RubyGems version #{rrgv}. " +
- "Try 'gem update --system' to update RubyGems itself."
- end
- end
- end
-
- def ensure_dependencies_met
- deps = spec.runtime_dependencies
- deps |= spec.development_dependencies if @development
-
- deps.each do |dep_gem|
- ensure_dependency spec, dep_gem
- end
- end
-
- def process_options
- @options = {
- :bin_dir => nil,
- :env_shebang => false,
- :exec_format => false,
- :force => false,
- :install_dir => Gem.dir,
- }.merge options
-
- @env_shebang = options[:env_shebang]
- @force = options[:force]
- @gem_home = options[:install_dir]
- @ignore_dependencies = options[:ignore_dependencies]
- @format_executable = options[:format_executable]
- @security_policy = options[:security_policy]
- @wrappers = options[:wrappers]
- @bin_dir = options[:bin_dir]
- @development = options[:development]
-
- raise "NOTE: Installer option :source_index is dead" if
- options[:source_index]
- end
-
- def check_that_user_bin_dir_is_in_path
- user_bin_dir = @bin_dir || Gem.bindir(gem_home)
- user_bin_dir.gsub!(File::SEPARATOR, File::ALT_SEPARATOR) if File::ALT_SEPARATOR
- path = ENV['PATH']
- if Gem.win_platform? then
- path = path.downcase
- user_bin_dir = user_bin_dir.downcase
- end
-
- unless path.split(File::PATH_SEPARATOR).include? user_bin_dir then
- unless self.class.path_warning then
- alert_warning "You don't have #{user_bin_dir} in your PATH,\n\t gem executables will not run."
- self.class.path_warning = true
- end
- end
- end
-
- def verify_gem_home(unpack = false)
- FileUtils.mkdir_p gem_home
- raise Gem::FilePermissionError, gem_home unless
- unpack or File.writable?(gem_home)
- end
-
- ##
- # Return the text for an application file.
-
- def app_script_text(bin_file_name)
- return <<-TEXT
-#{shebang bin_file_name}
-#
-# This file was generated by RubyGems.
-#
-# The application '#{spec.name}' is installed as part of a gem, and
-# this file is here to facilitate running it.
-#
-
-require 'rubygems'
-
-version = "#{Gem::Requirement.default}"
-
-if ARGV.first
- str = ARGV.first
- str = str.dup.force_encoding("BINARY") if str.respond_to? :force_encoding
- if str =~ /\\A_(.*)_\\z/
- version = $1
- ARGV.shift
- end
-end
-
-gem '#{spec.name}', version
-load Gem.bin_path('#{spec.name}', '#{bin_file_name}', version)
-TEXT
- end
-
- ##
- # return the stub script text used to launch the true ruby script
-
- def windows_stub_script(bindir, bin_file_name)
- ruby = File.basename(Gem.ruby).chomp('"')
- return <<-TEXT
-@ECHO OFF
-IF NOT "%~f0" == "~f0" GOTO :WinNT
-@"#{ruby}" "#{File.join(bindir, bin_file_name)}" %1 %2 %3 %4 %5 %6 %7 %8 %9
-GOTO :EOF
-:WinNT
-@"#{ruby}" "%~dpn0" %*
-TEXT
-
- end
-
- ##
- # Builds extensions. Valid types of extensions are extconf.rb files,
- # configure scripts and rakefiles or mkrf_conf files.
-
- def build_extensions
- return if spec.extensions.empty?
- say "Building native extensions. This could take a while..."
- dest_path = File.join gem_dir, spec.require_paths.first
- ran_rake = false # only run rake once
-
- spec.extensions.each do |extension|
- break if ran_rake
- results = []
-
- builder = case extension
- when /extconf/ then
- Gem::Ext::ExtConfBuilder
- when /configure/ then
- Gem::Ext::ConfigureBuilder
- when /rakefile/i, /mkrf_conf/i then
- ran_rake = true
- Gem::Ext::RakeBuilder
- else
- results = ["No builder for extension '#{extension}'"]
- nil
- end
-
-
- extension_dir = begin
- File.join gem_dir, File.dirname(extension)
- rescue TypeError # extension == nil
- gem_dir
- end
-
-
- begin
- Dir.chdir extension_dir do
- results = builder.build(extension, gem_dir, dest_path, results)
-
- say results.join("\n") if Gem.configuration.really_verbose
- end
- rescue
- results = results.join "\n"
-
- gem_make_out = File.join extension_dir, 'gem_make.out'
-
- open gem_make_out, 'wb' do |io| io.puts results end
-
- message = <<-EOF
-ERROR: Failed to build gem native extension.
-
- #{results}
-
-Gem files will remain installed in #{gem_dir} for inspection.
-Results logged to #{gem_make_out}
-EOF
-
- raise ExtensionBuildError, message
- end
- end
- end
-
- ##
- # Reads the file index and extracts each file into the gem directory.
- #
- # Ensures that files can't be installed outside the gem directory.
-
- def extract_files
- raise ArgumentError, "format required to extract from" if @format.nil?
-
- @format.file_entries.each do |entry, file_data|
- path = entry['path'].untaint
-
- if path.start_with? "/" then # for extra sanity
- raise Gem::InstallError, "attempt to install file into #{entry['path']}"
- end
-
- path = File.expand_path File.join(gem_dir, path)
-
- unless path.start_with? gem_dir then
- msg = "attempt to install file into %p under %s" %
- [entry['path'], gem_dir]
- raise Gem::InstallError, msg
- end
-
- FileUtils.rm_rf(path) if File.exist? path
-
- dir = File.dirname path
- FileUtils.mkdir_p dir unless File.exist? dir
-
- File.open(path, "wb") do |out|
- out.write file_data
- end
-
- FileUtils.chmod entry['mode'], path
-
- say path if Gem.configuration.really_verbose
- end
- end
-
- ##
- # Prefix and suffix the program filename the same as ruby.
-
- def formatted_program_filename(filename)
- if @format_executable then
- self.class.exec_format % File.basename(filename)
- else
- filename
- end
- end
-
- ##
- #
- # Return the target directory where the gem is to be installed. This
- # directory is not guaranteed to be populated.
- #
-
- def dir
- gem_dir.to_s
- end
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/installer_test_case.rb b/ruby_1_9_3/lib/rubygems/installer_test_case.rb
deleted file mode 100644
index 96a5156995..0000000000
--- a/ruby_1_9_3/lib/rubygems/installer_test_case.rb
+++ /dev/null
@@ -1,144 +0,0 @@
-require 'rubygems/test_case'
-require 'rubygems/installer'
-
-class Gem::Installer
-
- ##
- # Available through requiring rubygems/installer_test_case
-
- attr_writer :gem_dir
-
- ##
- # Available through requiring rubygems/installer_test_case
-
- attr_writer :format
-
- ##
- # Available through requiring rubygems/installer_test_case
-
- attr_writer :gem_home
-
- ##
- # Available through requiring rubygems/installer_test_case
-
- attr_writer :env_shebang
-
- ##
- # Available through requiring rubygems/installer_test_case
-
- attr_writer :ignore_dependencies
-
- ##
- # Available through requiring rubygems/installer_test_case
-
- attr_writer :format_executable
-
- ##
- # Available through requiring rubygems/installer_test_case
-
- attr_writer :security_policy
-
- ##
- # Available through requiring rubygems/installer_test_case
-
- attr_writer :spec
-
- ##
- # Available through requiring rubygems/installer_test_case
-
- attr_writer :wrappers
-end
-
-##
-# A test case for Gem::Installer.
-
-class Gem::InstallerTestCase < Gem::TestCase
-
- def setup
- super
-
- @installer_tmp = File.join @tempdir, 'installer'
- FileUtils.mkdir_p @installer_tmp
-
- Gem.use_paths @installer_tmp
- Gem.ensure_gem_subdirectories @installer_tmp
-
- @spec = quick_gem 'a'
- util_make_exec @spec
- util_build_gem @spec
- @gem = @spec.cache_file
-
- @user_spec = quick_gem 'b'
- util_make_exec @user_spec
- util_build_gem @user_spec
- @user_gem = @user_spec.cache_file
-
- Gem.use_paths @gemhome
-
- @installer = util_installer @spec, @gemhome
- @user_installer = util_installer @user_spec, Gem.user_dir, :user
-
- Gem.use_paths @gemhome
- end
-
- def util_gem_bindir spec = @spec
- # TODO: deprecate
- spec.bin_dir
- end
-
- def util_gem_dir spec = @spec
- # TODO: deprecate
- spec.gem_dir
- end
-
- def util_inst_bindir
- File.join @gemhome, "bin"
- end
-
- def util_make_exec(spec = @spec, shebang = "#!/usr/bin/ruby")
- spec.executables = %w[executable]
- spec.files << 'bin/executable'
-
- exec_path = spec.bin_file "executable"
- write_file exec_path do |io|
- io.puts shebang
- end
-
- bin_path = File.join @tempdir, "bin", "executable"
- write_file bin_path do |io|
- io.puts shebang
- end
- end
-
- def util_setup_gem(ui = @ui) # HACK fix use_ui to make this automatic
- @spec.files << File.join('lib', 'code.rb')
- @spec.extensions << File.join('ext', 'a', 'mkrf_conf.rb')
-
- Dir.chdir @tempdir do
- FileUtils.mkdir_p 'bin'
- FileUtils.mkdir_p 'lib'
- FileUtils.mkdir_p File.join('ext', 'a')
- File.open File.join('bin', 'executable'), 'w' do |f|
- f.puts "raise 'ran executable'"
- end
- File.open File.join('lib', 'code.rb'), 'w' do |f| f.puts '1' end
- File.open File.join('ext', 'a', 'mkrf_conf.rb'), 'w' do |f|
- f << <<-EOF
- File.open 'Rakefile', 'w' do |rf| rf.puts "task :default" end
- EOF
- end
-
- use_ui ui do
- FileUtils.rm @gem
-
- @gem = Gem::Builder.new(@spec).build
- end
- end
-
- @installer = Gem::Installer.new @gem
- end
-
- def util_installer(spec, gem_home, user=false)
- Gem::Installer.new spec.cache_file, :user_install => user
- end
-end
diff --git a/ruby_1_9_3/lib/rubygems/local_remote_options.rb b/ruby_1_9_3/lib/rubygems/local_remote_options.rb
deleted file mode 100644
index a1e106d9be..0000000000
--- a/ruby_1_9_3/lib/rubygems/local_remote_options.rb
+++ /dev/null
@@ -1,148 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-require 'uri'
-require 'rubygems'
-
-##
-# Mixin methods for local and remote Gem::Command options.
-
-module Gem::LocalRemoteOptions
-
- ##
- # Allows OptionParser to handle HTTP URIs.
-
- def accept_uri_http
- OptionParser.accept URI::HTTP do |value|
- begin
- uri = URI.parse value
- rescue URI::InvalidURIError
- raise OptionParser::InvalidArgument, value
- end
-
- unless ['http', 'https', 'file'].include?(uri.scheme)
- raise OptionParser::InvalidArgument, value
- end
-
- value
- end
- end
-
- ##
- # Add local/remote options to the command line parser.
-
- def add_local_remote_options
- add_option(:"Local/Remote", '-l', '--local',
- 'Restrict operations to the LOCAL domain') do |value, options|
- options[:domain] = :local
- end
-
- add_option(:"Local/Remote", '-r', '--remote',
- 'Restrict operations to the REMOTE domain') do |value, options|
- options[:domain] = :remote
- end
-
- add_option(:"Local/Remote", '-b', '--both',
- 'Allow LOCAL and REMOTE operations') do |value, options|
- options[:domain] = :both
- end
-
- add_bulk_threshold_option
- add_clear_sources_option
- add_source_option
- add_proxy_option
- add_update_sources_option
- end
-
- ##
- # Add the --bulk-threshold option
-
- def add_bulk_threshold_option
- add_option(:"Local/Remote", '-B', '--bulk-threshold COUNT',
- "Threshold for switching to bulk",
- "synchronization (default #{Gem.configuration.bulk_threshold})") do
- |value, options|
- Gem.configuration.bulk_threshold = value.to_i
- end
- end
-
- ##
- # Add the --clear-sources option
-
- def add_clear_sources_option
- add_option(:"Local/Remote", '--clear-sources',
- 'Clear the gem sources') do |value, options|
-
- Gem.sources = nil
- options[:sources_cleared] = true
- end
- end
-
- ##
- # Add the --http-proxy option
-
- def add_proxy_option
- accept_uri_http
-
- add_option(:"Local/Remote", '-p', '--[no-]http-proxy [URL]', URI::HTTP,
- 'Use HTTP proxy for remote operations') do |value, options|
- options[:http_proxy] = (value == false) ? :no_proxy : value
- Gem.configuration[:http_proxy] = options[:http_proxy]
- end
- end
-
- ##
- # Add the --source option
-
- def add_source_option
- accept_uri_http
-
- add_option(:"Local/Remote", '--source URL', URI::HTTP,
- 'Add URL as a remote source for gems') do |source, options|
-
- source << '/' if source !~ /\/\z/
-
- if options.delete :sources_cleared then
- Gem.sources = [source]
- else
- Gem.sources << source unless Gem.sources.include?(source)
- end
- end
- end
-
- ##
- # Add the --update-sources option
-
- def add_update_sources_option
- add_option(:Deprecated, '-u', '--[no-]update-sources',
- 'Update local source cache') do |value, options|
- Gem.configuration.update_sources = value
- end
- end
-
- ##
- # Is fetching of local and remote information enabled?
-
- def both?
- options[:domain] == :both
- end
-
- ##
- # Is local fetching enabled?
-
- def local?
- options[:domain] == :local || options[:domain] == :both
- end
-
- ##
- # Is remote fetching enabled?
-
- def remote?
- options[:domain] == :remote || options[:domain] == :both
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/mock_gem_ui.rb b/ruby_1_9_3/lib/rubygems/mock_gem_ui.rb
deleted file mode 100644
index 13f0bf564b..0000000000
--- a/ruby_1_9_3/lib/rubygems/mock_gem_ui.rb
+++ /dev/null
@@ -1,71 +0,0 @@
-require 'stringio'
-require 'rubygems/user_interaction'
-
-##
-# This Gem::StreamUI subclass records input and output to StringIO for
-# retrieval during tests.
-
-class Gem::MockGemUi < Gem::StreamUI
- class TermError < RuntimeError
- attr_reader :exit_code
-
- def initialize exit_code
- super
- @exit_code = exit_code
- end
- end
- class SystemExitException < RuntimeError; end
-
- module TTY
-
- attr_accessor :tty
-
- def tty?()
- @tty = true unless defined?(@tty)
- @tty
- end
-
- def noecho
- yield self
- end
- end
-
- def initialize(input = "")
- ins = StringIO.new input
- outs = StringIO.new
- errs = StringIO.new
-
- ins.extend TTY
- outs.extend TTY
- errs.extend TTY
-
- super ins, outs, errs, true
-
- @terminated = false
- end
-
- def input
- @ins.string
- end
-
- def output
- @outs.string
- end
-
- def error
- @errs.string
- end
-
- def terminated?
- @terminated
- end
-
- def terminate_interaction(status=0)
- @terminated = true
-
- raise TermError, status if status != 0
- raise SystemExitException
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/old_format.rb b/ruby_1_9_3/lib/rubygems/old_format.rb
deleted file mode 100644
index a44fd533a5..0000000000
--- a/ruby_1_9_3/lib/rubygems/old_format.rb
+++ /dev/null
@@ -1,153 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-require 'rubygems'
-
-##
-# The format class knows the guts of the RubyGem .gem file format and provides
-# the capability to read gem files
-
-class Gem::OldFormat
-
- attr_accessor :spec, :file_entries, :gem_path
-
- ##
- # Constructs an instance of a Format object, representing the gem's data
- # structure.
- #
- # gem:: [String] The file name of the gem
-
- def initialize(gem_path)
- require 'fileutils'
- require 'zlib'
- Gem.load_yaml
-
- @gem_path = gem_path
- end
-
- ##
- # Reads the named gem file and returns a Format object, representing the
- # data from the gem file
- #
- # file_path:: [String] Path to the gem file
-
- def self.from_file_by_path(file_path)
- unless File.exist?(file_path)
- raise Gem::Exception, "Cannot load gem file [#{file_path}]"
- end
-
- File.open(file_path, 'rb') do |file|
- from_io(file, file_path)
- end
- end
-
- ##
- # Reads a gem from an io stream and returns a Format object, representing
- # the data from the gem file
- #
- # io:: [IO] Stream from which to read the gem
-
- def self.from_io(io, gem_path="(io)")
- format = self.new(gem_path)
- skip_ruby(io)
- format.spec = read_spec(io)
- format.file_entries = []
- read_files_from_gem(io) do |entry, file_data|
- format.file_entries << [entry, file_data]
- end
- format
- end
-
- private
-
- ##
- # Skips the Ruby self-install header. After calling this method, the
- # IO index will be set after the Ruby code.
- #
- # file:: [IO] The IO to process (skip the Ruby code)
-
- def self.skip_ruby(file)
- end_seen = false
- loop {
- line = file.gets
- if(line == nil || line.chomp == "__END__") then
- end_seen = true
- break
- end
- }
-
- if end_seen == false then
- raise Gem::Exception.new("Failed to find end of ruby script while reading gem")
- end
- end
-
- ##
- # Reads the specification YAML from the supplied IO and constructs
- # a Gem::Specification from it. After calling this method, the
- # IO index will be set after the specification header.
- #
- # file:: [IO] The IO to process
-
- def self.read_spec(file)
- yaml = ''
-
- read_until_dashes file do |line|
- yaml << line
- end
-
- Gem::Specification.from_yaml yaml
- rescue YAML::Error => e
- raise Gem::Exception, "Failed to parse gem specification out of gem file"
- rescue ArgumentError => e
- raise Gem::Exception, "Failed to parse gem specification out of gem file"
- end
-
- ##
- # Reads lines from the supplied IO until a end-of-yaml (---) is
- # reached
- #
- # file:: [IO] The IO to process
- # block:: [String] The read line
-
- def self.read_until_dashes(file)
- while((line = file.gets) && line.chomp.strip != "---") do
- yield line
- end
- end
-
- ##
- # Reads the embedded file data from a gem file, yielding an entry
- # containing metadata about the file and the file contents themselves
- # for each file that's archived in the gem.
- # NOTE: Many of these methods should be extracted into some kind of
- # Gem file read/writer
- #
- # gem_file:: [IO] The IO to process
-
- def self.read_files_from_gem(gem_file)
- errstr = "Error reading files from gem"
- header_yaml = ''
- begin
- self.read_until_dashes(gem_file) do |line|
- header_yaml << line
- end
- header = YAML.load(header_yaml)
- raise Gem::Exception, errstr unless header
-
- header.each do |entry|
- file_data = ''
- self.read_until_dashes(gem_file) do |line|
- file_data << line
- end
- yield [entry, Zlib::Inflate.inflate(file_data.strip.unpack("m")[0])]
- end
- rescue Zlib::DataError
- raise Gem::Exception, errstr
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/package.rb b/ruby_1_9_3/lib/rubygems/package.rb
deleted file mode 100644
index 2b50c588ee..0000000000
--- a/ruby_1_9_3/lib/rubygems/package.rb
+++ /dev/null
@@ -1,83 +0,0 @@
-# -*- coding: utf-8 -*-
-#--
-# Copyright (C) 2004 Mauricio Julio Fernández Pradier
-# See LICENSE.txt for additional licensing information.
-#++
-
-require 'rubygems/specification'
-
-module Gem::Package
-
- class Error < StandardError; end
- class NonSeekableIO < Error; end
- class ClosedIO < Error; end
- class BadCheckSum < Error; end
- class TooLongFileName < Error; end
- class FormatError < Error
- attr_reader :path
-
- def initialize message, path = nil
- @path = path
-
- message << " in #{path}" if path
-
- super message
- end
-
- end
-
- ##
- # Raised when a tar file is corrupt
-
- class TarInvalidError < Error; end
-
- # FIX: zenspider said: does it really take an IO?
- # passed to a method called open?!? that seems stupid.
- def self.open(io, mode = "r", signer = nil, &block)
- tar_type = case mode
- when 'r' then TarInput
- when 'w' then TarOutput
- else
- raise "Unknown Package open mode"
- end
-
- tar_type.open(io, signer, &block)
- end
-
- def self.pack(src, destname, signer = nil)
- TarOutput.open(destname, signer) do |outp|
- dir_class.chdir(src) do
- outp.metadata = (file_class.read("RPA/metadata") rescue nil)
- find_class.find('.') do |entry|
- case
- when file_class.file?(entry)
- entry.sub!(%r{\./}, "")
- next if entry =~ /\ARPA\//
- stat = File.stat(entry)
- outp.add_file_simple(entry, stat.mode, stat.size) do |os|
- file_class.open(entry, "rb") do |f|
- os.write(f.read(4096)) until f.eof?
- end
- end
- when file_class.dir?(entry)
- entry.sub!(%r{\./}, "")
- next if entry == "RPA"
- outp.mkdir(entry, file_class.stat(entry).mode)
- else
- raise "Don't know how to pack this yet!"
- end
- end
- end
- end
- end
-
-end
-
-require 'rubygems/package/f_sync_dir'
-require 'rubygems/package/tar_header'
-require 'rubygems/package/tar_input'
-require 'rubygems/package/tar_output'
-require 'rubygems/package/tar_reader'
-require 'rubygems/package/tar_reader/entry'
-require 'rubygems/package/tar_writer'
-
diff --git a/ruby_1_9_3/lib/rubygems/package/f_sync_dir.rb b/ruby_1_9_3/lib/rubygems/package/f_sync_dir.rb
deleted file mode 100644
index f7eb7f3ce3..0000000000
--- a/ruby_1_9_3/lib/rubygems/package/f_sync_dir.rb
+++ /dev/null
@@ -1,23 +0,0 @@
-# -*- coding: utf-8 -*-
-#--
-# Copyright (C) 2004 Mauricio Julio Fernández Pradier
-# See LICENSE.txt for additional licensing information.
-#++
-
-module Gem::Package::FSyncDir
-
- private
-
- ##
- # make sure this hits the disc
-
- def fsync_dir(dirname)
- dir = open dirname, 'r'
- dir.fsync
- rescue # ignore IOError if it's an unpatched (old) Ruby
- ensure
- dir.close if dir rescue nil
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/package/tar_header.rb b/ruby_1_9_3/lib/rubygems/package/tar_header.rb
deleted file mode 100644
index 4f923b9b5e..0000000000
--- a/ruby_1_9_3/lib/rubygems/package/tar_header.rb
+++ /dev/null
@@ -1,266 +0,0 @@
-# -*- coding: utf-8 -*-
-#--
-# Copyright (C) 2004 Mauricio Julio Fernández Pradier
-# See LICENSE.txt for additional licensing information.
-#++
-
-##
-#--
-# struct tarfile_entry_posix {
-# char name[100]; # ASCII + (Z unless filled)
-# char mode[8]; # 0 padded, octal, null
-# char uid[8]; # ditto
-# char gid[8]; # ditto
-# char size[12]; # 0 padded, octal, null
-# char mtime[12]; # 0 padded, octal, null
-# char checksum[8]; # 0 padded, octal, null, space
-# char typeflag[1]; # file: "0" dir: "5"
-# char linkname[100]; # ASCII + (Z unless filled)
-# char magic[6]; # "ustar\0"
-# char version[2]; # "00"
-# char uname[32]; # ASCIIZ
-# char gname[32]; # ASCIIZ
-# char devmajor[8]; # 0 padded, octal, null
-# char devminor[8]; # o padded, octal, null
-# char prefix[155]; # ASCII + (Z unless filled)
-# };
-#++
-# A header for a tar file
-
-class Gem::Package::TarHeader
-
- ##
- # Fields in the tar header
-
- FIELDS = [
- :checksum,
- :devmajor,
- :devminor,
- :gid,
- :gname,
- :linkname,
- :magic,
- :mode,
- :mtime,
- :name,
- :prefix,
- :size,
- :typeflag,
- :uid,
- :uname,
- :version,
- ]
-
- ##
- # Pack format for a tar header
-
- PACK_FORMAT = 'a100' + # name
- 'a8' + # mode
- 'a8' + # uid
- 'a8' + # gid
- 'a12' + # size
- 'a12' + # mtime
- 'a7a' + # chksum
- 'a' + # typeflag
- 'a100' + # linkname
- 'a6' + # magic
- 'a2' + # version
- 'a32' + # uname
- 'a32' + # gname
- 'a8' + # devmajor
- 'a8' + # devminor
- 'a155' # prefix
-
- ##
- # Unpack format for a tar header
-
- UNPACK_FORMAT = 'A100' + # name
- 'A8' + # mode
- 'A8' + # uid
- 'A8' + # gid
- 'A12' + # size
- 'A12' + # mtime
- 'A8' + # checksum
- 'A' + # typeflag
- 'A100' + # linkname
- 'A6' + # magic
- 'A2' + # version
- 'A32' + # uname
- 'A32' + # gname
- 'A8' + # devmajor
- 'A8' + # devminor
- 'A155' # prefix
-
- attr_reader(*FIELDS)
-
- ##
- # Creates a tar header from IO +stream+
-
- def self.from(stream)
- header = stream.read 512
- empty = (header == "\0" * 512)
-
- fields = header.unpack UNPACK_FORMAT
-
- name = fields.shift
- mode = fields.shift.oct
- uid = fields.shift.oct
- gid = fields.shift.oct
- size = fields.shift.oct
- mtime = fields.shift.oct
- checksum = fields.shift.oct
- typeflag = fields.shift
- linkname = fields.shift
- magic = fields.shift
- version = fields.shift.oct
- uname = fields.shift
- gname = fields.shift
- devmajor = fields.shift.oct
- devminor = fields.shift.oct
- prefix = fields.shift
-
- new :name => name,
- :mode => mode,
- :uid => uid,
- :gid => gid,
- :size => size,
- :mtime => mtime,
- :checksum => checksum,
- :typeflag => typeflag,
- :linkname => linkname,
- :magic => magic,
- :version => version,
- :uname => uname,
- :gname => gname,
- :devmajor => devmajor,
- :devminor => devminor,
- :prefix => prefix,
-
- :empty => empty
-
- # HACK unfactor for Rubinius
- #new :name => fields.shift,
- # :mode => fields.shift.oct,
- # :uid => fields.shift.oct,
- # :gid => fields.shift.oct,
- # :size => fields.shift.oct,
- # :mtime => fields.shift.oct,
- # :checksum => fields.shift.oct,
- # :typeflag => fields.shift,
- # :linkname => fields.shift,
- # :magic => fields.shift,
- # :version => fields.shift.oct,
- # :uname => fields.shift,
- # :gname => fields.shift,
- # :devmajor => fields.shift.oct,
- # :devminor => fields.shift.oct,
- # :prefix => fields.shift,
-
- # :empty => empty
- end
-
- ##
- # Creates a new TarHeader using +vals+
-
- def initialize(vals)
- unless vals[:name] && vals[:size] && vals[:prefix] && vals[:mode] then
- raise ArgumentError, ":name, :size, :prefix and :mode required"
- end
-
- vals[:uid] ||= 0
- vals[:gid] ||= 0
- vals[:mtime] ||= 0
- vals[:checksum] ||= ""
- vals[:typeflag] ||= "0"
- vals[:magic] ||= "ustar"
- vals[:version] ||= "00"
- vals[:uname] ||= "wheel"
- vals[:gname] ||= "wheel"
- vals[:devmajor] ||= 0
- vals[:devminor] ||= 0
-
- FIELDS.each do |name|
- instance_variable_set "@#{name}", vals[name]
- end
-
- @empty = vals[:empty]
- end
-
- ##
- # Is the tar entry empty?
-
- def empty?
- @empty
- end
-
- def ==(other) # :nodoc:
- self.class === other and
- @checksum == other.checksum and
- @devmajor == other.devmajor and
- @devminor == other.devminor and
- @gid == other.gid and
- @gname == other.gname and
- @linkname == other.linkname and
- @magic == other.magic and
- @mode == other.mode and
- @mtime == other.mtime and
- @name == other.name and
- @prefix == other.prefix and
- @size == other.size and
- @typeflag == other.typeflag and
- @uid == other.uid and
- @uname == other.uname and
- @version == other.version
- end
-
- def to_s # :nodoc:
- update_checksum
- header
- end
-
- ##
- # Updates the TarHeader's checksum
-
- def update_checksum
- header = header " " * 8
- @checksum = oct calculate_checksum(header), 6
- end
-
- private
-
- def calculate_checksum(header)
- header.unpack("C*").inject { |a, b| a + b }
- end
-
- def header(checksum = @checksum)
- header = [
- name,
- oct(mode, 7),
- oct(uid, 7),
- oct(gid, 7),
- oct(size, 11),
- oct(mtime, 11),
- checksum,
- " ",
- typeflag,
- linkname,
- magic,
- oct(version, 2),
- uname,
- gname,
- oct(devmajor, 7),
- oct(devminor, 7),
- prefix
- ]
-
- header = header.pack PACK_FORMAT
-
- header << ("\0" * ((512 - header.size) % 512))
- end
-
- def oct(num, len)
- "%0#{len}o" % num
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/package/tar_input.rb b/ruby_1_9_3/lib/rubygems/package/tar_input.rb
deleted file mode 100644
index 77b4d698da..0000000000
--- a/ruby_1_9_3/lib/rubygems/package/tar_input.rb
+++ /dev/null
@@ -1,235 +0,0 @@
-# -*- coding: iso-8859-1 -*-
-#++
-# Copyright (C) 2004 Mauricio Julio Fernández Pradier
-# See LICENSE.txt for additional licensing information.
-#--
-
-require 'zlib'
-Gem.load_yaml
-
-class Gem::Package::TarInput
-
- include Gem::Package::FSyncDir
- include Enumerable
-
- attr_reader :metadata
-
- private_class_method :new
-
- def self.open(io, security_policy = nil, &block)
- is = new io, security_policy
-
- yield is
- ensure
- is.close if is
- end
-
- def initialize(io, security_policy = nil)
- @io = io
- @tarreader = Gem::Package::TarReader.new @io
- has_meta = false
-
- data_sig, meta_sig, data_dgst, meta_dgst = nil, nil, nil, nil
- dgst_algo = security_policy ? Gem::Security::OPT[:dgst_algo] : nil
-
- @tarreader.each do |entry|
- case entry.full_name
- when "metadata"
- @metadata = load_gemspec entry.read
- has_meta = true
- when "metadata.gz"
- begin
- # if we have a security_policy, then pre-read the metadata file
- # and calculate it's digest
- sio = nil
- if security_policy
- Gem.ensure_ssl_available
- sio = StringIO.new(entry.read)
- meta_dgst = dgst_algo.digest(sio.string)
- sio.rewind
- end
-
- # Ruby 1.8 doesn't have encoding and YAML is UTF-8
- args = [sio || entry]
- args << { :external_encoding => Encoding::UTF_8 } if
- Object.const_defined?(:Encoding)
-
- gzis = Zlib::GzipReader.new(*args)
-
- # YAML wants an instance of IO
- @metadata = load_gemspec(gzis)
- has_meta = true
- ensure
- gzis.close unless gzis.nil?
- end
- when 'metadata.gz.sig'
- meta_sig = entry.read
- when 'data.tar.gz.sig'
- data_sig = entry.read
- when 'data.tar.gz'
- if security_policy
- Gem.ensure_ssl_available
- data_dgst = dgst_algo.digest(entry.read)
- end
- end
- end
-
- if security_policy then
- Gem.ensure_ssl_available
-
- # map trust policy from string to actual class (or a serialized YAML
- # file, if that exists)
- if String === security_policy then
- if Gem::Security::Policies.key? security_policy then
- # load one of the pre-defined security policies
- security_policy = Gem::Security::Policies[security_policy]
- elsif File.exist? security_policy then
- # FIXME: this doesn't work yet
- security_policy = YAML.load File.read(security_policy)
- else
- raise Gem::Exception, "Unknown trust policy '#{security_policy}'"
- end
- end
-
- if data_sig && data_dgst && meta_sig && meta_dgst then
- # the user has a trust policy, and we have a signed gem
- # file, so use the trust policy to verify the gem signature
-
- begin
- security_policy.verify_gem(data_sig, data_dgst, @metadata.cert_chain)
- rescue Exception => e
- raise "Couldn't verify data signature: #{e}"
- end
-
- begin
- security_policy.verify_gem(meta_sig, meta_dgst, @metadata.cert_chain)
- rescue Exception => e
- raise "Couldn't verify metadata signature: #{e}"
- end
- elsif security_policy.only_signed
- raise Gem::Exception, "Unsigned gem"
- else
- # FIXME: should display warning here (trust policy, but
- # either unsigned or badly signed gem file)
- end
- end
-
- @tarreader.rewind
-
- unless has_meta then
- path = io.path if io.respond_to? :path
- error = Gem::Package::FormatError.new 'no metadata found', path
- raise error
- end
- end
-
- def close
- @io.close
- @tarreader.close
- end
-
- def each(&block)
- @tarreader.each do |entry|
- next unless entry.full_name == "data.tar.gz"
- is = zipped_stream entry
-
- begin
- Gem::Package::TarReader.new is do |inner|
- inner.each(&block)
- end
- ensure
- is.close if is
- end
- end
-
- @tarreader.rewind
- end
-
- def extract_entry(destdir, entry, expected_md5sum = nil)
- if entry.directory? then
- dest = File.join destdir, entry.full_name
-
- if File.directory? dest then
- FileUtils.chmod entry.header.mode, dest, :verbose => false
- else
- FileUtils.mkdir_p dest, :mode => entry.header.mode, :verbose => false
- end
-
- fsync_dir dest
- fsync_dir File.join(dest, "..")
-
- return
- end
-
- # it's a file
- md5 = Digest::MD5.new if expected_md5sum
- destdir = File.join destdir, File.dirname(entry.full_name)
- FileUtils.mkdir_p destdir, :mode => 0755, :verbose => false
- destfile = File.join destdir, File.basename(entry.full_name)
- FileUtils.chmod 0600, destfile, :verbose => false rescue nil # Errno::ENOENT
-
- open destfile, "wb", entry.header.mode do |os|
- loop do
- data = entry.read 4096
- break unless data
- # HACK shouldn't we check the MD5 before writing to disk?
- md5 << data if expected_md5sum
- os.write(data)
- end
-
- os.fsync
- end
-
- FileUtils.chmod entry.header.mode, destfile, :verbose => false
- fsync_dir File.dirname(destfile)
- fsync_dir File.join(File.dirname(destfile), "..")
-
- if expected_md5sum && expected_md5sum != md5.hexdigest then
- raise Gem::Package::BadCheckSum
- end
- end
-
- # Attempt to YAML-load a gemspec from the given _io_ parameter. Return
- # nil if it fails.
- def load_gemspec(io)
- Gem::Specification.from_yaml io
- rescue Gem::Exception
- nil
- end
-
- ##
- # Return an IO stream for the zipped entry.
- #
- # NOTE: Originally this method used two approaches, Return a GZipReader
- # directly, or read the GZipReader into a string and return a StringIO on
- # the string. The string IO approach was used for versions of ZLib before
- # 1.2.1 to avoid buffer errors on windows machines. Then we found that
- # errors happened with 1.2.1 as well, so we changed the condition. Then
- # we discovered errors occurred with versions as late as 1.2.3. At this
- # point (after some benchmarking to show we weren't seriously crippling
- # the unpacking speed) we threw our hands in the air and declared that
- # this method would use the String IO approach on all platforms at all
- # times. And that's the way it is.
- #
- # Revisited. Here's the beginning of the long story.
- # http://osdir.com/ml/lang.ruby.gems.devel/2007-06/msg00045.html
- #
- # StringIO wraping has never worked as a workaround by definition. Skipping
- # initial 10 bytes and passing -MAX_WBITS to Zlib::Inflate luckily works as
- # gzip reader, but it only works if the GZip header is 10 bytes long (see
- # below) and it does not check inflated stream consistency (CRC value in the
- # Gzip trailer.)
- #
- # RubyGems generated Gzip Header: 10 bytes
- # magic(2) + method(1) + flag(1) + mtime(4) + exflag(1) + os(1) +
- # orig_name(0) + comment(0)
- #
- # Ideally, it must return a GZipReader without meaningless buffering. We
- # have lots of CRuby committers around so let's fix windows build when we
- # received an error.
- def zipped_stream(entry)
- Zlib::GzipReader.new entry
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/package/tar_output.rb b/ruby_1_9_3/lib/rubygems/package/tar_output.rb
deleted file mode 100644
index fdc8f4fb7c..0000000000
--- a/ruby_1_9_3/lib/rubygems/package/tar_output.rb
+++ /dev/null
@@ -1,146 +0,0 @@
-# -*- coding: utf-8 -*-
-#--
-# Copyright (C) 2004 Mauricio Julio Fernández Pradier
-# See LICENSE.txt for additional licensing information.
-#++
-
-##
-# TarOutput is a wrapper to TarWriter that builds gem-format tar file.
-#
-# Gem-format tar files contain the following files:
-# [data.tar.gz] A gzipped tar file containing the files that compose the gem
-# which will be extracted into the gem/ dir on installation.
-# [metadata.gz] A YAML format Gem::Specification.
-# [data.tar.gz.sig] A signature for the gem's data.tar.gz.
-# [metadata.gz.sig] A signature for the gem's metadata.gz.
-#
-# See TarOutput::open for usage details.
-
-class Gem::Package::TarOutput
-
- ##
- # Creates a new TarOutput which will yield a TarWriter object for the
- # data.tar.gz portion of a gem-format tar file.
- #
- # See #initialize for details on +io+ and +signer+.
- #
- # See #add_gem_contents for details on adding metadata to the tar file.
-
- def self.open(io, signer = nil, &block) # :yield: data_tar_writer
- tar_outputter = new io, signer
- tar_outputter.add_gem_contents(&block)
- tar_outputter.add_metadata
- tar_outputter.add_signatures
-
- ensure
- tar_outputter.close
- end
-
- ##
- # Creates a new TarOutput that will write a gem-format tar file to +io+. If
- # +signer+ is given, the data.tar.gz and metadata.gz will be signed and
- # the signatures will be added to the tar file.
-
- def initialize(io, signer)
- @io = io
- @signer = signer
-
- @tar_writer = Gem::Package::TarWriter.new @io
-
- @metadata = nil
-
- @data_signature = nil
- @meta_signature = nil
- end
-
- ##
- # Yields a TarWriter for the data.tar.gz inside a gem-format tar file.
- # The yielded TarWriter has been extended with a #metadata= method for
- # attaching a YAML format Gem::Specification which will be written by
- # add_metadata.
-
- def add_gem_contents
- @tar_writer.add_file "data.tar.gz", 0644 do |inner|
- sio = @signer ? StringIO.new : nil
- Zlib::GzipWriter.wrap(sio || inner) do |os|
-
- Gem::Package::TarWriter.new os do |data_tar_writer|
- # :stopdoc:
- def data_tar_writer.metadata() @metadata end
- def data_tar_writer.metadata=(metadata) @metadata = metadata end
- # :startdoc:
-
- yield data_tar_writer
-
- @metadata = data_tar_writer.metadata
- end
- end
-
- # if we have a signing key, then sign the data
- # digest and return the signature
- if @signer then
- require 'rubygems/security'
- digest = Gem::Security::OPT[:dgst_algo].digest sio.string
- @data_signature = @signer.sign digest
- inner.write sio.string
- end
- end
-
- self
- end
-
- ##
- # Adds metadata.gz to the gem-format tar file which was saved from a
- # previous #add_gem_contents call.
-
- def add_metadata
- return if @metadata.nil?
-
- @tar_writer.add_file "metadata.gz", 0644 do |io|
- begin
- sio = @signer ? StringIO.new : nil
- gzos = Zlib::GzipWriter.new(sio || io)
- gzos.write @metadata
- ensure
- gzos.flush
- gzos.finish
-
- # if we have a signing key, then sign the metadata digest and return
- # the signature
- if @signer then
- require 'rubygems/security'
- digest = Gem::Security::OPT[:dgst_algo].digest sio.string
- @meta_signature = @signer.sign digest
- io.write sio.string
- end
- end
- end
- end
-
- ##
- # Adds data.tar.gz.sig and metadata.gz.sig to the gem-format tar files if
- # a Gem::Security::Signer was sent to initialize.
-
- def add_signatures
- if @data_signature then
- @tar_writer.add_file 'data.tar.gz.sig', 0644 do |io|
- io.write @data_signature
- end
- end
-
- if @meta_signature then
- @tar_writer.add_file 'metadata.gz.sig', 0644 do |io|
- io.write @meta_signature
- end
- end
- end
-
- ##
- # Closes the TarOutput.
-
- def close
- @tar_writer.close
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/package/tar_reader.rb b/ruby_1_9_3/lib/rubygems/package/tar_reader.rb
deleted file mode 100644
index e6a71d386c..0000000000
--- a/ruby_1_9_3/lib/rubygems/package/tar_reader.rb
+++ /dev/null
@@ -1,106 +0,0 @@
-# -*- coding: utf-8 -*-
-#--
-# Copyright (C) 2004 Mauricio Julio Fernández Pradier
-# See LICENSE.txt for additional licensing information.
-#++
-
-##
-# TarReader reads tar files and allows iteration over their items
-
-class Gem::Package::TarReader
-
- include Gem::Package
-
- ##
- # Raised if the tar IO is not seekable
-
- class UnexpectedEOF < StandardError; end
-
- ##
- # Creates a new TarReader on +io+ and yields it to the block, if given.
-
- def self.new(io)
- reader = super
-
- return reader unless block_given?
-
- begin
- yield reader
- ensure
- reader.close
- end
-
- nil
- end
-
- ##
- # Creates a new tar file reader on +io+ which needs to respond to #pos,
- # #eof?, #read, #getc and #pos=
-
- def initialize(io)
- @io = io
- @init_pos = io.pos
- end
-
- ##
- # Close the tar file
-
- def close
- end
-
- ##
- # Iterates over files in the tarball yielding each entry
-
- def each
- loop do
- return if @io.eof?
-
- header = Gem::Package::TarHeader.from @io
- return if header.empty?
-
- entry = Gem::Package::TarReader::Entry.new header, @io
- size = entry.header.size
-
- yield entry
-
- skip = (512 - (size % 512)) % 512
- pending = size - entry.bytes_read
-
- begin
- # avoid reading...
- @io.seek pending, IO::SEEK_CUR
- pending = 0
- rescue Errno::EINVAL, NameError
- while pending > 0 do
- bytes_read = @io.read([pending, 4096].min).size
- raise UnexpectedEOF if @io.eof?
- pending -= bytes_read
- end
- end
-
- @io.read skip # discard trailing zeros
-
- # make sure nobody can use #read, #getc or #rewind anymore
- entry.close
- end
- end
-
- alias each_entry each
-
- ##
- # NOTE: Do not call #rewind during #each
-
- def rewind
- if @init_pos == 0 then
- raise Gem::Package::NonSeekableIO unless @io.respond_to? :rewind
- @io.rewind
- else
- raise Gem::Package::NonSeekableIO unless @io.respond_to? :pos=
- @io.pos = @init_pos
- end
- end
-
-end
-
-require 'rubygems/package/tar_reader/entry'
-
diff --git a/ruby_1_9_3/lib/rubygems/package/tar_reader/entry.rb b/ruby_1_9_3/lib/rubygems/package/tar_reader/entry.rb
deleted file mode 100644
index 7034e59210..0000000000
--- a/ruby_1_9_3/lib/rubygems/package/tar_reader/entry.rb
+++ /dev/null
@@ -1,145 +0,0 @@
-# -*- coding: utf-8 -*-
-#++
-# Copyright (C) 2004 Mauricio Julio Fernández Pradier
-# See LICENSE.txt for additional licensing information.
-#--
-
-##
-# Class for reading entries out of a tar file
-
-class Gem::Package::TarReader::Entry
-
- ##
- # Header for this tar entry
-
- attr_reader :header
-
- ##
- # Creates a new tar entry for +header+ that will be read from +io+
-
- def initialize(header, io)
- @closed = false
- @header = header
- @io = io
- @orig_pos = @io.pos
- @read = 0
- end
-
- def check_closed # :nodoc:
- raise IOError, "closed #{self.class}" if closed?
- end
-
- ##
- # Number of bytes read out of the tar entry
-
- def bytes_read
- @read
- end
-
- ##
- # Closes the tar entry
-
- def close
- @closed = true
- end
-
- ##
- # Is the tar entry closed?
-
- def closed?
- @closed
- end
-
- ##
- # Are we at the end of the tar entry?
-
- def eof?
- check_closed
-
- @read >= @header.size
- end
-
- ##
- # Full name of the tar entry
-
- def full_name
- if @header.prefix != "" then
- File.join @header.prefix, @header.name
- else
- @header.name
- end
- rescue ArgumentError => e
- raise unless e.message == 'string contains null byte'
- raise Gem::Package::TarInvalidError,
- 'tar is corrupt, name contains null byte'
- end
-
- ##
- # Read one byte from the tar entry
-
- def getc
- check_closed
-
- return nil if @read >= @header.size
-
- ret = @io.getc
- @read += 1 if ret
-
- ret
- end
-
- ##
- # Is this tar entry a directory?
-
- def directory?
- @header.typeflag == "5"
- end
-
- ##
- # Is this tar entry a file?
-
- def file?
- @header.typeflag == "0"
- end
-
- ##
- # The position in the tar entry
-
- def pos
- check_closed
-
- bytes_read
- end
-
- ##
- # Reads +len+ bytes from the tar file entry, or the rest of the entry if
- # nil
-
- def read(len = nil)
- check_closed
-
- return nil if @read >= @header.size
-
- len ||= @header.size - @read
- max_read = [len, @header.size - @read].min
-
- ret = @io.read max_read
- @read += ret.size
-
- ret
- end
-
- ##
- # Rewinds to the beginning of the tar file entry
-
- def rewind
- check_closed
-
- raise Gem::Package::NonSeekableIO unless @io.respond_to? :pos=
-
- @io.pos = @orig_pos
- @read = 0
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/package/tar_test_case.rb b/ruby_1_9_3/lib/rubygems/package/tar_test_case.rb
deleted file mode 100644
index 4601f1328f..0000000000
--- a/ruby_1_9_3/lib/rubygems/package/tar_test_case.rb
+++ /dev/null
@@ -1,137 +0,0 @@
-require 'rubygems/test_case'
-require 'rubygems/package'
-
-##
-# A test case for Gem::Package::Tar* classes
-
-class Gem::Package::TarTestCase < Gem::TestCase
-
- def ASCIIZ(str, length)
- str + "\0" * (length - str.length)
- end
-
- def SP(s)
- s + " "
- end
-
- def SP_Z(s)
- s + " \0"
- end
-
- def Z(s)
- s + "\0"
- end
-
- def assert_headers_equal(expected, actual)
- expected = expected.to_s unless String === expected
- actual = actual.to_s unless String === actual
-
- fields = %w[
- name 100
- mode 8
- uid 8
- gid 8
- size 12
- mtime 12
- checksum 8
- typeflag 1
- linkname 100
- magic 6
- version 2
- uname 32
- gname 32
- devmajor 8
- devminor 8
- prefix 155
- ]
-
- offset = 0
-
- until fields.empty? do
- name = fields.shift
- length = fields.shift.to_i
-
- if name == "checksum" then
- chksum_off = offset
- offset += length
- next
- end
-
- assert_equal expected[offset, length], actual[offset, length],
- "Field #{name} of the tar header differs."
-
- offset += length
- end
-
- assert_equal expected[chksum_off, 8], actual[chksum_off, 8]
- end
-
- def calc_checksum(header)
- sum = header.unpack("C*").inject{|s,a| s + a}
- SP(Z(to_oct(sum, 6)))
- end
-
- def header(type, fname, dname, length, mode, checksum = nil)
- checksum ||= " " * 8
-
- arr = [ # struct tarfile_entry_posix
- ASCIIZ(fname, 100), # char name[100]; ASCII + (Z unless filled)
- Z(to_oct(mode, 7)), # char mode[8]; 0 padded, octal null
- Z(to_oct(0, 7)), # char uid[8]; ditto
- Z(to_oct(0, 7)), # char gid[8]; ditto
- Z(to_oct(length, 11)), # char size[12]; 0 padded, octal, null
- Z(to_oct(0, 11)), # char mtime[12]; 0 padded, octal, null
- checksum, # char checksum[8]; 0 padded, octal, null, space
- type, # char typeflag[1]; file: "0" dir: "5"
- "\0" * 100, # char linkname[100]; ASCII + (Z unless filled)
- "ustar\0", # char magic[6]; "ustar\0"
- "00", # char version[2]; "00"
- ASCIIZ("wheel", 32), # char uname[32]; ASCIIZ
- ASCIIZ("wheel", 32), # char gname[32]; ASCIIZ
- Z(to_oct(0, 7)), # char devmajor[8]; 0 padded, octal, null
- Z(to_oct(0, 7)), # char devminor[8]; 0 padded, octal, null
- ASCIIZ(dname, 155) # char prefix[155]; ASCII + (Z unless filled)
- ]
-
- format = "C100C8C8C8C12C12C8CC100C6C2C32C32C8C8C155"
- h = if RUBY_VERSION >= "1.9" then
- arr.join
- else
- arr = arr.join("").split(//).map{|x| x[0]}
- arr.pack format
- end
- ret = h + "\0" * (512 - h.size)
- assert_equal(512, ret.size)
- ret
- end
-
- def tar_dir_header(name, prefix, mode)
- h = header("5", name, prefix, 0, mode)
- checksum = calc_checksum(h)
- header("5", name, prefix, 0, mode, checksum)
- end
-
- def tar_file_header(fname, dname, mode, length)
- h = header("0", fname, dname, length, mode)
- checksum = calc_checksum(h)
- header("0", fname, dname, length, mode, checksum)
- end
-
- def to_oct(n, pad_size)
- "%0#{pad_size}o" % n
- end
-
- def util_entry(tar)
- io = TempIO.new tar
-
- header = Gem::Package::TarHeader.from io
-
- Gem::Package::TarReader::Entry.new header, io
- end
-
- def util_dir_entry
- util_entry tar_dir_header("foo", "bar", 0)
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/package/tar_writer.rb b/ruby_1_9_3/lib/rubygems/package/tar_writer.rb
deleted file mode 100644
index a73b5e5cab..0000000000
--- a/ruby_1_9_3/lib/rubygems/package/tar_writer.rb
+++ /dev/null
@@ -1,241 +0,0 @@
-# -*- coding: utf-8 -*-
-#--
-# Copyright (C) 2004 Mauricio Julio Fernández Pradier
-# See LICENSE.txt for additional licensing information.
-#++
-
-##
-# Allows writing of tar files
-
-class Gem::Package::TarWriter
-
- class FileOverflow < StandardError; end
-
- ##
- # IO wrapper that allows writing a limited amount of data
-
- class BoundedStream
-
- ##
- # Maximum number of bytes that can be written
-
- attr_reader :limit
-
- ##
- # Number of bytes written
-
- attr_reader :written
-
- ##
- # Wraps +io+ and allows up to +limit+ bytes to be written
-
- def initialize(io, limit)
- @io = io
- @limit = limit
- @written = 0
- end
-
- ##
- # Writes +data+ onto the IO, raising a FileOverflow exception if the
- # number of bytes will be more than #limit
-
- def write(data)
- if data.size + @written > @limit
- raise FileOverflow, "You tried to feed more data than fits in the file."
- end
- @io.write data
- @written += data.size
- data.size
- end
-
- end
-
- ##
- # IO wrapper that provides only #write
-
- class RestrictedStream
-
- ##
- # Creates a new RestrictedStream wrapping +io+
-
- def initialize(io)
- @io = io
- end
-
- ##
- # Writes +data+ onto the IO
-
- def write(data)
- @io.write data
- end
-
- end
-
- ##
- # Creates a new TarWriter, yielding it if a block is given
-
- def self.new(io)
- writer = super
-
- return writer unless block_given?
-
- begin
- yield writer
- ensure
- writer.close
- end
-
- nil
- end
-
- ##
- # Creates a new TarWriter that will write to +io+
-
- def initialize(io)
- @io = io
- @closed = false
- end
-
- ##
- # Adds file +name+ with permissions +mode+, and yields an IO for writing the
- # file to
-
- def add_file(name, mode) # :yields: io
- check_closed
-
- raise Gem::Package::NonSeekableIO unless @io.respond_to? :pos=
-
- name, prefix = split_name name
-
- init_pos = @io.pos
- @io.write "\0" * 512 # placeholder for the header
-
- yield RestrictedStream.new(@io) if block_given?
-
- size = @io.pos - init_pos - 512
-
- remainder = (512 - (size % 512)) % 512
- @io.write "\0" * remainder
-
- final_pos = @io.pos
- @io.pos = init_pos
-
- header = Gem::Package::TarHeader.new :name => name, :mode => mode,
- :size => size, :prefix => prefix
-
- @io.write header
- @io.pos = final_pos
-
- self
- end
-
- ##
- # Add file +name+ with permissions +mode+ +size+ bytes long. Yields an IO
- # to write the file to.
-
- def add_file_simple(name, mode, size) # :yields: io
- check_closed
-
- name, prefix = split_name name
-
- header = Gem::Package::TarHeader.new(:name => name, :mode => mode,
- :size => size, :prefix => prefix).to_s
-
- @io.write header
- os = BoundedStream.new @io, size
-
- yield os if block_given?
-
- min_padding = size - os.written
- @io.write("\0" * min_padding)
-
- remainder = (512 - (size % 512)) % 512
- @io.write("\0" * remainder)
-
- self
- end
-
- ##
- # Raises IOError if the TarWriter is closed
-
- def check_closed
- raise IOError, "closed #{self.class}" if closed?
- end
-
- ##
- # Closes the TarWriter
-
- def close
- check_closed
-
- @io.write "\0" * 1024
- flush
-
- @closed = true
- end
-
- ##
- # Is the TarWriter closed?
-
- def closed?
- @closed
- end
-
- ##
- # Flushes the TarWriter's IO
-
- def flush
- check_closed
-
- @io.flush if @io.respond_to? :flush
- end
-
- ##
- # Creates a new directory in the tar file +name+ with +mode+
-
- def mkdir(name, mode)
- check_closed
-
- name, prefix = split_name(name)
-
- header = Gem::Package::TarHeader.new :name => name, :mode => mode,
- :typeflag => "5", :size => 0,
- :prefix => prefix
-
- @io.write header
-
- self
- end
-
- ##
- # Splits +name+ into a name and prefix that can fit in the TarHeader
-
- def split_name(name) # :nodoc:
- raise Gem::Package::TooLongFileName if name.size > 256
-
- if name.size <= 100 then
- prefix = ""
- else
- parts = name.split(/\//)
- newname = parts.pop
- nxt = ""
-
- loop do
- nxt = parts.pop
- break if newname.size + 1 + nxt.size > 100
- newname = nxt + "/" + newname
- end
-
- prefix = (parts + [nxt]).join "/"
- name = newname
-
- if name.size > 100 or prefix.size > 155 then
- raise Gem::Package::TooLongFileName
- end
- end
-
- return name, prefix
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/package_task.rb b/ruby_1_9_3/lib/rubygems/package_task.rb
deleted file mode 100644
index fe32a03b27..0000000000
--- a/ruby_1_9_3/lib/rubygems/package_task.rb
+++ /dev/null
@@ -1,126 +0,0 @@
-# Copyright (c) 2003, 2004 Jim Weirich, 2009 Eric Hodel
-#
-# Permission is hereby granted, free of charge, to any person obtaining
-# a copy of this software and associated documentation files (the
-# "Software"), to deal in the Software without restriction, including
-# without limitation the rights to use, copy, modify, merge, publish,
-# distribute, sublicense, and/or sell copies of the Software, and to
-# permit persons to whom the Software is furnished to do so, subject to
-# the following conditions:
-#
-# The above copyright notice and this permission notice shall be
-# included in all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-require 'rubygems'
-begin
- gem 'rake'
-rescue Gem::LoadError
-end
-
-require 'rake/packagetask'
-
-##
-# Create a package based upon a Gem::Specification. Gem packages, as well as
-# zip files and tar/gzipped packages can be produced by this task.
-#
-# In addition to the Rake targets generated by Rake::PackageTask, a
-# Gem::PackageTask will also generate the following tasks:
-#
-# [<b>"<em>package_dir</em>/<em>name</em>-<em>version</em>.gem"</b>]
-# Create a RubyGems package with the given name and version.
-#
-# Example using a Gem::Specification:
-#
-# require 'rubygems'
-# require 'rubygems/package_task'
-#
-# spec = Gem::Specification.new do |s|
-# s.platform = Gem::Platform::RUBY
-# s.summary = "Ruby based make-like utility."
-# s.name = 'rake'
-# s.version = PKG_VERSION
-# s.requirements << 'none'
-# s.require_path = 'lib'
-# s.autorequire = 'rake'
-# s.files = PKG_FILES
-# s.description = <<-EOF
-# Rake is a Make-like program implemented in Ruby. Tasks
-# and dependencies are specified in standard Ruby syntax.
-# EOF
-# end
-#
-# Gem::PackageTask.new(spec) do |pkg|
-# pkg.need_zip = true
-# pkg.need_tar = true
-# end
-
-class Gem::PackageTask < Rake::PackageTask
-
- ##
- # Ruby Gem::Specification containing the metadata for this package. The
- # name, version and package_files are automatically determined from the
- # gemspec and don't need to be explicitly provided.
-
- attr_accessor :gem_spec
-
- ##
- # Create a Gem Package task library. Automatically define the gem if a
- # block is given. If no block is supplied, then #define needs to be called
- # to define the task.
-
- def initialize(gem_spec)
- init gem_spec
- yield self if block_given?
- define if block_given?
- end
-
- ##
- # Initialization tasks without the "yield self" or define operations.
-
- def init(gem)
- super gem.full_name, :noversion
- @gem_spec = gem
- @package_files += gem_spec.files if gem_spec.files
- end
-
- ##
- # Create the Rake tasks and actions specified by this Gem::PackageTask.
- # (+define+ is automatically called if a block is given to +new+).
-
- def define
- super
-
- task :package => [:gem]
-
- gem_file = File.basename gem_spec.cache_file
- gem_path = File.join package_dir, gem_file
- gem_dir = File.join package_dir, gem_spec.full_name
-
- desc "Build the gem file #{gem_file}"
- task :gem => [gem_path]
-
- trace = Rake.application.options.trace
- Gem.configuration.verbose = trace
-
- file gem_path => [package_dir, gem_dir] + @gem_spec.files do
- chdir(gem_dir) do
- when_writing "Creating #{gem_spec.file_name}" do
- Gem::Builder.new(gem_spec).build
- verbose trace do
- mv gem_file, '..'
- end
- end
- end
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/path_support.rb b/ruby_1_9_3/lib/rubygems/path_support.rb
deleted file mode 100644
index 0aaf2c1bed..0000000000
--- a/ruby_1_9_3/lib/rubygems/path_support.rb
+++ /dev/null
@@ -1,70 +0,0 @@
-##
-# Gem::PathSupport facilitates the GEM_HOME and GEM_PATH environment settings
-# to the rest of RubyGems.
-#
-class Gem::PathSupport
- ##
- # The default system path for managing Gems.
- attr_reader :home
-
- ##
- # Array of paths to search for Gems.
- attr_reader :path
-
- ##
- #
- # Constructor. Takes a single argument which is to be treated like a
- # hashtable, or defaults to ENV, the system environment.
- #
- def initialize(env=ENV)
- @env = env
-
- # note 'env' vs 'ENV'...
- @home = env["GEM_HOME"] || ENV["GEM_HOME"] || Gem.default_dir
-
- if File::ALT_SEPARATOR then
- @home = @home.gsub(File::ALT_SEPARATOR, File::SEPARATOR)
- end
-
- self.path = env["GEM_PATH"] || ENV["GEM_PATH"]
- end
-
- private
-
- ##
- # Set the Gem home directory (as reported by Gem.dir).
-
- def home=(home)
- @home = home.to_s
- end
-
- ##
- # Set the Gem search path (as reported by Gem.path).
-
- def path=(gpaths)
- gem_path = [@home]
-
- # FIX: I can't tell wtf this is doing.
- gpaths ||= (ENV['GEM_PATH'] || "").empty? ? nil : ENV["GEM_PATH"]
-
- if gpaths then
- if gpaths.kind_of?(Array) then
- gem_path.push(*gpaths)
- else
- gem_path.push(*gpaths.split(File::PATH_SEPARATOR))
- end
-
- if File::ALT_SEPARATOR then
- gem_path.map! do |this_path|
- this_path.gsub File::ALT_SEPARATOR, File::SEPARATOR
- end
- end
- else
- gem_path.push(*Gem.default_path)
-
- gem_path << APPLE_GEM_HOME if defined?(APPLE_GEM_HOME)
- end
-
- @path = gem_path.uniq
- end
-end
diff --git a/ruby_1_9_3/lib/rubygems/platform.rb b/ruby_1_9_3/lib/rubygems/platform.rb
deleted file mode 100644
index 682714a5de..0000000000
--- a/ruby_1_9_3/lib/rubygems/platform.rb
+++ /dev/null
@@ -1,194 +0,0 @@
-require "rubygems/deprecate"
-
-##
-# Available list of platforms for targeting Gem installations.
-
-class Gem::Platform
-
- @local = nil
-
- attr_accessor :cpu
-
- attr_accessor :os
-
- attr_accessor :version
-
- def self.local
- arch = Gem::ConfigMap[:arch]
- arch = "#{arch}_60" if arch =~ /mswin32$/
- @local ||= new(arch)
- end
-
- def self.match(platform)
- Gem.platforms.any? do |local_platform|
- platform.nil? or local_platform == platform or
- (local_platform != Gem::Platform::RUBY and local_platform =~ platform)
- end
- end
-
- def self.new(arch) # :nodoc:
- case arch
- when Gem::Platform::CURRENT then
- Gem::Platform.local
- when Gem::Platform::RUBY, nil, '' then
- Gem::Platform::RUBY
- else
- super
- end
- end
-
- def initialize(arch)
- case arch
- when Array then
- @cpu, @os, @version = arch
- when String then
- arch = arch.split '-'
-
- if arch.length > 2 and arch.last !~ /\d/ then # reassemble x86-linux-gnu
- extra = arch.pop
- arch.last << "-#{extra}"
- end
-
- cpu = arch.shift
-
- @cpu = case cpu
- when /i\d86/ then 'x86'
- else cpu
- end
-
- if arch.length == 2 and arch.last =~ /^\d+(\.\d+)?$/ then # for command-line
- @os, @version = arch
- return
- end
-
- os, = arch
- @cpu, os = nil, cpu if os.nil? # legacy jruby
-
- @os, @version = case os
- when /aix(\d+)/ then [ 'aix', $1 ]
- when /cygwin/ then [ 'cygwin', nil ]
- when /darwin(\d+)?/ then [ 'darwin', $1 ]
- when /^macruby$/ then [ 'macruby', nil ]
- when /freebsd(\d+)/ then [ 'freebsd', $1 ]
- when /hpux(\d+)/ then [ 'hpux', $1 ]
- when /^java$/, /^jruby$/ then [ 'java', nil ]
- when /^java([\d.]*)/ then [ 'java', $1 ]
- when /^dotnet$/ then [ 'dotnet', nil ]
- when /^dotnet([\d.]*)/ then [ 'dotnet', $1 ]
- when /linux/ then [ 'linux', $1 ]
- when /mingw32/ then [ 'mingw32', nil ]
- when /(mswin\d+)(\_(\d+))?/ then
- os, version = $1, $3
- @cpu = 'x86' if @cpu.nil? and os =~ /32$/
- [os, version]
- when /netbsdelf/ then [ 'netbsdelf', nil ]
- when /openbsd(\d+\.\d+)/ then [ 'openbsd', $1 ]
- when /solaris(\d+\.\d+)/ then [ 'solaris', $1 ]
- # test
- when /^(\w+_platform)(\d+)/ then [ $1, $2 ]
- else [ 'unknown', nil ]
- end
- when Gem::Platform then
- @cpu = arch.cpu
- @os = arch.os
- @version = arch.version
- else
- raise ArgumentError, "invalid argument #{arch.inspect}"
- end
- end
-
- def inspect
- "#<%s:0x%x @cpu=%p, @os=%p, @version=%p>" % [self.class, object_id, *to_a]
- end
-
- def to_a
- [@cpu, @os, @version]
- end
-
- def to_s
- to_a.compact.join '-'
- end
-
- def empty?
- to_s.empty?
- end
-
- ##
- # Is +other+ equal to this platform? Two platforms are equal if they have
- # the same CPU, OS and version.
-
- def ==(other)
- self.class === other and to_a == other.to_a
- end
-
- alias :eql? :==
-
- def hash # :nodoc:
- to_a.hash
- end
-
- ##
- # Does +other+ match this platform? Two platforms match if they have the
- # same CPU, or either has a CPU of 'universal', they have the same OS, and
- # they have the same version, or either has no version.
-
- def ===(other)
- return nil unless Gem::Platform === other
-
- # cpu
- (@cpu == 'universal' or other.cpu == 'universal' or @cpu == other.cpu) and
-
- # os
- @os == other.os and
-
- # version
- (@version.nil? or other.version.nil? or @version == other.version)
- end
-
- ##
- # Does +other+ match this platform? If +other+ is a String it will be
- # converted to a Gem::Platform first. See #=== for matching rules.
-
- def =~(other)
- case other
- when Gem::Platform then # nop
- when String then
- # This data is from http://gems.rubyforge.org/gems/yaml on 19 Aug 2007
- other = case other
- when /^i686-darwin(\d)/ then ['x86', 'darwin', $1 ]
- when /^i\d86-linux/ then ['x86', 'linux', nil ]
- when 'java', 'jruby' then [nil, 'java', nil ]
- when /dotnet(\-(\d+\.\d+))?/ then ['universal','dotnet', $2 ]
- when /mswin32(\_(\d+))?/ then ['x86', 'mswin32', $2 ]
- when 'powerpc-darwin' then ['powerpc', 'darwin', nil ]
- when /powerpc-darwin(\d)/ then ['powerpc', 'darwin', $1 ]
- when /sparc-solaris2.8/ then ['sparc', 'solaris', '2.8' ]
- when /universal-darwin(\d)/ then ['universal', 'darwin', $1 ]
- else other
- end
-
- other = Gem::Platform.new other
- else
- return nil
- end
-
- self === other
- end
-
- ##
- # A pure-ruby gem that may use Gem::Specification#extensions to build
- # binary files.
-
- RUBY = 'ruby'
-
- ##
- # A platform-specific gem that is built for the packaging ruby's platform.
- # This will be replaced with Gem::Platform::local.
-
- CURRENT = 'current'
-
- extend Gem::Deprecate
-
- deprecate :empty?, :none, 2011, 11
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/psych_additions.rb b/ruby_1_9_3/lib/rubygems/psych_additions.rb
deleted file mode 100644
index 6a46bdaf3c..0000000000
--- a/ruby_1_9_3/lib/rubygems/psych_additions.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-# This exists just to satify bugs in marshal'd gemspecs that
-# contain a reference to YAML::PrivateType. We prune these out
-# in Specification._load, but if we don't have the constant, Marshal
-# blows up.
-
-module Psych
- class PrivateType
- end
-end
-# This exists just to satify bugs in marshal'd gemspecs that
-# contain a reference to YAML::PrivateType. We prune these out
-# in Specification._load, but if we don't have the constant, Marshal
-# blows up.
-
-module Psych
- class PrivateType
- end
-end
diff --git a/ruby_1_9_3/lib/rubygems/psych_tree.rb b/ruby_1_9_3/lib/rubygems/psych_tree.rb
deleted file mode 100644
index d73541e4f2..0000000000
--- a/ruby_1_9_3/lib/rubygems/psych_tree.rb
+++ /dev/null
@@ -1,54 +0,0 @@
-module Gem
- if defined? ::Psych::Visitors
- class NoAliasYAMLTree < Psych::Visitors::YAMLTree
- def visit_String(str)
- return super unless str == '=' # or whatever you want
-
- quote = Psych::Nodes::Scalar::SINGLE_QUOTED
- @emitter.scalar str, nil, nil, false, true, quote
- end
-
- # Noop this out so there are no anchors
- def register(target, obj)
- end
-
- # This is ported over from the yaml_tree in 1.9.3
- def format_time time
- if time.utc?
- time.strftime("%Y-%m-%d %H:%M:%S.%9N Z")
- else
- time.strftime("%Y-%m-%d %H:%M:%S.%9N %:z")
- end
- end
-
- private :format_time
- end
- end
-end
-module Gem
- if defined? ::Psych::Visitors
- class NoAliasYAMLTree < Psych::Visitors::YAMLTree
- def visit_String(str)
- return super unless str == '=' # or whatever you want
-
- quote = Psych::Nodes::Scalar::SINGLE_QUOTED
- @emitter.scalar str, nil, nil, false, true, quote
- end
-
- # Noop this out so there are no anchors
- def register(target, obj)
- end
-
- # This is ported over from the yaml_tree in 1.9.3
- def format_time time
- if time.utc?
- time.strftime("%Y-%m-%d %H:%M:%S.%9N Z")
- else
- time.strftime("%Y-%m-%d %H:%M:%S.%9N %:z")
- end
- end
-
- private :format_time
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rubygems/remote_fetcher.rb b/ruby_1_9_3/lib/rubygems/remote_fetcher.rb
deleted file mode 100644
index 9827e66f34..0000000000
--- a/ruby_1_9_3/lib/rubygems/remote_fetcher.rb
+++ /dev/null
@@ -1,507 +0,0 @@
-require 'rubygems'
-require 'rubygems/user_interaction'
-require 'uri'
-
-##
-# RemoteFetcher handles the details of fetching gems and gem information from
-# a remote source.
-
-class Gem::RemoteFetcher
-
- BuiltinSSLCerts = File.expand_path("./ssl_certs/*.pem", File.dirname(__FILE__))
-
- include Gem::UserInteraction
-
- ##
- # A FetchError exception wraps up the various possible IO and HTTP failures
- # that could happen while downloading from the internet.
-
- class FetchError < Gem::Exception
-
- ##
- # The URI which was being accessed when the exception happened.
-
- attr_accessor :uri
-
- def initialize(message, uri)
- super message
- @uri = uri
- end
-
- def to_s # :nodoc:
- "#{super} (#{uri})"
- end
-
- end
-
- @fetcher = nil
-
- ##
- # Cached RemoteFetcher instance.
-
- def self.fetcher
- @fetcher ||= self.new Gem.configuration[:http_proxy]
- end
-
- ##
- # Initialize a remote fetcher using the source URI and possible proxy
- # information.
- #
- # +proxy+
- # * [String]: explicit specification of proxy; overrides any environment
- # variable setting
- # * nil: respect environment variables (HTTP_PROXY, HTTP_PROXY_USER,
- # HTTP_PROXY_PASS)
- # * <tt>:no_proxy</tt>: ignore environment variables and _don't_ use a proxy
-
- def initialize(proxy = nil)
- require 'net/http'
- require 'stringio'
- require 'time'
- require 'uri'
-
- Socket.do_not_reverse_lookup = true
-
- @connections = {}
- @requests = Hash.new 0
- @proxy_uri =
- case proxy
- when :no_proxy then nil
- when nil then get_proxy_from_env
- when URI::HTTP then proxy
- else URI.parse(proxy)
- end
- @user_agent = user_agent
- end
-
- ##
- # Given a name and requirement, downloads this gem into cache and returns the
- # filename. Returns nil if the gem cannot be located.
- #--
- # Should probably be integrated with #download below, but that will be a
- # larger, more emcompassing effort. -erikh
-
- def download_to_cache dependency
- found = Gem::SpecFetcher.fetcher.fetch dependency, true, true,
- dependency.prerelease?
-
- return if found.empty?
-
- spec, source_uri = found.sort_by { |(s,_)| s.version }.last
-
- download spec, source_uri
- end
-
- ##
- # Moves the gem +spec+ from +source_uri+ to the cache dir unless it is
- # already there. If the source_uri is local the gem cache dir copy is
- # always replaced.
-
- def download(spec, source_uri, install_dir = Gem.dir)
- Gem.ensure_gem_subdirectories(install_dir) rescue nil
-
- if File.writable?(install_dir)
- cache_dir = File.join install_dir, "cache"
- else
- cache_dir = File.join Gem.user_dir, "cache"
- end
-
- gem_file_name = File.basename spec.cache_file
- local_gem_path = File.join cache_dir, gem_file_name
-
- FileUtils.mkdir_p cache_dir rescue nil unless File.exist? cache_dir
-
- # Always escape URI's to deal with potential spaces and such
- unless URI::Generic === source_uri
- source_uri = URI.parse(URI.const_defined?(:DEFAULT_PARSER) ?
- URI::DEFAULT_PARSER.escape(source_uri.to_s) :
- URI.escape(source_uri.to_s))
- end
-
- scheme = source_uri.scheme
-
- # URI.parse gets confused by MS Windows paths with forward slashes.
- scheme = nil if scheme =~ /^[a-z]$/i
-
- case scheme
- when 'http', 'https' then
- unless File.exist? local_gem_path then
- begin
- say "Downloading gem #{gem_file_name}" if
- Gem.configuration.really_verbose
-
- remote_gem_path = source_uri + "gems/#{gem_file_name}"
-
- gem = self.fetch_path remote_gem_path
- rescue Gem::RemoteFetcher::FetchError
- raise if spec.original_platform == spec.platform
-
- alternate_name = "#{spec.original_name}.gem"
-
- say "Failed, downloading gem #{alternate_name}" if
- Gem.configuration.really_verbose
-
- remote_gem_path = source_uri + "gems/#{alternate_name}"
-
- gem = self.fetch_path remote_gem_path
- end
-
- File.open local_gem_path, 'wb' do |fp|
- fp.write gem
- end
- end
- when 'file' then
- begin
- path = source_uri.path
- path = File.dirname(path) if File.extname(path) == '.gem'
-
- remote_gem_path = correct_for_windows_path(File.join(path, 'gems', gem_file_name))
-
- FileUtils.cp(remote_gem_path, local_gem_path)
- rescue Errno::EACCES
- local_gem_path = source_uri.to_s
- end
-
- say "Using local gem #{local_gem_path}" if
- Gem.configuration.really_verbose
- when nil then # TODO test for local overriding cache
- source_path = if Gem.win_platform? && source_uri.scheme &&
- !source_uri.path.include?(':') then
- "#{source_uri.scheme}:#{source_uri.path}"
- else
- source_uri.path
- end
-
- source_path = unescape source_path
-
- begin
- FileUtils.cp source_path, local_gem_path unless
- File.expand_path(source_path) == File.expand_path(local_gem_path)
- rescue Errno::EACCES
- local_gem_path = source_uri.to_s
- end
-
- say "Using local gem #{local_gem_path}" if
- Gem.configuration.really_verbose
- else
- raise Gem::InstallError, "unsupported URI scheme #{source_uri.scheme}"
- end
-
- local_gem_path
- end
-
- ##
- # File Fetcher. Dispatched by +fetch_path+. Use it instead.
-
- def fetch_file uri, *_
- Gem.read_binary correct_for_windows_path uri.path
- end
-
- ##
- # HTTP Fetcher. Dispatched by +fetch_path+. Use it instead.
-
- def fetch_http uri, last_modified = nil, head = false, depth = 0
- fetch_type = head ? Net::HTTP::Head : Net::HTTP::Get
- response = request uri, fetch_type, last_modified
-
- case response
- when Net::HTTPOK, Net::HTTPNotModified then
- head ? response : response.body
- when Net::HTTPMovedPermanently, Net::HTTPFound, Net::HTTPSeeOther,
- Net::HTTPTemporaryRedirect then
- raise FetchError.new('too many redirects', uri) if depth > 10
-
- location = URI.parse response['Location']
-
- if https?(uri) && !https?(location)
- raise FetchError.new("redirecting to non-https resource: #{location}", uri)
- end
-
- fetch_http(location, last_modified, head, depth + 1)
- else
- raise FetchError.new("bad response #{response.message} #{response.code}", uri)
- end
- end
-
- alias :fetch_https :fetch_http
-
- ##
- # Downloads +uri+ and returns it as a String.
-
- def fetch_path(uri, mtime = nil, head = false)
- uri = URI.parse uri unless URI::Generic === uri
-
- raise ArgumentError, "bad uri: #{uri}" unless uri
- raise ArgumentError, "uri scheme is invalid: #{uri.scheme.inspect}" unless
- uri.scheme
-
- data = send "fetch_#{uri.scheme}", uri, mtime, head
- data = Gem.gunzip data if data and not head and uri.to_s =~ /gz$/
- data
- rescue FetchError
- raise
- rescue Timeout::Error
- raise FetchError.new('timed out', uri.to_s)
- rescue IOError, SocketError, SystemCallError => e
- raise FetchError.new("#{e.class}: #{e}", uri.to_s)
- end
-
- ##
- # Returns the size of +uri+ in bytes.
-
- def fetch_size(uri) # TODO: phase this out
- response = fetch_path(uri, nil, true)
-
- response['content-length'].to_i
- end
-
- def escape(str)
- return unless str
- @uri_parser ||= uri_escaper
- @uri_parser.escape str
- end
-
- def unescape(str)
- return unless str
- @uri_parser ||= uri_escaper
- @uri_parser.unescape str
- end
-
- def uri_escaper
- URI::Parser.new
- rescue NameError
- URI
- end
-
- ##
- # Returns an HTTP proxy URI if one is set in the environment variables.
-
- def get_proxy_from_env
- env_proxy = ENV['http_proxy'] || ENV['HTTP_PROXY']
-
- return nil if env_proxy.nil? or env_proxy.empty?
-
- uri = URI.parse(normalize_uri(env_proxy))
-
- if uri and uri.user.nil? and uri.password.nil? then
- # Probably we have http_proxy_* variables?
- uri.user = escape(ENV['http_proxy_user'] || ENV['HTTP_PROXY_USER'])
- uri.password = escape(ENV['http_proxy_pass'] || ENV['HTTP_PROXY_PASS'])
- end
-
- uri
- end
-
- ##
- # Normalize the URI by adding "http://" if it is missing.
-
- def normalize_uri(uri)
- (uri =~ /^(https?|ftp|file):/) ? uri : "http://#{uri}"
- end
-
- ##
- # Creates or an HTTP connection based on +uri+, or retrieves an existing
- # connection, using a proxy if needed.
-
- def connection_for(uri)
- net_http_args = [uri.host, uri.port]
-
- if @proxy_uri then
- net_http_args += [
- @proxy_uri.host,
- @proxy_uri.port,
- @proxy_uri.user,
- @proxy_uri.password
- ]
- end
-
- connection_id = [Thread.current.object_id, *net_http_args].join ':'
- @connections[connection_id] ||= Net::HTTP.new(*net_http_args)
- connection = @connections[connection_id]
-
- if https?(uri) and !connection.started? then
- configure_connection_for_https(connection)
- end
-
- connection.start unless connection.started?
-
- connection
- rescue OpenSSL::SSL::SSLError, Errno::EHOSTDOWN => e
- raise FetchError.new(e.message, uri)
- end
-
- def configure_connection_for_https(connection)
- require 'net/https'
-
- connection.use_ssl = true
- connection.verify_mode =
- Gem.configuration.ssl_verify_mode || OpenSSL::SSL::VERIFY_PEER
-
- store = OpenSSL::X509::Store.new
-
- if Gem.configuration.ssl_ca_cert
- if File.directory? Gem.configuration.ssl_ca_cert
- store.add_path Gem.configuration.ssl_ca_cert
- else
- store.add_file Gem.configuration.ssl_ca_cert
- end
- else
- store.set_default_paths
- add_rubygems_trusted_certs(store)
- end
-
- connection.cert_store = store
- end
-
- def add_rubygems_trusted_certs(store)
- Dir.glob(BuiltinSSLCerts).each do |ssl_cert_file|
- store.add_file ssl_cert_file
- end
- end
-
- def correct_for_windows_path(path)
- if path[0].chr == '/' && path[1].chr =~ /[a-z]/i && path[2].chr == ':'
- path = path[1..-1]
- else
- path
- end
- end
-
- ##
- # Read the data from the (source based) URI, but if it is a file:// URI,
- # read from the filesystem instead.
-
- def open_uri_or_path(uri, last_modified = nil, head = false, depth = 0)
- raise "NO: Use fetch_path instead"
- # TODO: deprecate for fetch_path
- end
-
- ##
- # Performs a Net::HTTP request of type +request_class+ on +uri+ returning
- # a Net::HTTP response object. request maintains a table of persistent
- # connections to reduce connect overhead.
-
- def request(uri, request_class, last_modified = nil)
- request = request_class.new uri.request_uri
-
- unless uri.nil? || uri.user.nil? || uri.user.empty? then
- request.basic_auth uri.user, uri.password
- end
-
- request.add_field 'User-Agent', @user_agent
- request.add_field 'Connection', 'keep-alive'
- request.add_field 'Keep-Alive', '30'
-
- if last_modified then
- last_modified = last_modified.utc
- request.add_field 'If-Modified-Since', last_modified.rfc2822
- end
-
- yield request if block_given?
-
- connection = connection_for uri
-
- retried = false
- bad_response = false
-
- begin
- @requests[connection.object_id] += 1
-
- say "#{request.method} #{uri}" if
- Gem.configuration.really_verbose
-
- file_name = File.basename(uri.path)
- # perform download progress reporter only for gems
- if request.response_body_permitted? && file_name =~ /\.gem$/
- reporter = ui.download_reporter
- response = connection.request(request) do |incomplete_response|
- if Net::HTTPOK === incomplete_response
- reporter.fetch(file_name, incomplete_response.content_length)
- downloaded = 0
- data = ''
-
- incomplete_response.read_body do |segment|
- data << segment
- downloaded += segment.length
- reporter.update(downloaded)
- end
- reporter.done
- if incomplete_response.respond_to? :body=
- incomplete_response.body = data
- else
- incomplete_response.instance_variable_set(:@body, data)
- end
- end
- end
- else
- response = connection.request request
- end
-
- say "#{response.code} #{response.message}" if
- Gem.configuration.really_verbose
-
- rescue Net::HTTPBadResponse
- say "bad response" if Gem.configuration.really_verbose
-
- reset connection
-
- raise FetchError.new('too many bad responses', uri) if bad_response
-
- bad_response = true
- retry
- # HACK work around EOFError bug in Net::HTTP
- # NOTE Errno::ECONNABORTED raised a lot on Windows, and make impossible
- # to install gems.
- rescue EOFError, Timeout::Error,
- Errno::ECONNABORTED, Errno::ECONNRESET, Errno::EPIPE
-
- requests = @requests[connection.object_id]
- say "connection reset after #{requests} requests, retrying" if
- Gem.configuration.really_verbose
-
- raise FetchError.new('too many connection resets', uri) if retried
-
- reset connection
-
- retried = true
- retry
- end
-
- response
- end
-
- ##
- # Resets HTTP connection +connection+.
-
- def reset(connection)
- @requests.delete connection.object_id
-
- connection.finish
- connection.start
- end
-
- def user_agent
- ua = "RubyGems/#{Gem::VERSION} #{Gem::Platform.local}"
-
- ruby_version = RUBY_VERSION
- ruby_version += 'dev' if RUBY_PATCHLEVEL == -1
-
- ua << " Ruby/#{ruby_version} (#{RUBY_RELEASE_DATE}"
- if RUBY_PATCHLEVEL >= 0 then
- ua << " patchlevel #{RUBY_PATCHLEVEL}"
- elsif defined?(RUBY_REVISION) then
- ua << " revision #{RUBY_REVISION}"
- end
- ua << ")"
-
- ua << " #{RUBY_ENGINE}" if defined?(RUBY_ENGINE) and RUBY_ENGINE != 'ruby'
-
- ua
- end
-
- def https?(uri)
- uri.scheme.downcase == 'https'
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/require_paths_builder.rb b/ruby_1_9_3/lib/rubygems/require_paths_builder.rb
deleted file mode 100644
index 23e974639f..0000000000
--- a/ruby_1_9_3/lib/rubygems/require_paths_builder.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-require 'rubygems'
-
-# TODO: remove after 1.9.1 dropped
-module Gem::RequirePathsBuilder
- def write_require_paths_file_if_needed(spec = @spec, gem_home = @gem_home)
- return if spec.require_paths == ["lib"] &&
- (spec.bindir.nil? || spec.bindir == "bin")
- file_name = File.join(gem_home, 'gems', "#{@spec.full_name}", ".require_paths")
- file_name.untaint
- File.open(file_name, "w") do |file|
- spec.require_paths.each do |path|
- file.puts path
- end
- file.puts spec.bindir if spec.bindir
- end
- end
-end if Gem::QUICKLOADER_SUCKAGE
-
diff --git a/ruby_1_9_3/lib/rubygems/requirement.rb b/ruby_1_9_3/lib/rubygems/requirement.rb
deleted file mode 100644
index 7abff01c39..0000000000
--- a/ruby_1_9_3/lib/rubygems/requirement.rb
+++ /dev/null
@@ -1,204 +0,0 @@
-require "rubygems/version"
-
-##
-# A Requirement is a set of one or more version restrictions. It supports a
-# few (<tt>=, !=, >, <, >=, <=, ~></tt>) different restriction operators.
-
-# REFACTOR: The fact that a requirement is singular or plural is kind of
-# awkward. Is Requirement the right name for this? Or should it be one
-# [op, number] pair, and we call the list of requirements something else?
-# Since a Requirement is held by a Dependency, maybe this should be made
-# singular and the list aspect should be pulled up into Dependency?
-
-require "rubygems/version"
-require "rubygems/deprecate"
-
-class Gem::Requirement
- include Comparable
-
- OPS = { #:nodoc:
- "=" => lambda { |v, r| v == r },
- "!=" => lambda { |v, r| v != r },
- ">" => lambda { |v, r| v > r },
- "<" => lambda { |v, r| v < r },
- ">=" => lambda { |v, r| v >= r },
- "<=" => lambda { |v, r| v <= r },
- "~>" => lambda { |v, r| v >= r && v.release < r.bump }
- }
-
- quoted = OPS.keys.map { |k| Regexp.quote k }.join "|"
- PATTERN = /\A\s*(#{quoted})?\s*(#{Gem::Version::VERSION_PATTERN})\s*\z/
-
- ##
- # Factory method to create a Gem::Requirement object. Input may be
- # a Version, a String, or nil. Intended to simplify client code.
- #
- # If the input is "weird", the default version requirement is
- # returned.
-
- def self.create input
- case input
- when Gem::Requirement then
- input
- when Gem::Version, Array then
- new input
- else
- if input.respond_to? :to_str then
- new [input.to_str]
- else
- default
- end
- end
- end
-
- ##
- # A default "version requirement" can surely _only_ be '>= 0'.
- #--
- # This comment once said:
- #
- # "A default "version requirement" can surely _only_ be '> 0'."
-
- def self.default
- new '>= 0'
- end
-
- ##
- # Parse +obj+, returning an <tt>[op, version]</tt> pair. +obj+ can
- # be a String or a Gem::Version.
- #
- # If +obj+ is a String, it can be either a full requirement
- # specification, like <tt>">= 1.2"</tt>, or a simple version number,
- # like <tt>"1.2"</tt>.
- #
- # parse("> 1.0") # => [">", "1.0"]
- # parse("1.0") # => ["=", "1.0"]
- # parse(Gem::Version.new("1.0")) # => ["=, "1.0"]
-
- def self.parse obj
- return ["=", obj] if Gem::Version === obj
-
- unless PATTERN =~ obj.to_s
- raise ArgumentError, "Illformed requirement [#{obj.inspect}]"
- end
-
- [$1 || "=", Gem::Version.new($2)]
- end
-
- ##
- # An array of requirement pairs. The first element of the pair is
- # the op, and the second is the Gem::Version.
-
- attr_reader :requirements #:nodoc:
-
- ##
- # Constructs a requirement from +requirements+. Requirements can be
- # Strings, Gem::Versions, or Arrays of those. +nil+ and duplicate
- # requirements are ignored. An empty set of +requirements+ is the
- # same as <tt>">= 0"</tt>.
-
- def initialize *requirements
- requirements = requirements.flatten
- requirements.compact!
- requirements.uniq!
-
- requirements << ">= 0" if requirements.empty?
- @none = (requirements == ">= 0")
- @requirements = requirements.map! { |r| self.class.parse r }
- end
-
- def none?
- @none ||= (to_s == ">= 0")
- end
-
- def as_list # :nodoc:
- requirements.map { |op, version| "#{op} #{version}" }.sort
- end
-
- def hash # :nodoc:
- requirements.hash
- end
-
- def marshal_dump # :nodoc:
- fix_syck_default_key_in_requirements
-
- [@requirements]
- end
-
- def marshal_load array # :nodoc:
- @requirements = array[0]
-
- fix_syck_default_key_in_requirements
- end
-
- def yaml_initialize(tag, vals) # :nodoc:
- vals.each do |ivar, val|
- instance_variable_set "@#{ivar}", val
- end
-
- fix_syck_default_key_in_requirements
- end
-
- def init_with coder # :nodoc:
- yaml_initialize coder.tag, coder.map
- end
-
- def prerelease?
- requirements.any? { |r| r.last.prerelease? }
- end
-
- def pretty_print q # :nodoc:
- q.group 1, 'Gem::Requirement.new(', ')' do
- q.pp as_list
- end
- end
-
- ##
- # True if +version+ satisfies this Requirement.
-
- def satisfied_by? version
- # #28965: syck has a bug with unquoted '=' YAML.loading as YAML::DefaultKey
- requirements.all? { |op, rv| (OPS[op] || OPS["="]).call version, rv }
- end
-
- alias :=== :satisfied_by?
- alias :=~ :satisfied_by?
-
- ##
- # True if the requirement will not always match the latest version.
-
- def specific?
- return true if @requirements.length > 1 # GIGO, > 1, > 2 is silly
-
- not %w[> >=].include? @requirements.first.first # grab the operator
- end
-
- def to_s # :nodoc:
- as_list.join ", "
- end
-
- def <=> other # :nodoc:
- to_s <=> other.to_s
- end
-
- private
-
- def fix_syck_default_key_in_requirements
- Gem.load_yaml
-
- # Fixup the Syck DefaultKey bug
- @requirements.each do |r|
- if r[0].kind_of? Gem::SyckDefaultKey
- r[0] = "="
- end
- end
- end
-end
-
-# :stopdoc:
-# Gem::Version::Requirement is used in a lot of old YAML specs. It's aliased
-# here for backwards compatibility. I'd like to remove this, maybe in RubyGems
-# 2.0.
-
-::Gem::Version::Requirement = ::Gem::Requirement
-# :startdoc:
-
diff --git a/ruby_1_9_3/lib/rubygems/security.rb b/ruby_1_9_3/lib/rubygems/security.rb
deleted file mode 100644
index f51da65b4b..0000000000
--- a/ruby_1_9_3/lib/rubygems/security.rb
+++ /dev/null
@@ -1,826 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-require 'rubygems/exceptions'
-require 'rubygems/gem_openssl'
-require 'fileutils'
-
-#
-# = Signed Gems README
-#
-# == Table of Contents
-# * Overview
-# * Walkthrough
-# * Command-Line Options
-# * OpenSSL Reference
-# * Bugs/TODO
-# * About the Author
-#
-# == Overview
-#
-# Gem::Security implements cryptographic signatures in RubyGems. The section
-# below is a step-by-step guide to using signed gems and generating your own.
-#
-# == Walkthrough
-#
-# In order to start signing your gems, you'll need to build a private key and
-# a self-signed certificate. Here's how:
-#
-# # build a private key and certificate for gemmaster@example.com
-# $ gem cert --build gemmaster@example.com
-#
-# This could take anywhere from 5 seconds to 10 minutes, depending on the
-# speed of your computer (public key algorithms aren't exactly the speediest
-# crypto algorithms in the world). When it's finished, you'll see the files
-# "gem-private_key.pem" and "gem-public_cert.pem" in the current directory.
-#
-# First things first: take the "gem-private_key.pem" file and move it
-# somewhere private, preferably a directory only you have access to, a floppy
-# (yuck!), a CD-ROM, or something comparably secure. Keep your private key
-# hidden; if it's compromised, someone can sign packages as you (note: PKI has
-# ways of mitigating the risk of stolen keys; more on that later).
-#
-# Now, let's sign an existing gem. I'll be using my Imlib2-Ruby bindings, but
-# you can use whatever gem you'd like. Open up your existing gemspec file and
-# add the following lines:
-#
-# # signing key and certificate chain
-# s.signing_key = '/mnt/floppy/gem-private_key.pem'
-# s.cert_chain = ['gem-public_cert.pem']
-#
-# (Be sure to replace "/mnt/floppy" with the ultra-secret path to your private
-# key).
-#
-# After that, go ahead and build your gem as usual. Congratulations, you've
-# just built your first signed gem! If you peek inside your gem file, you'll
-# see a couple of new files have been added:
-#
-# $ tar tf tar tf Imlib2-Ruby-0.5.0.gem
-# data.tar.gz
-# data.tar.gz.sig
-# metadata.gz
-# metadata.gz.sig
-#
-# Now let's verify the signature. Go ahead and install the gem, but add the
-# following options: "-P HighSecurity", like this:
-#
-# # install the gem with using the security policy "HighSecurity"
-# $ sudo gem install Imlib2-Ruby-0.5.0.gem -P HighSecurity
-#
-# The -P option sets your security policy -- we'll talk about that in just a
-# minute. Eh, what's this?
-#
-# Attempting local installation of 'Imlib2-Ruby-0.5.0.gem'
-# ERROR: Error installing gem Imlib2-Ruby-0.5.0.gem[.gem]: Couldn't
-# verify data signature: Untrusted Signing Chain Root: cert =
-# '/CN=gemmaster/DC=example/DC=com', error = 'path
-# "/root/.rubygems/trust/cert-15dbb43a6edf6a70a85d4e784e2e45312cff7030.pem"
-# does not exist'
-#
-# The culprit here is the security policy. RubyGems has several different
-# security policies. Let's take a short break and go over the security
-# policies. Here's a list of the available security policies, and a brief
-# description of each one:
-#
-# * NoSecurity - Well, no security at all. Signed packages are treated like
-# unsigned packages.
-# * LowSecurity - Pretty much no security. If a package is signed then
-# RubyGems will make sure the signature matches the signing
-# certificate, and that the signing certificate hasn't expired, but
-# that's it. A malicious user could easily circumvent this kind of
-# security.
-# * MediumSecurity - Better than LowSecurity and NoSecurity, but still
-# fallible. Package contents are verified against the signing
-# certificate, and the signing certificate is checked for validity,
-# and checked against the rest of the certificate chain (if you don't
-# know what a certificate chain is, stay tuned, we'll get to that).
-# The biggest improvement over LowSecurity is that MediumSecurity
-# won't install packages that are signed by untrusted sources.
-# Unfortunately, MediumSecurity still isn't totally secure -- a
-# malicious user can still unpack the gem, strip the signatures, and
-# distribute the gem unsigned.
-# * HighSecurity - Here's the bugger that got us into this mess.
-# The HighSecurity policy is identical to the MediumSecurity policy,
-# except that it does not allow unsigned gems. A malicious user
-# doesn't have a whole lot of options here; he can't modify the
-# package contents without invalidating the signature, and he can't
-# modify or remove signature or the signing certificate chain, or
-# RubyGems will simply refuse to install the package. Oh well, maybe
-# he'll have better luck causing problems for CPAN users instead :).
-#
-# So, the reason RubyGems refused to install our shiny new signed gem was
-# because it was from an untrusted source. Well, my code is infallible
-# (hah!), so I'm going to add myself as a trusted source.
-#
-# Here's how:
-#
-# # add trusted certificate
-# gem cert --add gem-public_cert.pem
-#
-# I've added my public certificate as a trusted source. Now I can install
-# packages signed my private key without any hassle. Let's try the install
-# command above again:
-#
-# # install the gem with using the HighSecurity policy (and this time
-# # without any shenanigans)
-# $ sudo gem install Imlib2-Ruby-0.5.0.gem -P HighSecurity
-#
-# This time RubyGems should accept your signed package and begin installing.
-# While you're waiting for RubyGems to work it's magic, have a look at some of
-# the other security commands:
-#
-# Usage: gem cert [options]
-#
-# Options:
-# -a, --add CERT Add a trusted certificate.
-# -l, --list List trusted certificates.
-# -r, --remove STRING Remove trusted certificates containing STRING.
-# -b, --build EMAIL_ADDR Build private key and self-signed certificate
-# for EMAIL_ADDR.
-# -C, --certificate CERT Certificate for --sign command.
-# -K, --private-key KEY Private key for --sign command.
-# -s, --sign NEWCERT Sign a certificate with my key and certificate.
-#
-# (By the way, you can pull up this list any time you'd like by typing "gem
-# cert --help")
-#
-# Hmm. We've already covered the "--build" option, and the "--add", "--list",
-# and "--remove" commands seem fairly straightforward; they allow you to add,
-# list, and remove the certificates in your trusted certificate list. But
-# what's with this "--sign" option?
-#
-# To answer that question, let's take a look at "certificate chains", a
-# concept I mentioned earlier. There are a couple of problems with
-# self-signed certificates: first of all, self-signed certificates don't offer
-# a whole lot of security. Sure, the certificate says Yukihiro Matsumoto, but
-# how do I know it was actually generated and signed by matz himself unless he
-# gave me the certificate in person?
-#
-# The second problem is scalability. Sure, if there are 50 gem authors, then
-# I have 50 trusted certificates, no problem. What if there are 500 gem
-# authors? 1000? Having to constantly add new trusted certificates is a
-# pain, and it actually makes the trust system less secure by encouraging
-# RubyGems users to blindly trust new certificates.
-#
-# Here's where certificate chains come in. A certificate chain establishes an
-# arbitrarily long chain of trust between an issuing certificate and a child
-# certificate. So instead of trusting certificates on a per-developer basis,
-# we use the PKI concept of certificate chains to build a logical hierarchy of
-# trust. Here's a hypothetical example of a trust hierarchy based (roughly)
-# on geography:
-#
-#
-# --------------------------
-# | rubygems@rubyforge.org |
-# --------------------------
-# |
-# -----------------------------------
-# | |
-# ---------------------------- -----------------------------
-# | seattle.rb@zenspider.com | | dcrubyists@richkilmer.com |
-# ---------------------------- -----------------------------
-# | | | |
-# --------------- ---------------- ----------- --------------
-# | alf@seattle | | bob@portland | | pabs@dc | | tomcope@dc |
-# --------------- ---------------- ----------- --------------
-#
-#
-# Now, rather than having 4 trusted certificates (one for alf@seattle,
-# bob@portland, pabs@dc, and tomecope@dc), a user could actually get by with 1
-# certificate: the "rubygems@rubyforge.org" certificate. Here's how it works:
-#
-# I install "Alf2000-Ruby-0.1.0.gem", a package signed by "alf@seattle". I've
-# never heard of "alf@seattle", but his certificate has a valid signature from
-# the "seattle.rb@zenspider.com" certificate, which in turn has a valid
-# signature from the "rubygems@rubyforge.org" certificate. Voila! At this
-# point, it's much more reasonable for me to trust a package signed by
-# "alf@seattle", because I can establish a chain to "rubygems@rubyforge.org",
-# which I do trust.
-#
-# And the "--sign" option allows all this to happen. A developer creates
-# their build certificate with the "--build" option, then has their
-# certificate signed by taking it with them to their next regional Ruby meetup
-# (in our hypothetical example), and it's signed there by the person holding
-# the regional RubyGems signing certificate, which is signed at the next
-# RubyConf by the holder of the top-level RubyGems certificate. At each point
-# the issuer runs the same command:
-#
-# # sign a certificate with the specified key and certificate
-# # (note that this modifies client_cert.pem!)
-# $ gem cert -K /mnt/floppy/issuer-priv_key.pem -C issuer-pub_cert.pem
-# --sign client_cert.pem
-#
-# Then the holder of issued certificate (in this case, our buddy
-# "alf@seattle"), can start using this signed certificate to sign RubyGems.
-# By the way, in order to let everyone else know about his new fancy signed
-# certificate, "alf@seattle" would change his gemspec file to look like this:
-#
-# # signing key (still kept in an undisclosed location!)
-# s.signing_key = '/mnt/floppy/alf-private_key.pem'
-#
-# # certificate chain (includes the issuer certificate now too)
-# s.cert_chain = ['/home/alf/doc/seattlerb-public_cert.pem',
-# '/home/alf/doc/alf_at_seattle-public_cert.pem']
-#
-# Obviously, this RubyGems trust infrastructure doesn't exist yet. Also, in
-# the "real world" issuers actually generate the child certificate from a
-# certificate request, rather than sign an existing certificate. And our
-# hypothetical infrastructure is missing a certificate revocation system.
-# These are that can be fixed in the future...
-#
-# I'm sure your new signed gem has finished installing by now (unless you're
-# installing rails and all it's dependencies, that is ;D). At this point you
-# should know how to do all of these new and interesting things:
-#
-# * build a gem signing key and certificate
-# * modify your existing gems to support signing
-# * adjust your security policy
-# * modify your trusted certificate list
-# * sign a certificate
-#
-# If you've got any questions, feel free to contact me at the email address
-# below. The next couple of sections
-#
-#
-# == Command-Line Options
-#
-# Here's a brief summary of the certificate-related command line options:
-#
-# gem install
-# -P, --trust-policy POLICY Specify gem trust policy.
-#
-# gem cert
-# -a, --add CERT Add a trusted certificate.
-# -l, --list List trusted certificates.
-# -r, --remove STRING Remove trusted certificates containing
-# STRING.
-# -b, --build EMAIL_ADDR Build private key and self-signed
-# certificate for EMAIL_ADDR.
-# -C, --certificate CERT Certificate for --sign command.
-# -K, --private-key KEY Private key for --sign command.
-# -s, --sign NEWCERT Sign a certificate with my key and
-# certificate.
-#
-# A more detailed description of each options is available in the walkthrough
-# above.
-#
-# == Manually verifying signatures
-#
-# In case you don't trust RubyGems you can verify gem signatures manually:
-#
-# 1. Fetch and unpack the gem
-#
-# gem fetch some_signed_gem
-# tar -xf some_signed_gem-1.0.gem
-#
-# 2. Grab the public key from the gemspec
-#
-# gem spec some_signed_gem-1.0.gem cert_chain | \
-# ruby -pe 'sub(/^ +/, "")' > public_key.crt
-#
-# 3. Generate a SHA1 hash of the data.tar.gz
-#
-# openssl dgst -sha1 < data.tar.gz > my.hash
-#
-# 4. Verify the signature
-#
-# openssl rsautl -verify -inkey public_key.crt -certin \
-# -in data.tar.gz.sig > verified.hash
-#
-# 5. Compare your hash to the verified hash
-#
-# diff -s verified.hash my.hash
-#
-# 6. Repeat 5 and 6 with metadata.gz
-#
-# == OpenSSL Reference
-#
-# The .pem files generated by --build and --sign are just basic OpenSSL PEM
-# files. Here's a couple of useful commands for manipulating them:
-#
-# # convert a PEM format X509 certificate into DER format:
-# # (note: Windows .cer files are X509 certificates in DER format)
-# $ openssl x509 -in input.pem -outform der -out output.der
-#
-# # print out the certificate in a human-readable format:
-# $ openssl x509 -in input.pem -noout -text
-#
-# And you can do the same thing with the private key file as well:
-#
-# # convert a PEM format RSA key into DER format:
-# $ openssl rsa -in input_key.pem -outform der -out output_key.der
-#
-# # print out the key in a human readable format:
-# $ openssl rsa -in input_key.pem -noout -text
-#
-# == Bugs/TODO
-#
-# * There's no way to define a system-wide trust list.
-# * custom security policies (from a YAML file, etc)
-# * Simple method to generate a signed certificate request
-# * Support for OCSP, SCVP, CRLs, or some other form of cert
-# status check (list is in order of preference)
-# * Support for encrypted private keys
-# * Some sort of semi-formal trust hierarchy (see long-winded explanation
-# above)
-# * Path discovery (for gem certificate chains that don't have a self-signed
-# root) -- by the way, since we don't have this, THE ROOT OF THE CERTIFICATE
-# CHAIN MUST BE SELF SIGNED if Policy#verify_root is true (and it is for the
-# MediumSecurity and HighSecurity policies)
-# * Better explanation of X509 naming (ie, we don't have to use email
-# addresses)
-# * Possible alternate signing mechanisms (eg, via PGP). this could be done
-# pretty easily by adding a :signing_type attribute to the gemspec, then add
-# the necessary support in other places
-# * Honor AIA field (see note about OCSP above)
-# * Maybe honor restriction extensions?
-# * Might be better to store the certificate chain as a PKCS#7 or PKCS#12
-# file, instead of an array embedded in the metadata. ideas?
-# * Possibly embed signature and key algorithms into metadata (right now
-# they're assumed to be the same as what's set in Gem::Security::OPT)
-#
-# == About the Author
-#
-# Paul Duncan <pabs@pablotron.org>
-# http://pablotron.org/
-
-module Gem::Security
-
- ##
- # Gem::Security default exception type
-
- class Exception < Gem::Exception; end
-
- ##
- # Default options for most of the methods below
-
- OPT = {
- # private key options
- :key_algo => Gem::SSL::PKEY_RSA,
- :key_size => 2048,
-
- # public cert options
- :cert_age => 365 * 24 * 3600, # 1 year
- :dgst_algo => Gem::SSL::DIGEST_SHA1,
-
- # x509 certificate extensions
- :cert_exts => {
- 'basicConstraints' => 'CA:FALSE',
- 'subjectKeyIdentifier' => 'hash',
- 'keyUsage' => 'keyEncipherment,dataEncipherment,digitalSignature',
- },
-
- # save the key and cert to a file in build_self_signed_cert()?
- :save_key => true,
- :save_cert => true,
-
- # if you define either of these, then they'll be used instead of
- # the output_fmt macro below
- :save_key_path => nil,
- :save_cert_path => nil,
-
- # output name format for self-signed certs
- :output_fmt => 'gem-%s.pem',
- :munge_re => Regexp.new(/[^a-z0-9_.-]+/),
-
- # output directory for trusted certificate checksums
- :trust_dir => File.join(Gem.user_home, '.gem', 'trust'),
-
- # default permissions for trust directory and certs
- :perms => {
- :trust_dir => 0700,
- :trusted_cert => 0600,
- :signing_cert => 0600,
- :signing_key => 0600,
- },
- }
-
- ##
- # A Gem::Security::Policy object encapsulates the settings for verifying
- # signed gem files. This is the base class. You can either declare an
- # instance of this or use one of the preset security policies below.
-
- class Policy
- attr_accessor :verify_data, :verify_signer, :verify_chain,
- :verify_root, :only_trusted, :only_signed
-
- #
- # Create a new Gem::Security::Policy object with the given mode and
- # options.
- #
- def initialize(policy = {}, opt = {})
- # set options
- @opt = Gem::Security::OPT.merge(opt)
-
- # build policy
- policy.each_pair do |key, val|
- case key
- when :verify_data then @verify_data = val
- when :verify_signer then @verify_signer = val
- when :verify_chain then @verify_chain = val
- when :verify_root then @verify_root = val
- when :only_trusted then @only_trusted = val
- when :only_signed then @only_signed = val
- end
- end
- end
-
- #
- # Get the path to the file for this cert.
- #
- def self.trusted_cert_path(cert, opt = {})
- opt = Gem::Security::OPT.merge(opt)
-
- # get digest algorithm, calculate checksum of root.subject
- algo = opt[:dgst_algo]
- dgst = algo.hexdigest(cert.subject.to_s)
-
- # build path to trusted cert file
- name = "cert-#{dgst}.pem"
-
- # join and return path components
- File::join(opt[:trust_dir], name)
- end
-
- #
- # Verify that the gem data with the given signature and signing chain
- # matched this security policy at the specified time.
- #
- def verify_gem(signature, data, chain, time = Time.now)
- Gem.ensure_ssl_available
- cert_class = OpenSSL::X509::Certificate
- exc = Gem::Security::Exception
- chain ||= []
-
- chain = chain.map{ |str| cert_class.new(str) }
- signer, ch_len = chain[-1], chain.size
-
- # make sure signature is valid
- if @verify_data
- # get digest algorithm (TODO: this should be configurable)
- dgst = @opt[:dgst_algo]
-
- # verify the data signature (this is the most important part, so don't
- # screw it up :D)
- v = signer.public_key.verify(dgst.new, signature, data)
- raise exc, "Invalid Gem Signature" unless v
-
- # make sure the signer is valid
- if @verify_signer
- # make sure the signing cert is valid right now
- v = signer.check_validity(nil, time)
- raise exc, "Invalid Signature: #{v[:desc]}" unless v[:is_valid]
- end
- end
-
- # make sure the certificate chain is valid
- if @verify_chain
- # iterate down over the chain and verify each certificate against it's
- # issuer
- (ch_len - 1).downto(1) do |i|
- issuer, cert = chain[i - 1, 2]
- v = cert.check_validity(issuer, time)
- raise exc, "%s: cert = '%s', error = '%s'" % [
- 'Invalid Signing Chain', cert.subject, v[:desc]
- ] unless v[:is_valid]
- end
-
- # verify root of chain
- if @verify_root
- # make sure root is self-signed
- root = chain[0]
- raise exc, "%s: %s (subject = '%s', issuer = '%s')" % [
- 'Invalid Signing Chain Root',
- 'Subject does not match Issuer for Gem Signing Chain',
- root.subject.to_s,
- root.issuer.to_s,
- ] unless root.issuer.to_s == root.subject.to_s
-
- # make sure root is valid
- v = root.check_validity(root, time)
- raise exc, "%s: cert = '%s', error = '%s'" % [
- 'Invalid Signing Chain Root', root.subject, v[:desc]
- ] unless v[:is_valid]
-
- # verify that the chain root is trusted
- if @only_trusted
- # get digest algorithm, calculate checksum of root.subject
- algo = @opt[:dgst_algo]
- path = Gem::Security::Policy.trusted_cert_path(root, @opt)
-
- # check to make sure trusted path exists
- raise exc, "%s: cert = '%s', error = '%s'" % [
- 'Untrusted Signing Chain Root',
- root.subject.to_s,
- "path \"#{path}\" does not exist",
- ] unless File.exist?(path)
-
- # load calculate digest from saved cert file
- save_cert = OpenSSL::X509::Certificate.new(File.read(path))
- save_dgst = algo.digest(save_cert.public_key.to_s)
-
- # create digest of public key
- pkey_str = root.public_key.to_s
- cert_dgst = algo.digest(pkey_str)
-
- # now compare the two digests, raise exception
- # if they don't match
- raise exc, "%s: %s (saved = '%s', root = '%s')" % [
- 'Invalid Signing Chain Root',
- "Saved checksum doesn't match root checksum",
- save_dgst, cert_dgst,
- ] unless save_dgst == cert_dgst
- end
- end
-
- # return the signing chain
- chain.map { |cert| cert.subject }
- end
- end
- end
-
- ##
- # No security policy: all package signature checks are disabled.
-
- NoSecurity = Policy.new(
- :verify_data => false,
- :verify_signer => false,
- :verify_chain => false,
- :verify_root => false,
- :only_trusted => false,
- :only_signed => false
- )
-
- ##
- # AlmostNo security policy: only verify that the signing certificate is the
- # one that actually signed the data. Make no attempt to verify the signing
- # certificate chain.
- #
- # This policy is basically useless. better than nothing, but can still be
- # easily spoofed, and is not recommended.
-
- AlmostNoSecurity = Policy.new(
- :verify_data => true,
- :verify_signer => false,
- :verify_chain => false,
- :verify_root => false,
- :only_trusted => false,
- :only_signed => false
- )
-
- ##
- # Low security policy: only verify that the signing certificate is actually
- # the gem signer, and that the signing certificate is valid.
- #
- # This policy is better than nothing, but can still be easily spoofed, and
- # is not recommended.
-
- LowSecurity = Policy.new(
- :verify_data => true,
- :verify_signer => true,
- :verify_chain => false,
- :verify_root => false,
- :only_trusted => false,
- :only_signed => false
- )
-
- ##
- # Medium security policy: verify the signing certificate, verify the signing
- # certificate chain all the way to the root certificate, and only trust root
- # certificates that we have explicitly allowed trust for.
- #
- # This security policy is reasonable, but it allows unsigned packages, so a
- # malicious person could simply delete the package signature and pass the
- # gem off as unsigned.
-
- MediumSecurity = Policy.new(
- :verify_data => true,
- :verify_signer => true,
- :verify_chain => true,
- :verify_root => true,
- :only_trusted => true,
- :only_signed => false
- )
-
- ##
- # High security policy: only allow signed gems to be installed, verify the
- # signing certificate, verify the signing certificate chain all the way to
- # the root certificate, and only trust root certificates that we have
- # explicitly allowed trust for.
- #
- # This security policy is significantly more difficult to bypass, and offers
- # a reasonable guarantee that the contents of the gem have not been altered.
-
- HighSecurity = Policy.new(
- :verify_data => true,
- :verify_signer => true,
- :verify_chain => true,
- :verify_root => true,
- :only_trusted => true,
- :only_signed => true
- )
-
- ##
- # Hash of configured security policies
-
- Policies = {
- 'NoSecurity' => NoSecurity,
- 'AlmostNoSecurity' => AlmostNoSecurity,
- 'LowSecurity' => LowSecurity,
- 'MediumSecurity' => MediumSecurity,
- 'HighSecurity' => HighSecurity,
- }
-
- ##
- # Sign the cert cert with @signing_key and @signing_cert, using the digest
- # algorithm opt[:dgst_algo]. Returns the newly signed certificate.
-
- def self.sign_cert(cert, signing_key, signing_cert, opt = {})
- opt = OPT.merge(opt)
-
- cert.issuer = signing_cert.subject
- cert.sign signing_key, opt[:dgst_algo].new
-
- cert
- end
-
- ##
- # Make sure the trust directory exists. If it does exist, make sure it's
- # actually a directory. If not, then create it with the appropriate
- # permissions.
-
- def self.verify_trust_dir(path, perms)
- # if the directory exists, then make sure it is in fact a directory. if
- # it doesn't exist, then create it with the appropriate permissions
- if File.exist?(path)
- # verify that the trust directory is actually a directory
- unless File.directory?(path)
- err = "trust directory #{path} isn't a directory"
- raise Gem::Security::Exception, err
- end
- else
- # trust directory doesn't exist, so create it with permissions
- FileUtils.mkdir_p(path)
- FileUtils.chmod(perms, path)
- end
- end
-
- ##
- # Build a certificate from the given DN and private key.
-
- def self.build_cert(name, key, opt = {})
- Gem.ensure_ssl_available
- opt = OPT.merge opt
-
- cert = OpenSSL::X509::Certificate.new
-
- cert.not_after = Time.now + opt[:cert_age]
- cert.not_before = Time.now
- cert.public_key = key.public_key
- cert.serial = 0
- cert.subject = name
- cert.version = 2
-
- ef = OpenSSL::X509::ExtensionFactory.new nil, cert
-
- cert.extensions = opt[:cert_exts].map do |ext_name, value|
- ef.create_extension ext_name, value
- end
-
- i_key = opt[:issuer_key] || key
- i_cert = opt[:issuer_cert] || cert
-
- cert = sign_cert cert, i_key, i_cert, opt
-
- cert
- end
-
- ##
- # Build a self-signed certificate for the given email address.
-
- def self.build_self_signed_cert(email_addr, opt = {})
- Gem.ensure_ssl_available
- opt = OPT.merge(opt)
- path = { :key => nil, :cert => nil }
-
- name = email_to_name email_addr, opt[:munge_re]
-
- key = opt[:key_algo].new opt[:key_size]
-
- verify_trust_dir opt[:trust_dir], opt[:perms][:trust_dir]
-
- if opt[:save_key] then
- path[:key] = opt[:save_key_path] || (opt[:output_fmt] % 'private_key')
-
- open path[:key], 'wb' do |io|
- io.chmod opt[:perms][:signing_key]
- io.write key.to_pem
- end
- end
-
- cert = build_cert name, key, opt
-
- if opt[:save_cert] then
- path[:cert] = opt[:save_cert_path] || (opt[:output_fmt] % 'public_cert')
-
- open path[:cert], 'wb' do |file|
- file.chmod opt[:perms][:signing_cert]
- file.write cert.to_pem
- end
- end
-
- { :key => key, :cert => cert,
- :key_path => path[:key], :cert_path => path[:cert] }
- end
-
- ##
- # Turns +email_address+ into an OpenSSL::X509::Name
-
- def self.email_to_name email_address, munge_re
- cn, dcs = email_address.split '@'
-
- dcs = dcs.split '.'
-
- cn = cn.gsub munge_re, '_'
-
- dcs = dcs.map do |dc|
- dc.gsub munge_re, '_'
- end
-
- name = "CN=#{cn}/" << dcs.map { |dc| "DC=#{dc}" }.join('/')
-
- OpenSSL::X509::Name.parse name
- end
-
- ##
- # Add certificate to trusted cert list.
- #
- # Note: At the moment these are stored in OPT[:trust_dir], although that
- # directory may change in the future.
-
- def self.add_trusted_cert(cert, opt = {})
- opt = OPT.merge(opt)
-
- # get destination path
- path = Gem::Security::Policy.trusted_cert_path(cert, opt)
-
- # verify trust directory (can't write to nowhere, you know)
- verify_trust_dir(opt[:trust_dir], opt[:perms][:trust_dir])
-
- # write cert to output file
- File.open(path, 'wb') do |file|
- file.chmod(opt[:perms][:trusted_cert])
- file.write(cert.to_pem)
- end
-
- # return nil
- nil
- end
-
- ##
- # Basic OpenSSL-based package signing class.
-
- class Signer
-
- attr_accessor :cert_chain
- attr_accessor :key
-
- def initialize(key, cert_chain)
- Gem.ensure_ssl_available
- @algo = Gem::Security::OPT[:dgst_algo]
- @key, @cert_chain = key, cert_chain
-
- # check key, if it's a file, and if it's key, leave it alone
- if @key && !@key.kind_of?(OpenSSL::PKey::PKey)
- @key = OpenSSL::PKey::RSA.new(File.read(@key))
- end
-
- # check cert chain, if it's a file, load it, if it's cert data, convert
- # it into a cert object, and if it's a cert object, leave it alone
- if @cert_chain
- @cert_chain = @cert_chain.map do |cert|
- # check cert, if it's a file, load it, if it's cert data, convert it
- # into a cert object, and if it's a cert object, leave it alone
- if cert && !cert.kind_of?(OpenSSL::X509::Certificate)
- cert = File.read(cert) if File::exist?(cert)
- cert = OpenSSL::X509::Certificate.new(cert)
- end
- cert
- end
- end
- end
-
- ##
- # Sign data with given digest algorithm
-
- def sign(data)
- @key.sign(@algo.new, data)
- end
-
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/server.rb b/ruby_1_9_3/lib/rubygems/server.rb
deleted file mode 100644
index 47fa7c562d..0000000000
--- a/ruby_1_9_3/lib/rubygems/server.rb
+++ /dev/null
@@ -1,832 +0,0 @@
-require 'webrick'
-require 'zlib'
-require 'erb'
-
-require 'rubygems'
-require 'rubygems/doc_manager'
-
-##
-# Gem::Server and allows users to serve gems for consumption by
-# `gem --remote-install`.
-#
-# gem_server starts an HTTP server on the given port and serves the following:
-# * "/" - Browsing of gem spec files for installed gems
-# * "/specs.#{Gem.marshal_version}.gz" - specs name/version/platform index
-# * "/latest_specs.#{Gem.marshal_version}.gz" - latest specs
-# name/version/platform index
-# * "/quick/" - Individual gemspecs
-# * "/gems" - Direct access to download the installable gems
-# * "/rdoc?q=" - Search for installed rdoc documentation
-# * legacy indexes:
-# * "/Marshal.#{Gem.marshal_version}" - Full SourceIndex dump of metadata
-# for installed gems
-#
-# == Usage
-#
-# gem_server = Gem::Server.new Gem.dir, 8089, false
-# gem_server.run
-#
-#--
-# TODO Refactor into a real WEBrick servlet to remove code duplication.
-
-class Gem::Server
-
- attr_reader :spec_dirs
-
- include ERB::Util
- include Gem::UserInteraction
-
- SEARCH = <<-SEARCH
- <form class="headerSearch" name="headerSearchForm" method="get" action="/rdoc">
- <div id="search" style="float:right">
- <label for="q">Filter/Search</label>
- <input id="q" type="text" style="width:10em" name="q">
- <button type="submit" style="display:none"></button>
- </div>
- </form>
- SEARCH
-
- DOC_TEMPLATE = <<-'DOC_TEMPLATE'
- <?xml version="1.0" encoding="iso-8859-1"?>
- <!DOCTYPE html
- PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
- <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
- <head>
- <title>RubyGems Documentation Index</title>
- <link rel="stylesheet" href="gem-server-rdoc-style.css" type="text/css" media="screen" />
- </head>
- <body>
- <div id="fileHeader">
-<%= SEARCH %>
- <h1>RubyGems Documentation Index</h1>
- </div>
- <!-- banner header -->
-
- <div id="bodyContent">
- <div id="contextContent">
- <div id="description">
- <h1>Summary</h1>
- <p>There are <%=values["gem_count"]%> gems installed:</p>
- <p>
- <%= values["specs"].map { |v| "<a href=\"##{v["name"]}\">#{v["name"]}</a>" }.join ', ' %>.
- <h1>Gems</h1>
-
- <dl>
- <% values["specs"].each do |spec| %>
- <dt>
- <% if spec["first_name_entry"] then %>
- <a name="<%=spec["name"]%>"></a>
- <% end %>
-
- <b><%=spec["name"]%> <%=spec["version"]%></b>
-
- <% if spec["rdoc_installed"] then %>
- <a href="<%=spec["doc_path"]%>">[rdoc]</a>
- <% else %>
- <span title="rdoc not installed">[rdoc]</span>
- <% end %>
-
- <% if spec["homepage"] then %>
- <a href="<%=spec["homepage"]%>" title="<%=spec["homepage"]%>">[www]</a>
- <% else %>
- <span title="no homepage available">[www]</span>
- <% end %>
-
- <% if spec["has_deps"] then %>
- - depends on
- <%= spec["dependencies"].map { |v| "<a href=\"##{v["name"]}\">#{v["name"]}</a>" }.join ', ' %>.
- <% end %>
- </dt>
- <dd>
- <%=spec["summary"]%>
- <% if spec["executables"] then %>
- <br/>
-
- <% if spec["only_one_executable"] then %>
- Executable is
- <% else %>
- Executables are
- <%end%>
-
- <%= spec["executables"].map { |v| "<span class=\"context-item-name\">#{v["executable"]}</span>"}.join ', ' %>.
-
- <%end%>
- <br/>
- <br/>
- </dd>
- <% end %>
- </dl>
-
- </div>
- </div>
- </div>
- <div id="validator-badges">
- <p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
- </div>
- </body>
- </html>
- DOC_TEMPLATE
-
- # CSS is copy & paste from rdoc-style.css, RDoc V1.0.1 - 20041108
- RDOC_CSS = <<-RDOC_CSS
-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 stylesheets 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; }
- RDOC_CSS
-
- RDOC_NO_DOCUMENTATION = <<-'NO_DOC'
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
- <head>
- <title>Found documentation</title>
- <link rel="stylesheet" href="gem-server-rdoc-style.css" type="text/css" media="screen" />
- </head>
- <body>
- <div id="fileHeader">
-<%= SEARCH %>
- <h1>No documentation found</h1>
- </div>
-
- <div id="bodyContent">
- <div id="contextContent">
- <div id="description">
- <p>No gems matched <%= h query.inspect %></p>
-
- <p>
- Back to <a href="/">complete gem index</a>
- </p>
-
- </div>
- </div>
- </div>
- <div id="validator-badges">
- <p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
- </div>
- </body>
-</html>
- NO_DOC
-
- RDOC_SEARCH_TEMPLATE = <<-'RDOC_SEARCH'
-<?xml version="1.0" encoding="iso-8859-1"?>
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
- <head>
- <title>Found documentation</title>
- <link rel="stylesheet" href="gem-server-rdoc-style.css" type="text/css" media="screen" />
- </head>
- <body>
- <div id="fileHeader">
-<%= SEARCH %>
- <h1>Found documentation</h1>
- </div>
- <!-- banner header -->
-
- <div id="bodyContent">
- <div id="contextContent">
- <div id="description">
- <h1>Summary</h1>
- <p><%=doc_items.length%> documentation topics found.</p>
- <h1>Topics</h1>
-
- <dl>
- <% doc_items.each do |doc_item| %>
- <dt>
- <b><%=doc_item[:name]%></b>
- <a href="<%=doc_item[:url]%>">[rdoc]</a>
- </dt>
- <dd>
- <%=doc_item[:summary]%>
- <br/>
- <br/>
- </dd>
- <% end %>
- </dl>
-
- <p>
- Back to <a href="/">complete gem index</a>
- </p>
-
- </div>
- </div>
- </div>
- <div id="validator-badges">
- <p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
- </div>
- </body>
-</html>
- RDOC_SEARCH
-
- def self.run(options)
- new(options[:gemdir], options[:port], options[:daemon],
- options[:launch], options[:addresses]).run
- end
-
- ##
- # Only the first directory in gem_dirs is used for serving gems
-
- def initialize(gem_dirs, port, daemon, launch = nil, addresses = nil)
- Socket.do_not_reverse_lookup = true
-
- @gem_dirs = Array gem_dirs
- @port = port
- @daemon = daemon
- @launch = launch
- @addresses = addresses
- logger = WEBrick::Log.new nil, WEBrick::BasicLog::FATAL
- @server = WEBrick::HTTPServer.new :DoNotListen => true, :Logger => logger
-
- @spec_dirs = @gem_dirs.map do |gem_dir|
- spec_dir = File.join gem_dir, 'specifications'
-
- unless File.directory? spec_dir then
- raise ArgumentError, "#{gem_dir} does not appear to be a gem repository"
- end
-
- spec_dir
- end
-
- Gem::Specification.dirs = @gem_dirs
- end
-
- def Marshal(req, res)
- Gem::Specification.reset
-
- add_date res
-
- index = Gem::Deprecate.skip_during { Marshal.dump Gem.source_index }
-
- if req.request_method == 'HEAD' then
- res['content-length'] = index.length
- return
- end
-
- if req.path =~ /Z$/ then
- res['content-type'] = 'application/x-deflate'
- index = Gem.deflate index
- else
- res['content-type'] = 'application/octet-stream'
- end
-
- res.body << index
- end
-
- def add_date res
- res['date'] = @spec_dirs.map do |spec_dir|
- File.stat(spec_dir).mtime
- end.max
- end
-
- def latest_specs(req, res)
- Gem::Specification.reset
-
- res['content-type'] = 'application/x-gzip'
-
- add_date res
-
- latest_specs = Gem::Specification.latest_specs
-
- specs = latest_specs.sort.map do |spec|
- platform = spec.original_platform || Gem::Platform::RUBY
- [spec.name, spec.version, platform]
- end
-
- specs = Marshal.dump specs
-
- if req.path =~ /\.gz$/ then
- specs = Gem.gzip specs
- res['content-type'] = 'application/x-gzip'
- else
- res['content-type'] = 'application/octet-stream'
- end
-
- if req.request_method == 'HEAD' then
- res['content-length'] = specs.length
- else
- res.body << specs
- end
- end
-
- ##
- # Creates server sockets based on the addresses option. If no addresses
- # were given a server socket for all interfaces is created.
-
- def listen addresses = @addresses
- addresses = [nil] unless addresses
-
- listeners = 0
-
- addresses.each do |address|
- begin
- @server.listen address, @port
- @server.listeners[listeners..-1].each do |listener|
- host, port = listener.addr.values_at 2, 1
- host = "[#{host}]" if host =~ /:/ # we don't reverse lookup
- say "Server started at http://#{host}:#{port}"
- end
-
- listeners = @server.listeners.length
- rescue SystemCallError
- next
- end
- end
-
- if @server.listeners.empty? then
- say "Unable to start a server."
- say "Check for running servers or your --bind and --port arguments"
- terminate_interaction 1
- end
- end
-
- def quick(req, res)
- Gem::Specification.reset
-
- res['content-type'] = 'text/plain'
- add_date res
-
- case req.request_uri.path
- when %r|^/quick/(Marshal.#{Regexp.escape Gem.marshal_version}/)?(.*?)-([0-9.]+)(-.*?)?\.gemspec\.rz$| then
- marshal_format, name, version, platform = $1, $2, $3, $4
- specs = Gem::Specification.find_all_by_name name, version
-
- selector = [name, version, platform].map(&:inspect).join ' '
-
- platform = if platform then
- Gem::Platform.new platform.sub(/^-/, '')
- else
- Gem::Platform::RUBY
- end
-
- specs = specs.select { |s| s.platform == platform }
-
- if specs.empty? then
- res.status = 404
- res.body = "No gems found matching #{selector}"
- elsif specs.length > 1 then
- res.status = 500
- res.body = "Multiple gems found matching #{selector}"
- elsif marshal_format then
- res['content-type'] = 'application/x-deflate'
- res.body << Gem.deflate(Marshal.dump(specs.first))
- end
- else
- raise WEBrick::HTTPStatus::NotFound, "`#{req.path}' not found."
- end
- end
-
- def root(req, res)
- Gem::Specification.reset
- add_date res
-
- raise WEBrick::HTTPStatus::NotFound, "`#{req.path}' not found." unless
- req.path == '/'
-
- specs = []
- total_file_count = 0
-
- Gem::Specification.each do |spec|
- total_file_count += spec.files.size
- deps = spec.dependencies.map { |dep|
- {
- "name" => dep.name,
- "type" => dep.type,
- "version" => dep.requirement.to_s,
- }
- }
-
- deps = deps.sort_by { |dep| [dep["name"].downcase, dep["version"]] }
- deps.last["is_last"] = true unless deps.empty?
-
- # executables
- executables = spec.executables.sort.collect { |exec| {"executable" => exec} }
- executables = nil if executables.empty?
- executables.last["is_last"] = true if executables
-
- specs << {
- "authors" => spec.authors.sort.join(", "),
- "date" => spec.date.to_s,
- "dependencies" => deps,
- "doc_path" => "/doc_root/#{spec.full_name}/rdoc/index.html",
- "executables" => executables,
- "only_one_executable" => (executables && executables.size == 1),
- "full_name" => spec.full_name,
- "has_deps" => !deps.empty?,
- "homepage" => spec.homepage,
- "name" => spec.name,
- "rdoc_installed" => Gem::DocManager.new(spec).rdoc_installed?,
- "summary" => spec.summary,
- "version" => spec.version.to_s,
- }
- end
-
- specs << {
- "authors" => "Chad Fowler, Rich Kilmer, Jim Weirich, Eric Hodel and others",
- "dependencies" => [],
- "doc_path" => "/doc_root/rubygems-#{Gem::VERSION}/rdoc/index.html",
- "executables" => [{"executable" => 'gem', "is_last" => true}],
- "only_one_executable" => true,
- "full_name" => "rubygems-#{Gem::VERSION}",
- "has_deps" => false,
- "homepage" => "http://docs.rubygems.org/",
- "name" => 'rubygems',
- "rdoc_installed" => true,
- "summary" => "RubyGems itself",
- "version" => Gem::VERSION,
- }
-
- specs = specs.sort_by { |spec| [spec["name"].downcase, spec["version"]] }
- specs.last["is_last"] = true
-
- # tag all specs with first_name_entry
- last_spec = nil
- specs.each do |spec|
- is_first = last_spec.nil? || (last_spec["name"].downcase != spec["name"].downcase)
- spec["first_name_entry"] = is_first
- last_spec = spec
- end
-
- # create page from template
- template = ERB.new(DOC_TEMPLATE)
- res['content-type'] = 'text/html'
-
- values = { "gem_count" => specs.size.to_s, "specs" => specs,
- "total_file_count" => total_file_count.to_s }
-
- # suppress 1.9.3dev warning about unused variable
- values = values
-
- result = template.result binding
- res.body = result
- end
-
- ##
- # Can be used for quick navigation to the rdoc documentation. You can then
- # define a search shortcut for your browser. E.g. in Firefox connect
- # 'shortcut:rdoc' to http://localhost:8808/rdoc?q=%s template. Then you can
- # directly open the ActionPack documentation by typing 'rdoc actionp'. If
- # there are multiple hits for the search term, they are presented as a list
- # with links.
- #
- # Search algorithm aims for an intuitive search:
- # 1. first try to find the gems and documentation folders which name
- # starts with the search term
- # 2. search for entries, that *contain* the search term
- # 3. show all the gems
- #
- # If there is only one search hit, user is immediately redirected to the
- # documentation for the particular gem, otherwise a list with results is
- # shown.
- #
- # === Additional trick - install documentation for ruby core
- #
- # Note: please adjust paths accordingly use for example 'locate yaml.rb' and
- # 'gem environment' to identify directories, that are specific for your
- # local installation
- #
- # 1. install ruby sources
- # cd /usr/src
- # sudo apt-get source ruby
- #
- # 2. generate documentation
- # rdoc -o /usr/lib/ruby/gems/1.8/doc/core/rdoc \
- # /usr/lib/ruby/1.8 ruby1.8-1.8.7.72
- #
- # By typing 'rdoc core' you can now access the core documentation
-
- def rdoc(req, res)
- query = req.query['q']
- show_rdoc_for_pattern("#{query}*", res) && return
- show_rdoc_for_pattern("*#{query}*", res) && return
-
- template = ERB.new RDOC_NO_DOCUMENTATION
-
- res['content-type'] = 'text/html'
- res.body = template.result binding
- end
-
- ##
- # Returns true and prepares http response, if rdoc for the requested gem
- # name pattern was found.
- #
- # The search is based on the file system content, not on the gems metadata.
- # This allows additional documentation folders like 'core' for the ruby core
- # documentation - just put it underneath the main doc folder.
-
- def show_rdoc_for_pattern(pattern, res)
- found_gems = Dir.glob("{#{@gem_dirs.join ','}}/doc/#{pattern}").select {|path|
- File.exist? File.join(path, 'rdoc/index.html')
- }
- case found_gems.length
- when 0
- return false
- when 1
- new_path = File.basename(found_gems[0])
- res.status = 302
- res['Location'] = "/doc_root/#{new_path}/rdoc/index.html"
- return true
- else
- doc_items = []
- found_gems.each do |file_name|
- base_name = File.basename(file_name)
- doc_items << {
- :name => base_name,
- :url => "/doc_root/#{base_name}/rdoc/index.html",
- :summary => ''
- }
- end
-
- template = ERB.new(RDOC_SEARCH_TEMPLATE)
- res['content-type'] = 'text/html'
- result = template.result binding
- res.body = result
- return true
- end
- end
-
- def run
- listen
-
- WEBrick::Daemon.start if @daemon
-
- @server.mount_proc "/Marshal.#{Gem.marshal_version}", method(:Marshal)
- @server.mount_proc "/Marshal.#{Gem.marshal_version}.Z", method(:Marshal)
-
- @server.mount_proc "/specs.#{Gem.marshal_version}", method(:specs)
- @server.mount_proc "/specs.#{Gem.marshal_version}.gz", method(:specs)
-
- @server.mount_proc "/latest_specs.#{Gem.marshal_version}",
- method(:latest_specs)
- @server.mount_proc "/latest_specs.#{Gem.marshal_version}.gz",
- method(:latest_specs)
-
- @server.mount_proc "/quick/", method(:quick)
-
- @server.mount_proc("/gem-server-rdoc-style.css") do |req, res|
- res['content-type'] = 'text/css'
- add_date res
- res.body << RDOC_CSS
- end
-
- @server.mount_proc "/", method(:root)
-
- @server.mount_proc "/rdoc", method(:rdoc)
-
- paths = { "/gems" => "/cache/", "/doc_root" => "/doc/" }
- paths.each do |mount_point, mount_dir|
- @server.mount(mount_point, WEBrick::HTTPServlet::FileHandler,
- File.join(@gem_dirs.first, mount_dir), true)
- end
-
- trap("INT") { @server.shutdown; exit! }
- trap("TERM") { @server.shutdown; exit! }
-
- launch if @launch
-
- @server.start
- end
-
- def specs(req, res)
- Gem::Specification.reset
-
- add_date res
-
- specs = Gem::Specification.sort_by(&:sort_obj).map do |spec|
- platform = spec.original_platform || Gem::Platform::RUBY
- [spec.name, spec.version, platform]
- end
-
- specs = Marshal.dump specs
-
- if req.path =~ /\.gz$/ then
- specs = Gem.gzip specs
- res['content-type'] = 'application/x-gzip'
- else
- res['content-type'] = 'application/octet-stream'
- end
-
- if req.request_method == 'HEAD' then
- res['content-length'] = specs.length
- else
- res.body << specs
- end
- end
-
- def launch
- listeners = @server.listeners.map{|l| l.addr[2] }
-
- # TODO: 0.0.0.0 == any, not localhost.
- host = listeners.any?{|l| l == '0.0.0.0'} ? 'localhost' : listeners.first
-
- say "Launching browser to http://#{host}:#{@port}"
-
- system("#{@launch} http://#{host}:#{@port}")
- end
-end
diff --git a/ruby_1_9_3/lib/rubygems/source_index.rb b/ruby_1_9_3/lib/rubygems/source_index.rb
deleted file mode 100644
index 1fe92c0a80..0000000000
--- a/ruby_1_9_3/lib/rubygems/source_index.rb
+++ /dev/null
@@ -1,406 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-require 'rubygems/specification'
-require 'rubygems/deprecate'
-
-##
-# The SourceIndex object indexes all the gems available from a
-# particular source (e.g. a list of gem directories, or a remote
-# source). A SourceIndex maps a gem full name to a gem
-# specification.
-#
-# NOTE:: The class used to be named Cache, but that became
-# confusing when cached source fetchers where introduced. The
-# constant Gem::Cache is an alias for this class to allow old
-# YAMLized source index objects to load properly.
-
-class Gem::SourceIndex
-
- include Enumerable
-
- attr_reader :gems # :nodoc:
-
- ##
- # Directories to use to refresh this SourceIndex when calling refresh!
-
- attr_accessor :spec_dirs
-
- ##
- # Factory method to construct a source index instance for a given
- # path.
- #
- # deprecated::
- # If supplied, from_installed_gems will act just like
- # +from_gems_in+. This argument is deprecated and is provided
- # just for backwards compatibility, and should not generally
- # be used.
- #
- # return::
- # SourceIndex instance
-
- def self.from_installed_gems(*deprecated)
- if deprecated.empty?
- from_gems_in(*installed_spec_directories)
- else
- warn "NOTE: from_installed_gems(arg) is deprecated. From #{caller.first}"
- from_gems_in(*deprecated) # HACK warn
- end
- end
-
- ##
- # Returns a list of directories from Gem.path that contain specifications.
-
- def self.installed_spec_directories
- # TODO: move to Gem::Utils
- Gem.path.collect { |dir| File.join(dir, "specifications") }
- end
-
- ##
- # Creates a new SourceIndex from the ruby format gem specifications in
- # +spec_dirs+.
-
- def self.from_gems_in(*spec_dirs)
- new spec_dirs
- end
-
- ##
- # Loads a ruby-format specification from +file_name+ and returns the
- # loaded spec.
-
- def self.load_specification(file_name)
- Gem::Deprecate.skip_during do
- Gem::Specification.load Gem::Path.new(file_name)
- end
- end
-
- ##
- # Constructs a source index instance from the provided specifications, which
- # is a Hash of gem full names and Gem::Specifications.
-
- def initialize specs_or_dirs = []
- @gems = {}
- @spec_dirs = nil
-
- case specs_or_dirs
- when Hash then
- specs_or_dirs.each do |full_name, spec|
- add_spec spec
- end
- when Array, String then
- self.spec_dirs = Array(specs_or_dirs)
- refresh!
- else
- arg = specs_or_dirs.inspect
- warn "NOTE: SourceIndex.new(#{arg}) is deprecated; From #{caller.first}."
- end
- end
-
- def all_gems
- gems
- end
-
- def prerelease_gems
- @gems.reject { |name, gem| !gem.version.prerelease? }
- end
-
- def released_gems
- @gems.reject { |name, gem| gem.version.prerelease? }
- end
-
- ##
- # Reconstruct the source index from the specifications in +spec_dirs+.
-
- def load_gems_in(*spec_dirs)
- @gems.clear
-
- spec_dirs.reverse_each do |spec_dir|
- spec_files = Dir[File.join(spec_dir, "*.gemspec")]
-
- spec_files.each do |spec_file|
- gemspec = Gem::Deprecate.skip_during do
- Gem::Specification.load spec_file
- end
- add_spec gemspec if gemspec
- end
- end
-
- self
- end
-
- ##
- # Returns an Array specifications for the latest released versions
- # of each gem in this index.
-
- def latest_specs(include_prerelease=false)
- result = Hash.new { |h,k| h[k] = [] }
- latest = {}
-
- sort.each do |_, spec|
- name = spec.name
- curr_ver = spec.version
- prev_ver = latest.key?(name) ? latest[name].version : nil
-
- next if !include_prerelease && curr_ver.prerelease?
- next unless prev_ver.nil? or curr_ver >= prev_ver or
- latest[name].platform != Gem::Platform::RUBY
-
- if prev_ver.nil? or
- (curr_ver > prev_ver and spec.platform == Gem::Platform::RUBY) then
- result[name].clear
- latest[name] = spec
- end
-
- if spec.platform != Gem::Platform::RUBY then
- result[name].delete_if do |result_spec|
- result_spec.platform == spec.platform
- end
- end
-
- result[name] << spec
- end
-
- result.values.flatten
- end
-
- ##
- # An array including only the prerelease gemspecs
-
- def prerelease_specs
- prerelease_gems.values
- end
-
- ##
- # An array including only the released gemspecs
-
- def released_specs
- released_gems.values
- end
-
- ##
- # Add a gem specification to the source index.
-
- def add_spec(gem_spec, name = gem_spec.full_name)
- # No idea why, but the Indexer wants to insert them using original_name
- # instead of full_name. So we make it an optional arg.
- @gems[name] = gem_spec
- end
-
- ##
- # Add gem specifications to the source index.
-
- def add_specs(*gem_specs)
- Gem::Deprecate.skip_during do
- gem_specs.each do |spec|
- add_spec spec
- end
- end
- end
-
- ##
- # Remove a gem specification named +full_name+.
-
- def remove_spec(full_name)
- @gems.delete full_name
- end
-
- ##
- # Iterate over the specifications in the source index.
-
- def each(&block) # :yields: gem.full_name, gem
- @gems.each(&block)
- end
-
- ##
- # The gem specification given a full gem spec name.
-
- def specification(full_name)
- @gems[full_name]
- end
-
- ##
- # The signature for the source index. Changes in the signature indicate a
- # change in the index.
-
- def index_signature
- require 'digest'
-
- Digest::SHA256.new.hexdigest(@gems.keys.sort.join(',')).to_s
- end
-
- ##
- # The signature for the given gem specification.
-
- def gem_signature(gem_full_name)
- require 'digest'
-
- Digest::SHA256.new.hexdigest(@gems[gem_full_name].to_yaml).to_s
- end
-
- def size
- @gems.size
- end
- alias length size
-
- ##
- # Find a gem by an exact match on the short name.
-
- def find_name(gem_name, requirement = Gem::Requirement.default)
- dep = Gem::Dependency.new gem_name, requirement
-
- Gem::Deprecate.skip_during do
- search dep
- end
- end
-
- ##
- # Search for a gem by Gem::Dependency +gem_pattern+. If +only_platform+
- # is true, only gems matching Gem::Platform.local will be returned. An
- # Array of matching Gem::Specification objects is returned.
- #
- # For backwards compatibility, a String or Regexp pattern may be passed as
- # +gem_pattern+, and a Gem::Requirement for +platform_only+. This
- # behavior is deprecated and will be removed.
-
- def search(gem_pattern, platform_or_requirement = false)
- requirement = nil
- only_platform = false # FIX: WTF is this?!?
-
- # TODO - Remove support and warning for legacy arguments after 2008/11
- unless Gem::Dependency === gem_pattern
- warn "#{Gem.location_of_caller.join ':'}:Warning: Gem::SourceIndex#search support for #{gem_pattern.class} patterns is deprecated, use #find_name"
- end
-
- case gem_pattern
- when Regexp then
- requirement = platform_or_requirement || Gem::Requirement.default
- when Gem::Dependency then
- only_platform = platform_or_requirement
- requirement = gem_pattern.requirement
-
- gem_pattern = if Regexp === gem_pattern.name then
- gem_pattern.name
- elsif gem_pattern.name.empty? then
- //
- else
- /^#{Regexp.escape gem_pattern.name}$/
- end
- else
- requirement = platform_or_requirement || Gem::Requirement.default
- gem_pattern = /#{gem_pattern}/i
- end
-
- unless Gem::Requirement === requirement then
- requirement = Gem::Requirement.create requirement
- end
-
- specs = @gems.values.select do |spec|
- spec.name =~ gem_pattern and
- requirement.satisfied_by? spec.version
- end
-
- if only_platform then
- specs = specs.select do |spec|
- Gem::Platform.match spec.platform
- end
- end
-
- specs.sort_by { |s| s.sort_obj }
- end
-
- ##
- # Replaces the gems in the source index from specifications in the
- # directories this source index was created from. Raises an exception if
- # this source index wasn't created from a directory (via from_gems_in or
- # from_installed_gems, or having spec_dirs set).
-
- def refresh!
- raise 'source index not created from disk' if @spec_dirs.nil?
- load_gems_in(*@spec_dirs)
- end
-
- ##
- # Returns an Array of Gem::Specifications that are not up to date.
-
- def outdated
- outdateds = []
-
- latest_specs.each do |local|
- dependency = Gem::Dependency.new local.name, ">= #{local.version}"
-
- fetcher = Gem::SpecFetcher.fetcher
- remotes = fetcher.find_matching dependency
- remotes = remotes.map { |(_, version, _), _| version }
-
- latest = remotes.sort.last
-
- outdateds << local.name if latest and local.version < latest
- end
-
- outdateds
- end
-
- def ==(other) # :nodoc:
- self.class === other and @gems == other.gems
- end
-
- def dump
- Marshal.dump(self)
- end
-end
-
-# :stopdoc:
-module Gem
-
- ##
- # Cache is an alias for SourceIndex to allow older YAMLized source index
- # objects to load properly.
-
- Cache = SourceIndex
-
-end
-
-class Gem::SourceIndex
- extend Gem::Deprecate
-
- deprecate :all_gems, :none, 2011, 10
-
- deprecate :==, :none, 2011, 11 # noisy
- deprecate :add_specs, :none, 2011, 11 # noisy
- deprecate :each, :none, 2011, 11
- deprecate :gems, :none, 2011, 11
- deprecate :load_gems_in, :none, 2011, 11
- deprecate :refresh!, :none, 2011, 11
- deprecate :spec_dirs=, "Specification.dirs=", 2011, 11 # noisy
- deprecate :add_spec, "Specification.add_spec", 2011, 11
- deprecate :find_name, "Specification.find_by_name", 2011, 11
- deprecate :gem_signature, :none, 2011, 11
- deprecate :index_signature, :none, 2011, 11
- deprecate :initialize, :none, 2011, 11
- deprecate :latest_specs, "Specification.latest_specs", 2011, 11
- deprecate :length, "Specification.all.length", 2011, 11
- deprecate :outdated, :none, 2011, 11
- deprecate :prerelease_gems, :none, 2011, 11
- deprecate :prerelease_specs, :none, 2011, 11
- deprecate :released_gems, :none, 2011, 11
- deprecate :released_specs, :none, 2011, 11
- deprecate :remove_spec, "Specification.remove_spec", 2011, 11
- deprecate :search, :none, 2011, 11
- deprecate :size, "Specification.all.size", 2011, 11
- deprecate :spec_dirs, "Specification.dirs", 2011, 11
- deprecate :specification, "Specification.find", 2011, 11
-
- class << self
- extend Gem::Deprecate
-
- deprecate :from_gems_in, :none, 2011, 10
- deprecate :from_installed_gems, :none, 2011, 10
- deprecate :installed_spec_directories, "Specification.dirs", 2011, 11
- deprecate :load_specification, :none, 2011, 10
- end
-end
-
-# :startdoc:
diff --git a/ruby_1_9_3/lib/rubygems/spec_fetcher.rb b/ruby_1_9_3/lib/rubygems/spec_fetcher.rb
deleted file mode 100644
index 7302ad9ffa..0000000000
--- a/ruby_1_9_3/lib/rubygems/spec_fetcher.rb
+++ /dev/null
@@ -1,297 +0,0 @@
-require 'rubygems/remote_fetcher'
-require 'rubygems/user_interaction'
-require 'rubygems/errors'
-require 'rubygems/text'
-
-##
-# SpecFetcher handles metadata updates from remote gem repositories.
-
-class Gem::SpecFetcher
-
- include Gem::UserInteraction
- include Gem::Text
-
- FILES = {
- :all => 'specs',
- :latest => 'latest_specs',
- :prerelease => 'prerelease_specs',
- }
-
- ##
- # The SpecFetcher cache dir.
-
- attr_reader :dir # :nodoc:
-
- ##
- # Cache of latest specs
-
- attr_reader :latest_specs # :nodoc:
-
- ##
- # Cache of all released specs
-
- attr_reader :specs # :nodoc:
-
- ##
- # Cache of prerelease specs
-
- attr_reader :prerelease_specs # :nodoc:
-
- @fetcher = nil
-
- def self.fetcher
- @fetcher ||= new
- end
-
- def self.fetcher=(fetcher) # :nodoc:
- @fetcher = fetcher
- end
-
- def initialize
- require 'fileutils'
-
- @dir = File.join Gem.user_home, '.gem', 'specs'
- @update_cache = File.stat(Gem.user_home).uid == Process.uid
-
- @specs = {}
- @latest_specs = {}
- @prerelease_specs = {}
-
- @caches = {
- :latest => @latest_specs,
- :prerelease => @prerelease_specs,
- :all => @specs
- }
-
- @fetcher = Gem::RemoteFetcher.fetcher
- end
-
- ##
- # Returns the local directory to write +uri+ to.
-
- def cache_dir(uri)
- # Correct for windows paths
- escaped_path = uri.path.sub(/^\/([a-z]):\//i, '/\\1-/')
- File.join @dir, "#{uri.host}%#{uri.port}", File.dirname(escaped_path)
- end
-
- ##
- # Fetch specs matching +dependency+. If +all+ is true, all matching
- # (released) versions are returned. If +matching_platform+ is
- # false, all platforms are returned. If +prerelease+ is true,
- # prerelease versions are included.
-
- def fetch_with_errors(dependency,
- all = false,
- matching_platform = true,
- prerelease = false)
-
- specs_and_sources, errors = find_matching_with_errors(dependency,
- all,
- matching_platform,
- prerelease)
-
- ss = specs_and_sources.map do |spec_tuple, source_uri|
- [fetch_spec(spec_tuple, URI.parse(source_uri)), source_uri]
- end
-
- return [ss, errors]
- end
-
- def fetch(*args)
- fetch_with_errors(*args).first
- end
-
- def fetch_spec(spec, source_uri)
- source_uri = URI.parse source_uri if String === source_uri
- spec = spec - [nil, 'ruby', '']
- spec_file_name = "#{spec.join '-'}.gemspec"
-
- uri = source_uri + "#{Gem::MARSHAL_SPEC_DIR}#{spec_file_name}"
-
- cache_dir = cache_dir uri
-
- local_spec = File.join cache_dir, spec_file_name
-
- if File.exist? local_spec then
- spec = Gem.read_binary local_spec
- else
- uri.path << '.rz'
-
- spec = @fetcher.fetch_path uri
- spec = Gem.inflate spec
-
- if @update_cache then
- FileUtils.mkdir_p cache_dir
-
- open local_spec, 'wb' do |io|
- io.write spec
- end
- end
- end
-
- # TODO: Investigate setting Gem::Specification#loaded_from to a URI
- Marshal.load spec
- end
-
- ##
- # Find spec names that match +dependency+. If +all+ is true, all
- # matching released versions are returned. If +matching_platform+
- # is false, gems for all platforms are returned.
-
- def find_matching_with_errors(dependency,
- all = false,
- matching_platform = true,
- prerelease = false)
- found = {}
-
- rejected_specs = {}
-
- list(all, prerelease).each do |source_uri, specs|
- found[source_uri] = specs.select do |spec_name, version, spec_platform|
- if dependency.match?(spec_name, version)
- if matching_platform and !Gem::Platform.match(spec_platform)
- pm = (rejected_specs[dependency] ||= Gem::PlatformMismatch.new(spec_name, version))
- pm.add_platform spec_platform
- false
- else
- true
- end
- end
- end
- end
-
- errors = rejected_specs.values
-
- specs_and_sources = []
-
- found.each do |source_uri, specs|
- uri_str = source_uri.to_s
- specs_and_sources.concat(specs.map { |spec| [spec, uri_str] })
- end
-
- [specs_and_sources, errors]
- end
-
- def find_matching(*args)
- find_matching_with_errors(*args).first
- end
-
- ##
- # Suggests a gem based on the supplied +gem_name+. Returns a string
- # of the gem name if an approximate match can be found or nil
- # otherwise. NOTE: for performance reasons only gems which exactly
- # match the first character of +gem_name+ are considered.
-
- def suggest_gems_from_name gem_name
- gem_name = gem_name.downcase
- max = gem_name.size / 2
- specs = list.values.flatten 1
-
- matches = specs.map { |name, version, platform|
- next unless Gem::Platform.match platform
-
- distance = levenshtein_distance gem_name, name.downcase
-
- next if distance >= max
-
- return [name] if distance == 0
-
- [name, distance]
- }.compact
-
- matches = matches.uniq.sort_by { |name, dist| dist }
-
- matches.first(5).map { |name, dist| name }
- end
-
- ##
- # Returns a list of gems available for each source in Gem::sources. If
- # +all+ is true, all released versions are returned instead of only latest
- # versions. If +prerelease+ is true, include prerelease versions.
-
- def list(all = false, prerelease = false)
- # TODO: make type the only argument
- type = if all
- :all
- elsif prerelease
- :prerelease
- else
- :latest
- end
-
- list = {}
- file = FILES[type]
- cache = @caches[type]
-
- Gem.sources.each do |source_uri|
- source_uri = URI.parse source_uri
-
- unless cache.include? source_uri
- cache[source_uri] = load_specs source_uri, file
- end
-
- list[source_uri] = cache[source_uri]
- end
-
- if type == :all
- list.values.map do |gems|
- gems.reject! { |g| !g[1] || g[1].prerelease? }
- end
- end
-
- list
- end
-
- ##
- # Loads specs in +file+, fetching from +source_uri+ if the on-disk cache is
- # out of date.
-
- def load_specs(source_uri, file)
- file_name = "#{file}.#{Gem.marshal_version}"
- spec_path = source_uri + "#{file_name}.gz"
- cache_dir = cache_dir spec_path
- local_file = File.join(cache_dir, file_name)
- loaded = false
-
- if File.exist? local_file then
- begin
- spec_dump =
- @fetcher.fetch_path(spec_path, File.mtime(local_file))
- rescue Gem::RemoteFetcher::FetchError => e
- alert_warning "Error fetching data: #{e.message}"
- end
-
- loaded = true if spec_dump
-
- spec_dump ||= Gem.read_binary local_file
- else
- spec_dump = @fetcher.fetch_path spec_path
- loaded = true
- end
-
- specs = begin
- Marshal.load spec_dump
- rescue ArgumentError
- spec_dump = @fetcher.fetch_path spec_path
- loaded = true
-
- Marshal.load spec_dump
- end
-
- if loaded and @update_cache then
- begin
- FileUtils.mkdir_p cache_dir
-
- open local_file, 'wb' do |io|
- io << spec_dump
- end
- rescue
- end
- end
-
- specs
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/specification.rb b/ruby_1_9_3/lib/rubygems/specification.rb
deleted file mode 100644
index 70a3fd09b4..0000000000
--- a/ruby_1_9_3/lib/rubygems/specification.rb
+++ /dev/null
@@ -1,2171 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-require 'rubygems/version'
-require 'rubygems/requirement'
-require 'rubygems/platform'
-require "rubygems/deprecate"
-
-# :stopdoc:
-class Date; end # for ruby_code if date.rb wasn't required
-# :startdoc:
-
-##
-# The Specification class contains the metadata for a Gem. Typically
-# defined in a .gemspec file or a Rakefile, and looks like this:
-#
-# spec = Gem::Specification.new do |s|
-# s.name = 'example'
-# s.version = '1.0'
-# s.summary = 'Example gem specification'
-# ...
-# end
-#
-# For a great way to package gems, use Hoe.
-
-class Gem::Specification
-
- ##
- # The the version number of a specification that does not specify one
- # (i.e. RubyGems 0.7 or earlier).
-
- NONEXISTENT_SPECIFICATION_VERSION = -1
-
- ##
- # The specification version applied to any new Specification instances
- # created. This should be bumped whenever something in the spec format
- # changes.
- #
- # Specification Version History:
- #
- # spec ruby
- # ver ver yyyy-mm-dd description
- # -1 <0.8.0 pre-spec-version-history
- # 1 0.8.0 2004-08-01 Deprecated "test_suite_file" for "test_files"
- # "test_file=x" is a shortcut for "test_files=[x]"
- # 2 0.9.5 2007-10-01 Added "required_rubygems_version"
- # Now forward-compatible with future versions
- # 3 1.3.2 2009-01-03 Added Fixnum validation to specification_version
- #--
- # When updating this number, be sure to also update #to_ruby.
- #
- # NOTE RubyGems < 1.2 cannot load specification versions > 2.
-
- CURRENT_SPECIFICATION_VERSION = 3
-
- # :stopdoc:
-
- # version => # of fields
- MARSHAL_FIELDS = { -1 => 16, 1 => 16, 2 => 16, 3 => 17 }
-
- today = Time.now.utc
- TODAY = Time.utc(today.year, today.month, today.day)
-
- # :startdoc:
-
- ##
- # List of attribute names: [:name, :version, ...]
-
- @@required_attributes = [:rubygems_version,
- :specification_version,
- :name,
- :version,
- :date,
- :summary,
- :require_paths]
-
- ##
- # Map of attribute names to default values.
-
- @@default_value = {
- :authors => [],
- :autorequire => nil,
- :bindir => 'bin',
- :cert_chain => [],
- :date => TODAY,
- :dependencies => [],
- :description => nil,
- :email => nil,
- :executables => [],
- :extensions => [],
- :extra_rdoc_files => [],
- :files => [],
- :homepage => nil,
- :licenses => [],
- :name => nil,
- :platform => Gem::Platform::RUBY,
- :post_install_message => nil,
- :rdoc_options => [],
- :require_paths => ['lib'],
- :required_ruby_version => Gem::Requirement.default,
- :required_rubygems_version => Gem::Requirement.default,
- :requirements => [],
- :rubyforge_project => nil,
- :rubygems_version => Gem::VERSION,
- :signing_key => nil,
- :specification_version => CURRENT_SPECIFICATION_VERSION,
- :summary => nil,
- :test_files => [],
- :version => nil,
- }
-
- @@attributes = @@default_value.keys.sort_by { |s| s.to_s }
- @@array_attributes = @@default_value.reject { |k,v| v != [] }.keys
- @@nil_attributes, @@non_nil_attributes = @@default_value.keys.partition { |k|
- @@default_value[k].nil?
- }
-
- ######################################################################
- # :section: Required gemspec attributes
-
- ##
- # This gem's name
-
- attr_accessor :name
-
- ##
- # This gem's version
-
- attr_reader :version
-
- ##
- # Paths in the gem to add to $LOAD_PATH when this gem is activated.
- #
- # The default ['lib'] is typically sufficient.
-
- attr_accessor :require_paths
-
- ##
- # The version of RubyGems used to create this gem.
- #
- # Do not set this, it is set automatically when the gem is packaged.
-
- attr_accessor :rubygems_version
-
- ##
- # The Gem::Specification version of this gemspec.
- #
- # Do not set this, it is set automatically when the gem is packaged.
-
- attr_accessor :specification_version
-
- ##
- # A short summary of this gem's description. Displayed in `gem list -d`.
- #
- # The description should be more detailed than the summary. For example,
- # you might wish to copy the entire README into the description.
-
- attr_reader :summary
-
- ######################################################################
- # :section: Optional gemspec attributes
-
- ##
- # Autorequire was used by old RubyGems to automatically require a file.
- #
- # Deprecated: It is neither supported nor functional.
-
- attr_accessor :autorequire
-
- ##
- # The path in the gem for executable scripts. Usually 'bin'
-
- attr_accessor :bindir
-
- ##
- # The certificate chain used to sign this gem. See Gem::Security for
- # details.
-
- attr_accessor :cert_chain
-
- ##
- # A long description of this gem
-
- attr_reader :description
-
- ##
- # Sets the default executable for this gem.
- #
- # Deprecated: You must now specify the executable name to Gem.bin_path.
-
- attr_writer :default_executable
-
- ##
- # A contact email for this gem
- #
- # If you are providing multiple authors and multiple emails they should be
- # in the same order such that:
- #
- # Hash[*spec.authors.zip(spec.emails).flatten]
- #
- # Gives a hash of author name to email address.
-
- attr_accessor :email
-
- ##
- # The URL of this gem's home page
-
- attr_accessor :homepage
-
- ##
- # True when this gemspec has been activated. This attribute is not persisted.
-
- attr_accessor :loaded # :nodoc:
-
- alias :loaded? :loaded # :nodoc:
-
- ##
- # True when this gemspec has been activated. This attribute is not persisted.
-
- attr_accessor :activated
-
- alias :activated? :activated
-
- ##
- # Path this gemspec was loaded from. This attribute is not persisted.
-
- attr_reader :loaded_from
-
- ##
- # Allows deinstallation of gems with legacy platforms.
-
- attr_writer :original_platform # :nodoc:
-
- ##
- # A message that gets displayed after the gem is installed
-
- attr_accessor :post_install_message
-
- ##
- # The version of ruby required by this gem
-
- attr_reader :required_ruby_version
-
- ##
- # The RubyGems version required by this gem
-
- attr_reader :required_rubygems_version
-
- ##
- # The rubyforge project this gem lives under. i.e. RubyGems'
- # rubyforge_project is "rubygems".
-
- attr_accessor :rubyforge_project
-
- ##
- # The key used to sign this gem. See Gem::Security for details.
-
- attr_accessor :signing_key
-
- def self._all # :nodoc:
- unless defined?(@@all) && @@all then
- specs = {}
-
- self.dirs.each { |dir|
- Dir[File.join(dir, "*.gemspec")].each { |path|
- spec = Gem::Specification.load path.untaint
- # #load returns nil if the spec is bad, so we just ignore
- # it at this stage
- specs[spec.full_name] ||= spec if spec
- }
- }
-
- @@all = specs.values
-
- _resort!
- end
- @@all
- end
-
- def self._resort! # :nodoc:
- @@all.sort! { |a, b|
- names = a.name <=> b.name
- next names if names.nonzero?
- b.version <=> a.version
- }
- end
-
- ##
- # Adds +spec+ to the known specifications, keeping the collection
- # properly sorted.
-
- def self.add_spec spec
- # TODO: find all extraneous adds
- # puts
- # p :add_spec => [spec.full_name, caller.reject { |s| s =~ /minitest/ }]
-
- # TODO: flush the rest of the crap from the tests
- # raise "no dupes #{spec.full_name} in #{all_names.inspect}" if
- # _all.include? spec
-
- raise "nil spec!" unless spec # TODO: remove once we're happy with tests
-
- return if _all.include? spec
-
- _all << spec
- _resort!
- end
-
- ##
- # Adds multiple specs to the known specifications.
-
- def self.add_specs *specs
- raise "nil spec!" if specs.any?(&:nil?) # TODO: remove once we're happy
-
- # TODO: this is much more efficient, but we need the extra checks for now
- # _all.concat specs
- # _resort!
-
- specs.each do |spec| # TODO: slow
- add_spec spec
- end
- end
-
- ##
- # Returns all specifications. This method is discouraged from use.
- # You probably want to use one of the Enumerable methods instead.
-
- def self.all
- warn "NOTE: Specification.all called from #{caller.first}" unless
- Gem::Deprecate.skip
- _all
- end
-
- ##
- # Sets the known specs to +specs+. Not guaranteed to work for you in
- # the future. Use at your own risk. Caveat emptor. Doomy doom doom.
- # Etc etc.
- #
- #--
- # Makes +specs+ the known specs
- # Listen, time is a river
- # Winter comes, code breaks
- #
- # -- wilsonb
-
- def self.all= specs
- @@all = specs
- end
-
- ##
- # Return full names of all specs in sorted order.
-
- def self.all_names
- self._all.map(&:full_name)
- end
-
- ##
- # Return the list of all array-oriented instance variables.
- #--
- # Not sure why we need to use so much stupid reflection in here...
-
- def self.array_attributes
- @@array_attributes.dup
- end
-
- ##
- # Return the list of all instance variables.
- #--
- # Not sure why we need to use so much stupid reflection in here...
-
- def self.attribute_names
- @@attributes.dup
- end
-
- ##
- # Return the directories that Specification uses to find specs.
-
- def self.dirs
- @@dirs ||= Gem.path.collect { |dir|
- File.join dir, "specifications"
- }
- end
-
- ##
- # Set the directories that Specification uses to find specs. Setting
- # this resets the list of known specs.
-
- def self.dirs= dirs
- # TODO: find extra calls to dir=
- # warn "NOTE: dirs= called from #{caller.first} for #{dirs.inspect}"
-
- self.reset
-
- # ugh
- @@dirs = Array(dirs).map { |dir| File.join dir, "specifications" }
- end
-
- extend Enumerable
-
- ##
- # Enumerate every known spec. See ::dirs= and ::add_spec to set the list of
- # specs.
-
- def self.each
- return enum_for(:each) unless block_given?
-
- self._all.each do |x|
- yield x
- end
- end
-
- ##
- # Returns every spec that matches +name+ and optional +requirements+.
-
- def self.find_all_by_name name, *requirements
- requirements = Gem::Requirement.default if requirements.empty?
-
- # TODO: maybe try: find_all { |s| spec === dep }
-
- Gem::Dependency.new(name, *requirements).matching_specs
- end
-
- ##
- # Find the best specification matching a +name+ and +requirements+. Raises
- # if the dependency doesn't resolve to a valid specification.
-
- def self.find_by_name name, *requirements
- requirements = Gem::Requirement.default if requirements.empty?
-
- # TODO: maybe try: find { |s| spec === dep }
-
- Gem::Dependency.new(name, *requirements).to_spec
- end
-
- ##
- # Return the best specification that contains the file matching +path+.
-
- def self.find_by_path path
- self.find { |spec|
- spec.contains_requirable_file? path
- }
- end
-
- ##
- # Return currently unresolved specs that contain the file matching +path+.
-
- def self.find_in_unresolved path
- # TODO: do we need these?? Kill it
- specs = Gem.unresolved_deps.values.map { |dep| dep.to_specs }.flatten
-
- specs.find_all { |spec| spec.contains_requirable_file? path }
- end
-
- ##
- # Search through all unresolved deps and sub-dependencies and return
- # specs that contain the file matching +path+.
-
- def self.find_in_unresolved_tree path
- specs = Gem.unresolved_deps.values.map { |dep| dep.to_specs }.flatten
-
- specs.reverse_each do |spec|
- trails = []
- spec.traverse do |from_spec, dep, to_spec, trail|
- next unless to_spec.conflicts.empty?
- trails << trail if to_spec.contains_requirable_file? path
- end
-
- next if trails.empty?
-
- return trails.map(&:reverse).sort.first.reverse
- end
-
- []
- end
-
- ##
- # Special loader for YAML files. When a Specification object is loaded
- # from a YAML file, it bypasses the normal Ruby object initialization
- # routine (#initialize). This method makes up for that and deals with
- # gems of different ages.
- #
- # +input+ can be anything that YAML.load() accepts: String or IO.
-
- def self.from_yaml(input)
- Gem.load_yaml
-
- input = normalize_yaml_input input
- spec = YAML.load input
-
- if spec && spec.class == FalseClass then
- raise Gem::EndOfYAMLException
- end
-
- unless Gem::Specification === spec then
- raise Gem::Exception, "YAML data doesn't evaluate to gem specification"
- end
-
- unless (spec.instance_variables.include? '@specification_version' or
- spec.instance_variables.include? :@specification_version) and
- spec.instance_variable_get :@specification_version
- spec.instance_variable_set :@specification_version,
- NONEXISTENT_SPECIFICATION_VERSION
- end
-
- spec
- end
-
- ##
- # Return the latest specs, optionally including prerelease specs if
- # +prerelease+ is true.
-
- def self.latest_specs prerelease = false
- result = Hash.new { |h,k| h[k] = {} }
- native = {}
-
- Gem::Specification._all.reverse_each do |spec|
- next if spec.version.prerelease? unless prerelease
-
- native[spec.name] = spec.version if spec.platform == Gem::Platform::RUBY
- result[spec.name][spec.platform] = spec
- end
-
- result.map(&:last).map(&:values).flatten.reject { |spec|
- minimum = native[spec.name]
- minimum && spec.version < minimum
- }
- end
-
- ##
- # Loads Ruby format gemspec from +file+.
-
- def self.load file
- return unless file && File.file?(file)
-
- file = file.dup.untaint
-
- code = if defined? Encoding
- File.read file, :mode => 'r:UTF-8:-'
- else
- File.read file
- end
-
- code.untaint
-
- begin
- spec = eval code, binding, file
-
- if Gem::Specification === spec
- spec.loaded_from = file.to_s
- return spec
- end
-
- warn "[#{file}] isn't a Gem::Specification (#{spec.class} instead)."
- rescue SignalException, SystemExit
- raise
- rescue SyntaxError, Exception => e
- warn "Invalid gemspec in [#{file}]: #{e}"
- end
-
- nil
- end
-
- ##
- # Specification attributes that must be non-nil
-
- def self.non_nil_attributes
- @@non_nil_attributes.dup
- end
-
- ##
- # Make sure the YAML specification is properly formatted with dashes
-
- def self.normalize_yaml_input(input)
- result = input.respond_to?(:read) ? input.read : input
- result = "--- " + result unless result =~ /\A--- /
- result.gsub!(/ !!null \n/, " \n")
- # date: 2011-04-26 00:00:00.000000000Z
- # date: 2011-04-26 00:00:00.000000000 Z
- result.gsub!(/^(date: \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+?)Z/, '\1 Z')
- result
- end
-
- ##
- # Return a list of all outdated specifications. This method is HEAVY
- # as it must go fetch specifications from the server.
-
- def self.outdated
- outdateds = []
-
- # TODO: maybe we should switch to rubygems' version service?
- fetcher = Gem::SpecFetcher.fetcher
-
- latest_specs.each do |local|
- dependency = Gem::Dependency.new local.name, ">= #{local.version}"
- remotes = fetcher.find_matching dependency
- remotes = remotes.map { |(_, version, _), _| version }
- latest = remotes.sort.last
-
- outdateds << local.name if latest and local.version < latest
- end
-
- outdateds
- end
-
- ##
- # Removes +spec+ from the known specs.
-
- def self.remove_spec spec
- # TODO: beat on the tests
- raise "wtf: #{spec.full_name} not in #{all_names.inspect}" unless
- _all.include? spec
- _all.delete spec
- end
-
- ##
- # Is +name+ a required attribute?
-
- def self.required_attribute?(name)
- @@required_attributes.include? name.to_sym
- end
-
- ##
- # Required specification attributes
-
- def self.required_attributes
- @@required_attributes.dup
- end
-
- ##
- # Reset the list of known specs, running pre and post reset hooks
- # registered in Gem.
-
- def self.reset
- @@dirs = nil
- # from = caller.first(10).reject { |s| s =~ /minitest/ }
- # warn ""
- # warn "NOTE: Specification.reset from #{from.inspect}"
- Gem.pre_reset_hooks.each { |hook| hook.call }
- @@all = nil
- Gem.post_reset_hooks.each { |hook| hook.call }
- end
-
- ##
- # Load custom marshal format, re-initializing defaults as needed
-
- def self._load(str)
- array = Marshal.load str
-
- spec = Gem::Specification.new
- spec.instance_variable_set :@specification_version, array[1]
-
- current_version = CURRENT_SPECIFICATION_VERSION
-
- field_count = if spec.specification_version > current_version then
- spec.instance_variable_set :@specification_version,
- current_version
- MARSHAL_FIELDS[current_version]
- else
- MARSHAL_FIELDS[spec.specification_version]
- end
-
- if array.size < field_count then
- raise TypeError, "invalid Gem::Specification format #{array.inspect}"
- end
-
- # Cleanup any YAML::PrivateType. They only show up for an old bug
- # where nil => null, so just convert them to nil based on the type.
-
- array.map! { |e| e.kind_of?(YAML::PrivateType) ? nil : e }
-
- spec.instance_variable_set :@rubygems_version, array[0]
- # spec version
- spec.instance_variable_set :@name, array[2]
- spec.instance_variable_set :@version, array[3]
- spec.date = array[4]
- spec.instance_variable_set :@summary, array[5]
- spec.instance_variable_set :@required_ruby_version, array[6]
- spec.instance_variable_set :@required_rubygems_version, array[7]
- spec.instance_variable_set :@original_platform, array[8]
- spec.instance_variable_set :@dependencies, array[9]
- spec.instance_variable_set :@rubyforge_project, array[10]
- spec.instance_variable_set :@email, array[11]
- spec.instance_variable_set :@authors, array[12]
- spec.instance_variable_set :@description, array[13]
- spec.instance_variable_set :@homepage, array[14]
- spec.instance_variable_set :@has_rdoc, array[15]
- spec.instance_variable_set :@new_platform, array[16]
- spec.instance_variable_set :@platform, array[16].to_s
- spec.instance_variable_set :@license, array[17]
- spec.instance_variable_set :@loaded, false
- spec.instance_variable_set :@activated, false
-
- spec
- end
-
- def <=>(other) # :nodoc:
- sort_obj <=> other.sort_obj
- end
-
- def == other # :nodoc:
- self.class === other &&
- name == other.name &&
- version == other.version &&
- platform == other.platform
- end
-
- ##
- # Dump only crucial instance variables.
- #--
- # MAINTAIN ORDER!
- # (down with the man)
-
- def _dump(limit)
- Marshal.dump [
- @rubygems_version,
- @specification_version,
- @name,
- @version,
- date,
- @summary,
- @required_ruby_version,
- @required_rubygems_version,
- @original_platform,
- @dependencies,
- @rubyforge_project,
- @email,
- @authors,
- @description,
- @homepage,
- true, # has_rdoc
- @new_platform,
- @licenses
- ]
- end
-
- ##
- # Activate this spec, registering it as a loaded spec and adding
- # it's lib paths to $LOAD_PATH. Returns true if the spec was
- # activated, false if it was previously activated. Freaks out if
- # there are conflicts upon activation.
-
- def activate
- raise_if_conflicts
-
- return false if Gem.loaded_specs[self.name]
-
- activate_dependencies
- add_self_to_load_path
-
- Gem.loaded_specs[self.name] = self
- @activated = true
- @loaded = true
-
- return true
- end
-
- ##
- # Activate all unambiguously resolved runtime dependencies of this
- # spec. Add any ambigous dependencies to the unresolved list to be
- # resolved later, as needed.
-
- def activate_dependencies
- self.runtime_dependencies.each do |spec_dep|
- if loaded = Gem.loaded_specs[spec_dep.name]
- next if spec_dep.matches_spec? loaded
-
- msg = "can't satisfy '#{spec_dep}', already activated '#{loaded.full_name}'"
- e = Gem::LoadError.new msg
- e.name = spec_dep.name
-
- raise e
- end
-
- specs = spec_dep.to_specs
-
- if specs.size == 1 then
- specs.first.activate
- else
- name = spec_dep.name
- Gem.unresolved_deps[name] = Gem.unresolved_deps[name].merge spec_dep
- end
- end
-
- Gem.unresolved_deps.delete self.name
- end
-
- ##
- # Returns an array with bindir attached to each executable in the
- # +executables+ list
-
- def add_bindir(executables)
- return nil if executables.nil?
-
- if @bindir then
- Array(executables).map { |e| File.join(@bindir, e) }
- else
- executables
- end
- rescue
- return nil
- end
-
- ##
- # Adds a dependency on gem +dependency+ with type +type+ that requires
- # +requirements+. Valid types are currently <tt>:runtime</tt> and
- # <tt>:development</tt>.
-
- def add_dependency_with_type(dependency, type, *requirements)
- requirements = if requirements.empty? then
- Gem::Requirement.default
- else
- requirements.flatten
- end
-
- unless dependency.respond_to?(:name) &&
- dependency.respond_to?(:version_requirements)
-
- dependency = Gem::Dependency.new(dependency, requirements, type)
- end
-
- dependencies << dependency
- end
-
- private :add_dependency_with_type
-
- ##
- # Adds a development dependency named +gem+ with +requirements+ to this
- # Gem. For example:
- #
- # spec.add_development_dependency 'example', '~> 1.1', '>= 1.1.4'
- #
- # Development dependencies aren't installed by default and aren't
- # activated when a gem is required.
-
- def add_development_dependency(gem, *requirements)
- add_dependency_with_type(gem, :development, *requirements)
- end
-
- ##
- # Adds a runtime dependency named +gem+ with +requirements+ to this Gem.
- # For example:
- #
- # spec.add_runtime_dependency 'example', '~> 1.1', '>= 1.1.4'
-
- def add_runtime_dependency(gem, *requirements)
- add_dependency_with_type(gem, :runtime, *requirements)
- end
-
- alias add_dependency add_runtime_dependency
-
- ##
- # Adds this spec's require paths to LOAD_PATH, in the proper location.
-
- def add_self_to_load_path
- paths = require_paths.map do |path|
- File.join full_gem_path, path
- end
-
- # gem directories must come after -I and ENV['RUBYLIB']
- insert_index = Gem.load_path_insert_index
-
- if insert_index then
- # gem directories must come after -I and ENV['RUBYLIB']
- $LOAD_PATH.insert(insert_index, *paths)
- else
- # we are probably testing in core, -I and RUBYLIB don't apply
- $LOAD_PATH.unshift(*paths)
- end
- end
-
- ##
- # Singular reader for #authors
-
- def author
- val = authors and val.first
- end
-
- ##
- # Singular writer for #authors
-
- def author= o
- self.authors = [o]
- end
-
- ##
- # The list of author names who wrote this gem.
- #
- # If you are providing multiple authors and multiple emails they should be
- # in the same order such that:
- #
- # Hash[*spec.authors.zip(spec.emails).flatten]
- #
- # Gives a hash of author name to email address.
-
- def authors
- @authors ||= []
- end
-
- ##
- # Sets the list of authors, ensuring it is an array.
-
- def authors= value
- @authors = Array(value).flatten.grep(String)
- end
-
- ##
- # Returns the full path to the base gem directory.
- #
- # eg: /usr/local/lib/ruby/gems/1.8
-
- def base_dir
- return Gem.dir unless loaded_from
- @base_dir ||= File.dirname File.dirname loaded_from
- end
-
- ##
- # Returns the full path to installed gem's bin directory.
- #
- # NOTE: do not confuse this with +bindir+, which is just 'bin', not
- # a full path.
-
- def bin_dir
- @bin_dir ||= File.join gem_dir, bindir # TODO: this is unfortunate
- end
-
- ##
- # Returns the full path to an executable named +name+ in this gem.
-
- def bin_file name
- File.join bin_dir, name
- end
-
- ##
- # Returns the full path to the cache directory containing this
- # spec's cached gem.
-
- def cache_dir
- @cache_dir ||= File.join base_dir, "cache"
- end
-
- ##
- # Returns the full path to the cached gem for this spec.
-
- def cache_file
- @cache_file ||= File.join cache_dir, "#{full_name}.gem"
- end
-
- alias :cache_gem :cache_file
-
- ##
- # Return any possible conflicts against the currently loaded specs.
-
- def conflicts
- conflicts = {}
- Gem.loaded_specs.values.each do |spec|
- bad = self.runtime_dependencies.find_all { |dep|
- spec.name == dep.name and not spec.satisfies_requirement? dep
- }
-
- conflicts[spec] = bad unless bad.empty?
- end
- conflicts
- end
-
- ##
- # Return true if this spec can require +file+.
-
- def contains_requirable_file? file
- root = full_gem_path
-
- require_paths.each do |lib|
- base = "#{root}/#{lib}/#{file}"
- Gem.suffixes.each do |suf|
- path = "#{base}#{suf}"
- return true if File.file? path
- end
- end
-
- return false
- end
-
- ##
- # The date this gem was created. Lazily defaults to TODAY.
-
- def date
- @date ||= TODAY
- end
-
- ##
- # The date this gem was created
- #
- # Do not set this, it is set automatically when the gem is packaged.
-
- def date= date
- # We want to end up with a Time object with one-day resolution.
- # This is the cleanest, most-readable, faster-than-using-Date
- # way to do it.
- @date = case date
- when String then
- if /\A(\d{4})-(\d{2})-(\d{2})\Z/ =~ date then
- Time.utc($1.to_i, $2.to_i, $3.to_i)
-
- # Workaround for where the date format output from psych isn't
- # parsed as a Time object by syck and thus comes through as a
- # string.
- elsif /\A(\d{4})-(\d{2})-(\d{2}) \d{2}:\d{2}:\d{2}\.\d+?Z\z/ =~ date then
- Time.utc($1.to_i, $2.to_i, $3.to_i)
- else
- raise(Gem::InvalidSpecificationException,
- "invalid date format in specification: #{date.inspect}")
- end
- when Time, Date then
- Time.utc(date.year, date.month, date.day)
- else
- TODAY
- end
- end
-
- ##
- # The default executable for this gem.
- #
- # Deprecated: The name of the gem is assumed to be the name of the
- # executable now. See Gem.bin_path.
-
- def default_executable
- if defined?(@default_executable) and @default_executable
- result = @default_executable
- elsif @executables and @executables.size == 1
- result = Array(@executables).first
- else
- result = nil
- end
- result
- end
-
- ##
- # The default value for specification attribute +name+
-
- def default_value name
- @@default_value[name]
- end
-
- ##
- # A list of Gem::Dependency objects this gem depends on.
- #
- # Use #add_dependency or #add_development_dependency to add dependencies to
- # a gem.
-
- def dependencies
- @dependencies ||= []
- end
-
- ##
- # Return a list of all gems that have a dependency on this gemspec. The
- # list is structured with entries that conform to:
- #
- # [depending_gem, dependency, [list_of_gems_that_satisfy_dependency]]
-
- def dependent_gems
- out = []
- Gem::Specification.each do |spec|
- spec.dependencies.each do |dep|
- if self.satisfies_requirement?(dep) then
- sats = []
- find_all_satisfiers(dep) do |sat|
- sats << sat
- end
- out << [spec, dep, sats]
- end
- end
- end
- out
- end
-
- ##
- # Returns all specs that matches this spec's runtime dependencies.
-
- def dependent_specs
- runtime_dependencies.map { |dep| dep.to_specs }.flatten
- end
-
- ##
- # A long description of this gem
-
- def description= str
- @description = str.to_s
- end
-
- ##
- # List of dependencies that are used for development
-
- def development_dependencies
- dependencies.select { |d| d.type == :development }
- end
-
- ##
- # Returns the full path to this spec's documentation directory.
-
- def doc_dir
- @doc_dir ||= File.join base_dir, 'doc', full_name
- end
-
- def encode_with coder # :nodoc:
- mark_version
-
- coder.add 'name', @name
- coder.add 'version', @version
- platform = case @original_platform
- when nil, '' then
- 'ruby'
- when String then
- @original_platform
- else
- @original_platform.to_s
- end
- coder.add 'platform', platform
-
- attributes = @@attributes.map(&:to_s) - %w[name version platform]
- attributes.each do |name|
- coder.add name, instance_variable_get("@#{name}")
- end
- end
-
- def eql? other # :nodoc:
- self.class === other && same_attributes?(other)
- end
-
- ##
- # Singular accessor for #executables
-
- def executable
- val = executables and val.first
- end
-
- ##
- # Singular accessor for #executables
-
- def executable=o
- self.executables = [o]
- end
-
- ##
- # Executables included in the gem.
-
- def executables
- @executables ||= []
- end
-
- ##
- # Sets executables to +value+, ensuring it is an array. Don't
- # use this, push onto the array instead.
-
- def executables= value
- # TODO: warn about setting instead of pushing
- @executables = Array(value)
- end
-
- ##
- # Extensions to build when installing the gem. See
- # Gem::Installer#build_extensions for valid values.
-
- def extensions
- @extensions ||= []
- end
-
- ##
- # Sets extensions to +extensions+, ensuring it is an array. Don't
- # use this, push onto the array instead.
-
- def extensions= extensions
- # TODO: warn about setting instead of pushing
- @extensions = Array extensions
- end
-
- ##
- # Extra files to add to RDoc such as README or doc/examples.txt
-
- def extra_rdoc_files
- @extra_rdoc_files ||= []
- end
-
- ##
- # Sets extra_rdoc_files to +files+, ensuring it is an array. Don't
- # use this, push onto the array instead.
-
- def extra_rdoc_files= files
- # TODO: warn about setting instead of pushing
- @extra_rdoc_files = Array files
- end
-
- ##
- # The default (generated) file name of the gem. See also #spec_name.
- #
- # spec.file_name # => "example-1.0.gem"
-
- def file_name
- "#{full_name}.gem"
- end
-
- ##
- # Files included in this gem. You cannot append to this accessor, you must
- # assign to it.
- #
- # Only add files you can require to this list, not directories, etc.
- #
- # Directories are automatically stripped from this list when building a gem,
- # other non-files cause an error.
-
- def files
- # DO NOT CHANGE TO ||= ! This is not a normal accessor. (yes, it sucks)
- @files = [@files,
- @test_files,
- add_bindir(@executables),
- @extra_rdoc_files,
- @extensions,
- ].flatten.uniq.compact
- end
-
- ##
- # Sets files to +files+, ensuring it is an array.
-
- def files= files
- @files = Array files
- end
-
- ##
- # Finds all gems that satisfy +dep+
-
- def find_all_satisfiers dep
- Gem::Specification.each do |spec|
- yield spec if spec.satisfies_requirement? dep
- end
- end
-
- private :find_all_satisfiers
-
- ##
- # Creates a duplicate spec without large blobs that aren't used at runtime.
-
- def for_cache
- spec = dup
-
- spec.files = nil
- spec.test_files = nil
-
- spec
- end
-
- ##
- # The full path to the gem (install path + full name).
-
- def full_gem_path
- # TODO: try to get rid of this... or the awkward
- # TODO: also, shouldn't it default to full_name if it hasn't been written?
- return @full_gem_path if defined?(@full_gem_path) && @full_gem_path
-
- @full_gem_path = File.expand_path File.join(gems_dir, full_name)
-
- return @full_gem_path if File.directory? @full_gem_path
-
- @full_gem_path = File.expand_path File.join(gems_dir, original_name)
- end
-
- ##
- # Returns the full name (name-version) of this Gem. Platform information
- # is included (name-version-platform) if it is specified and not the
- # default Ruby platform.
-
- def full_name
- if platform == Gem::Platform::RUBY or platform.nil? then
- "#{@name}-#{@version}"
- else
- "#{@name}-#{@version}-#{platform}"
- end
- end
-
- ##
- # Returns the full path to this spec's gem directory.
- # eg: /usr/local/lib/ruby/1.8/gems/mygem-1.0
-
- def gem_dir
- @gem_dir ||= File.expand_path File.join(gems_dir, full_name)
- end
-
- ##
- # Returns the full path to the gems directory containing this spec's
- # gem directory. eg: /usr/local/lib/ruby/1.8/gems
-
- def gems_dir
- # TODO: this logic seems terribly broken, but tests fail if just base_dir
- @gems_dir ||= File.join(loaded_from && base_dir || Gem.dir, "gems")
- end
-
- ##
- # Deprecated and ignored, defaults to true.
- #
- # Formerly used to indicate this gem was RDoc-capable.
-
- def has_rdoc
- true
- end
-
- ##
- # Deprecated and ignored.
- #
- # Formerly used to indicate this gem was RDoc-capable.
-
- def has_rdoc= ignored
- @has_rdoc = true
- end
-
- alias :has_rdoc? :has_rdoc
-
- ##
- # True if this gem has files in test_files
-
- def has_unit_tests?
- not test_files.empty?
- end
-
- # :stopdoc:
- alias has_test_suite? has_unit_tests?
- # :startdoc:
-
- def hash # :nodoc:
- @@attributes.inject(0) { |hash_code, (name, _)|
- hash_code ^ self.send(name).hash
- }
- end
-
- def init_with coder # :nodoc:
- yaml_initialize coder.tag, coder.map
- end
-
- ##
- # Specification constructor. Assigns the default values to the attributes
- # and yields itself for further initialization. Optionally takes +name+ and
- # +version+.
-
- def initialize name = nil, version = nil
- @loaded = false
- @activated = false
- @loaded_from = nil
- @original_platform = nil
-
- @@nil_attributes.each do |key|
- instance_variable_set "@#{key}", nil
- end
-
- @@non_nil_attributes.each do |key|
- default = default_value(key)
- value = case default
- when Time, Numeric, Symbol, true, false, nil then default
- else default.dup
- end
-
- instance_variable_set "@#{key}", value
- end
-
- @new_platform = Gem::Platform::RUBY
-
- self.name = name if name
- self.version = version if version
-
- yield self if block_given?
- end
-
- ##
- # Duplicates array_attributes from +other_spec+ so state isn't shared.
-
- def initialize_copy other_spec
- other_ivars = other_spec.instance_variables
- other_ivars = other_ivars.map { |ivar| ivar.intern } if # for 1.9
- String === other_ivars.first
-
- self.class.array_attributes.each do |name|
- name = :"@#{name}"
- next unless other_ivars.include? name
-
- begin
- val = other_spec.instance_variable_get(name)
- if val then
- instance_variable_set name, val.dup
- elsif Gem.configuration.really_verbose
- warn "WARNING: #{full_name} has an invalid nil value for #{name}"
- end
- rescue TypeError
- e = Gem::FormatException.new \
- "#{full_name} has an invalid value for #{name}"
-
- e.file_path = loaded_from
- raise e
- end
- end
- end
-
- ##
- # The directory that this gem was installed into.
- # TODO: rename - horrible. this is the base_dir for a gem path
-
- def installation_path
- loaded_from && base_dir
- end
-
- ##
- # Returns a string usable in Dir.glob to match all requirable paths
- # for this spec.
-
- def lib_dirs_glob
- dirs = if self.require_paths.size > 1 then
- "{#{self.require_paths.join(',')}}"
- else
- self.require_paths.first
- end
-
- "#{self.full_gem_path}/#{dirs}"
- end
-
- ##
- # Files in the Gem under one of the require_paths
-
- def lib_files
- @files.select do |file|
- require_paths.any? do |path|
- file.index(path) == 0
- end
- end
- end
-
- ##
- # Singular accessor for #licenses
-
- def license
- val = licenses and val.first
- end
-
- ##
- # Singular accessor for #licenses
-
- def license=o
- self.licenses = [o]
- end
-
- ##
- # The license(s) for the library. Each license must be a short name, no
- # more than 64 characters.
-
- def licenses
- @licenses ||= []
- end
-
- ##
- # Set licenses to +licenses+, ensuring it is an array.
-
- def licenses= licenses
- @licenses = Array licenses
- end
-
- ##
- # Set the location a Specification was loaded from. +obj+ is converted
- # to a String.
-
- def loaded_from= path
- @loaded_from = path.to_s
- end
-
- ##
- # Sets the rubygems_version to the current RubyGems version.
-
- def mark_version
- @rubygems_version = Gem::VERSION
- end
-
- ##
- # Return all files in this gem that match for +glob+.
-
- def matches_for_glob glob # TODO: rename?
- # TODO: do we need these?? Kill it
- glob = File.join(self.lib_dirs_glob, glob)
-
- Dir[glob].map { |f| f.untaint } # FIX our tests are broken, run w/ SAFE=1
- end
-
- ##
- # Warn about unknown attributes while loading a spec.
-
- def method_missing(sym, *a, &b) # :nodoc:
- if @specification_version > CURRENT_SPECIFICATION_VERSION and
- sym.to_s =~ /=$/ then
- warn "ignoring #{sym} loading #{full_name}" if $DEBUG
- else
- super
- end
- end
-
- ##
- # Normalize the list of files so that:
- # * All file lists have redundancies removed.
- # * Files referenced in the extra_rdoc_files are included in the package
- # file list.
-
- def normalize
- if defined?(@extra_rdoc_files) and @extra_rdoc_files then
- @extra_rdoc_files.uniq!
- @files ||= []
- @files.concat(@extra_rdoc_files)
- end
-
- @files = @files.uniq if @files
- @extensions = @extensions.uniq if @extensions
- @test_files = @test_files.uniq if @test_files
- @executables = @executables.uniq if @executables
- @extra_rdoc_files = @extra_rdoc_files.uniq if @extra_rdoc_files
- end
-
- ##
- # Returns the full name (name-version) of this gemspec using the original
- # platform. For use with legacy gems.
-
- def original_name # :nodoc:
- if platform == Gem::Platform::RUBY or platform.nil? then
- "#{@name}-#{@version}"
- else
- "#{@name}-#{@version}-#{@original_platform}"
- end
- end
-
- ##
- # Cruft. Use +platform+.
-
- def original_platform # :nodoc:
- @original_platform ||= platform
- end
-
- ##
- # The platform this gem runs on. See Gem::Platform for details.
-
- def platform
- @new_platform ||= Gem::Platform::RUBY
- end
-
- ##
- # The platform this gem runs on. See Gem::Platform for details.
- #
- # Setting this to any value other than Gem::Platform::RUBY or
- # Gem::Platform::CURRENT is probably wrong.
-
- def platform= platform
- if @original_platform.nil? or
- @original_platform == Gem::Platform::RUBY then
- @original_platform = platform
- end
-
- case platform
- when Gem::Platform::CURRENT then
- @new_platform = Gem::Platform.local
- @original_platform = @new_platform.to_s
-
- when Gem::Platform then
- @new_platform = platform
-
- # legacy constants
- when nil, Gem::Platform::RUBY then
- @new_platform = Gem::Platform::RUBY
- when 'mswin32' then # was Gem::Platform::WIN32
- @new_platform = Gem::Platform.new 'x86-mswin32'
- when 'i586-linux' then # was Gem::Platform::LINUX_586
- @new_platform = Gem::Platform.new 'x86-linux'
- when 'powerpc-darwin' then # was Gem::Platform::DARWIN
- @new_platform = Gem::Platform.new 'ppc-darwin'
- else
- @new_platform = Gem::Platform.new platform
- end
-
- @platform = @new_platform.to_s
-
- @new_platform
- end
-
- def pretty_print(q) # :nodoc:
- q.group 2, 'Gem::Specification.new do |s|', 'end' do
- q.breakable
-
- # REFACTOR: each_attr - use in to_yaml as well
- @@attributes.each do |attr_name|
- current_value = self.send attr_name
- if current_value != default_value(attr_name) or
- self.class.required_attribute? attr_name then
-
- q.text "s.#{attr_name} = "
-
- if attr_name == :date then
- current_value = current_value.utc
-
- q.text "Time.utc(#{current_value.year}, #{current_value.month}, #{current_value.day})"
- else
- q.pp current_value
- end
-
- q.breakable
- end
- end
- end
- end
-
- ##
- # Check the spec for possible conflicts and freak out if there are any.
-
- def raise_if_conflicts
- other = Gem.loaded_specs[self.name]
-
- if other and self.version != other.version then
- # This gem is already loaded. If the currently loaded gem is not in the
- # list of candidate gems, then we have a version conflict.
-
- msg = "can't activate #{full_name}, already activated #{other.full_name}"
-
- e = Gem::LoadError.new msg
- e.name = self.name
- # TODO: e.requirement = dep.requirement
-
- raise e
- end
-
- conf = self.conflicts
-
- unless conf.empty? then
- y = conf.map { |act,con|
- "#{act.full_name} conflicts with #{con.join(", ")}"
- }.join ", "
-
- # TODO: improve message by saying who activated `con`
-
- raise Gem::LoadError, "Unable to activate #{self.full_name}, because #{y}"
- end
- end
-
- ##
- # An ARGV style array of options to RDoc
-
- def rdoc_options
- @rdoc_options ||= []
- end
-
- ##
- # Sets rdoc_options to +value+, ensuring it is an array. Don't
- # use this, push onto the array instead.
-
- def rdoc_options= options
- # TODO: warn about setting instead of pushing
- @rdoc_options = Array options
- end
-
- ##
- # Singular accessor for #require_paths
-
- def require_path
- val = require_paths and val.first
- end
-
- ##
- # Singular accessor for #require_paths
-
- def require_path= path
- self.require_paths = [path]
- end
-
- ##
- # The version of ruby required by this gem
-
- def required_ruby_version= req
- @required_ruby_version = Gem::Requirement.create req
- end
-
- ##
- # The RubyGems version required by this gem
-
- def required_rubygems_version= req
- @required_rubygems_version = Gem::Requirement.create req
- end
-
- ##
- # An array or things required by this gem. Not used by anything
- # presently.
-
- def requirements
- @requirements ||= []
- end
-
- ##
- # Set requirements to +req+, ensuring it is an array. Don't
- # use this, push onto the array instead.
-
- def requirements= req
- # TODO: warn about setting instead of pushing
- @requirements = Array req
- end
-
- ##
- # Returns the full path to this spec's ri directory.
-
- def ri_dir
- @ri_dir ||= File.join base_dir, 'ri', full_name
- end
-
- ##
- # Return a string containing a Ruby code representation of the given
- # object.
-
- def ruby_code(obj)
- case obj
- when String then obj.dump
- when Array then '[' + obj.map { |x| ruby_code x }.join(", ") + ']'
- when Gem::Version then obj.to_s.dump
- when Date then obj.strftime('%Y-%m-%d').dump
- when Time then obj.strftime('%Y-%m-%d').dump
- when Numeric then obj.inspect
- when true, false, nil then obj.inspect
- when Gem::Platform then "Gem::Platform.new(#{obj.to_a.inspect})"
- when Gem::Requirement then "Gem::Requirement.new(#{obj.to_s.inspect})"
- else raise Gem::Exception, "ruby_code case not handled: #{obj.class}"
- end
- end
-
- private :ruby_code
-
- ##
- # List of dependencies that will automatically be activated at runtime.
-
- def runtime_dependencies
- dependencies.select { |d| d.type == :runtime }
- end
-
- ##
- # True if this gem has the same attributes as +other+.
-
- def same_attributes? spec
- @@attributes.all? { |name, default| self.send(name) == spec.send(name) }
- end
-
- private :same_attributes?
-
- ##
- # Checks if this specification meets the requirement of +dependency+.
-
- def satisfies_requirement? dependency
- return @name == dependency.name &&
- dependency.requirement.satisfied_by?(@version)
- end
-
- ##
- # Returns an object you can use to sort specifications in #sort_by.
-
- def sort_obj
- # TODO: this is horrible. Deprecate it.
- [@name, @version, @new_platform == Gem::Platform::RUBY ? -1 : 1]
- end
-
- ##
- # Returns the full path to the directory containing this spec's
- # gemspec file. eg: /usr/local/lib/ruby/gems/1.8/specifications
-
- def spec_dir
- @spec_dir ||= File.join base_dir, "specifications"
- end
-
- ##
- # Returns the full path to this spec's gemspec file.
- # eg: /usr/local/lib/ruby/gems/1.8/specifications/mygem-1.0.gemspec
-
- def spec_file
- @spec_file ||= File.join spec_dir, "#{full_name}.gemspec"
- end
-
- ##
- # The default name of the gemspec. See also #file_name
- #
- # spec.spec_name # => "example-1.0.gemspec"
-
- def spec_name
- "#{full_name}.gemspec"
- end
-
- ##
- # A short summary of this gem's description.
-
- def summary= str
- @summary = str.to_s.strip.
- gsub(/(\w-)\n[ \t]*(\w)/, '\1\2').gsub(/\n[ \t]*/, " ") # so. weird.
- end
-
- ##
- # Singular accessor for #test_files
-
- def test_file
- val = test_files and val.first
- end
-
- ##
- # Singular accessor for #test_files
-
- def test_file= file
- self.test_files = [file]
- end
-
- ##
- # Test files included in this gem. You cannot append to this accessor, you
- # must assign to it.
-
- def test_files
- # Handle the possibility that we have @test_suite_file but not
- # @test_files. This will happen when an old gem is loaded via
- # YAML.
- if defined? @test_suite_file then
- @test_files = [@test_suite_file].flatten
- @test_suite_file = nil
- end
- if defined?(@test_files) and @test_files then
- @test_files
- else
- @test_files = []
- end
- end
-
- ##
- # Set test_files to +files+, ensuring it is an array.
-
- def test_files= files
- @test_files = Array files
- end
-
- def test_suite_file # :nodoc:
- # TODO: deprecate
- test_files.first
- end
-
- def test_suite_file= file # :nodoc:
- # TODO: deprecate
- @test_files = [] unless defined? @test_files
- @test_files << file
- end
-
- ##
- # Returns a Ruby code representation of this specification, such that it can
- # be eval'ed and reconstruct the same specification later. Attributes that
- # still have their default values are omitted.
-
- def to_ruby
- mark_version
- result = []
- result << "# -*- encoding: utf-8 -*-"
- result << nil
- result << "Gem::Specification.new do |s|"
-
- result << " s.name = #{ruby_code name}"
- result << " s.version = #{ruby_code version}"
- unless platform.nil? or platform == Gem::Platform::RUBY then
- result << " s.platform = #{ruby_code original_platform}"
- end
- result << ""
- result << " s.required_rubygems_version = #{ruby_code required_rubygems_version} if s.respond_to? :required_rubygems_version="
-
- handled = [
- :dependencies,
- :name,
- :platform,
- :required_rubygems_version,
- :specification_version,
- :version,
- :has_rdoc,
- :default_executable,
- ]
-
- @@attributes.each do |attr_name|
- next if handled.include? attr_name
- current_value = self.send(attr_name)
- if current_value != default_value(attr_name) or
- self.class.required_attribute? attr_name then
- result << " s.#{attr_name} = #{ruby_code current_value}"
- end
- end
-
- result << nil
- result << " if s.respond_to? :specification_version then"
- result << " s.specification_version = #{specification_version}"
- result << nil
-
- result << " if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then"
-
- dependencies.each do |dep|
- req = dep.requirements_list.inspect
- dep.instance_variable_set :@type, :runtime if dep.type.nil? # HACK
- result << " s.add_#{dep.type}_dependency(%q<#{dep.name}>, #{req})"
- end
-
- result << " else"
-
- dependencies.each do |dep|
- version_reqs_param = dep.requirements_list.inspect
- result << " s.add_dependency(%q<#{dep.name}>, #{version_reqs_param})"
- end
-
- result << ' end'
-
- result << " else"
- dependencies.each do |dep|
- version_reqs_param = dep.requirements_list.inspect
- result << " s.add_dependency(%q<#{dep.name}>, #{version_reqs_param})"
- end
- result << " end"
-
- result << "end"
- result << nil
-
- result.join "\n"
- end
-
- ##
- # Returns a Ruby lighter-weight code representation of this specification,
- # used for indexing only.
- #
- # See #to_ruby.
-
- def to_ruby_for_cache
- for_cache.to_ruby
- end
-
- def to_s # :nodoc:
- "#<Gem::Specification name=#{@name} version=#{@version}>"
- end
-
- def to_yaml(opts = {}) # :nodoc:
- if YAML.const_defined?(:ENGINE) && !YAML::ENGINE.syck? then
- # Because the user can switch the YAML engine behind our
- # back, we have to check again here to make sure that our
- # psych code was properly loaded, and load it if not.
- unless Gem.const_defined?(:NoAliasYAMLTree)
- require 'rubygems/psych_tree'
- end
-
- builder = Gem::NoAliasYAMLTree.new({})
- builder << self
- ast = builder.tree
-
- io = StringIO.new
-
- Psych::Visitors::Emitter.new(io).accept(ast)
-
- io.string.gsub(/ !!null \n/, " \n")
- else
- YAML.quick_emit object_id, opts do |out|
- out.map taguri, to_yaml_style do |map|
- encode_with map
- end
- end
- end
- end
-
- ##
- # Recursively walk dependencies of this spec, executing the +block+ for each
- # hop.
-
- def traverse trail = [], &block
- trail = trail + [self]
- runtime_dependencies.each do |dep|
- dep.to_specs.each do |dep_spec|
- block[self, dep, dep_spec, trail + [dep_spec]]
- dep_spec.traverse(trail, &block) unless
- trail.map(&:name).include? dep_spec.name
- end
- end
- end
-
- ##
- # Checks that the specification contains all required fields, and does a
- # very basic sanity check.
- #
- # Raises InvalidSpecificationException if the spec does not pass the
- # checks..
-
- def validate packaging = true
- require 'rubygems/user_interaction'
- extend Gem::UserInteraction
- normalize
-
- nil_attributes = self.class.non_nil_attributes.find_all do |name|
- instance_variable_get("@#{name}").nil?
- end
-
- unless nil_attributes.empty? then
- raise Gem::InvalidSpecificationException,
- "#{nil_attributes.join ', '} must not be nil"
- end
-
- if packaging and rubygems_version != Gem::VERSION then
- raise Gem::InvalidSpecificationException,
- "expected RubyGems version #{Gem::VERSION}, was #{rubygems_version}"
- end
-
- @@required_attributes.each do |symbol|
- unless self.send symbol then
- raise Gem::InvalidSpecificationException,
- "missing value for attribute #{symbol}"
- end
- end
-
- unless String === name then
- raise Gem::InvalidSpecificationException,
- "invalid value for attribute name: \"#{name.inspect}\""
- end
-
- if require_paths.empty? then
- raise Gem::InvalidSpecificationException,
- 'specification must have at least one require_path'
- end
-
- @files.delete_if { |x| File.directory?(x) }
- @test_files.delete_if { |x| File.directory?(x) }
- @executables.delete_if { |x| File.directory?(File.join(@bindir, x)) }
- @extra_rdoc_files.delete_if { |x| File.directory?(x) }
- @extensions.delete_if { |x| File.directory?(x) }
-
- non_files = files.reject { |x| File.file?(x) }
-
- unless not packaging or non_files.empty? then
- raise Gem::InvalidSpecificationException,
- "[\"#{non_files.join "\", \""}\"] are not files"
- end
-
- unless specification_version.is_a?(Fixnum)
- raise Gem::InvalidSpecificationException,
- 'specification_version must be a Fixnum (did you mean version?)'
- end
-
- case platform
- when Gem::Platform, Gem::Platform::RUBY then # ok
- else
- raise Gem::InvalidSpecificationException,
- "invalid platform #{platform.inspect}, see Gem::Platform"
- end
-
- self.class.array_attributes.each do |field|
- val = self.send field
- klass = case field
- when :dependencies
- Gem::Dependency
- else
- String
- end
-
- unless Array === val and val.all? { |x| x.kind_of?(klass) } then
- raise(Gem::InvalidSpecificationException,
- "#{field} must be an Array of #{klass}")
- end
- end
-
- [:authors].each do |field|
- val = self.send field
- raise Gem::InvalidSpecificationException, "#{field} may not be empty" if
- val.empty?
- end
-
- licenses.each { |license|
- if license.length > 64
- raise Gem::InvalidSpecificationException,
- "each license must be 64 characters or less"
- end
- }
-
- # reject lazy developers:
-
- lazy = '"FIxxxXME" or "TOxxxDO"'.gsub(/xxx/, '')
-
- unless authors.grep(/FI XME|TO DO/x).empty? then
- raise Gem::InvalidSpecificationException, "#{lazy} is not an author"
- end
-
- unless Array(email).grep(/FI XME|TO DO/x).empty? then
- raise Gem::InvalidSpecificationException, "#{lazy} is not an email"
- end
-
- if description =~ /FI XME|TO DO/x then
- raise Gem::InvalidSpecificationException, "#{lazy} is not a description"
- end
-
- if summary =~ /FI XME|TO DO/x then
- raise Gem::InvalidSpecificationException, "#{lazy} is not a summary"
- end
-
- if homepage and not homepage.empty? and
- homepage !~ /\A[a-z][a-z\d+.-]*:/i then
- raise Gem::InvalidSpecificationException,
- "\"#{homepage}\" is not a URI"
- end
-
- # Warnings
-
- %w[author description email homepage summary].each do |attribute|
- value = self.send attribute
- alert_warning "no #{attribute} specified" if value.nil? or value.empty?
- end
-
- if description == summary then
- alert_warning 'description and summary are identical'
- end
-
- # TODO: raise at some given date
- alert_warning "deprecated autorequire specified" if autorequire
-
- executables.each do |executable|
- executable_path = File.join(bindir, executable)
- shebang = File.read(executable_path, 2) == '#!'
-
- alert_warning "#{executable_path} is missing #! line" unless shebang
- end
-
- true
- end
-
- ##
- # Set the version to +version+, potentially also setting
- # required_rubygems_version if +version+ indicates it is a
- # prerelease.
-
- def version= version
- @version = Gem::Version.create(version)
- self.required_rubygems_version = '> 1.3.1' if @version.prerelease?
- return @version
- end
-
- # FIX: have this handle the platform/new_platform/original_platform bullshit
- def yaml_initialize(tag, vals) # :nodoc:
- vals.each do |ivar, val|
- case ivar
- when "date"
- # Force Date to go through the extra coerce logic in date=
- self.date = val.untaint
- else
- instance_variable_set "@#{ivar}", val.untaint
- end
- end
-
- @original_platform = @platform # for backwards compatibility
- self.platform = Gem::Platform.new @platform
- end
-
- extend Gem::Deprecate
-
- deprecate :test_suite_file, :test_file, 2011, 10
- deprecate :test_suite_file=, :test_file=, 2011, 10
- deprecate :loaded, :activated, 2011, 10
- deprecate :loaded?, :activated?, 2011, 10
- deprecate :loaded=, :activated=, 2011, 10
- deprecate :installation_path, :base_dir, 2011, 10
- deprecate :cache_gem, :cache_file, 2011, 10
- # TODO:
- # deprecate :has_rdoc, :none, 2011, 10
- # deprecate :has_rdoc?, :none, 2011, 10
- # deprecate :has_rdoc=, :none, 2011, 10
- # deprecate :default_executable, :none, 2011, 10
- # deprecate :default_executable=, :none, 2011, 10
- # deprecate :spec_name, :spec_file, 2011, 10
- # deprecate :file_name, :cache_file, 2011, 10
- # deprecate :full_gem_path, :cache_file, 2011, 10
-end
-
-Gem.clear_paths
-
diff --git a/ruby_1_9_3/lib/rubygems/ssl_certs/ca-bundle.pem b/ruby_1_9_3/lib/rubygems/ssl_certs/ca-bundle.pem
deleted file mode 100644
index b4dac9112f..0000000000
--- a/ruby_1_9_3/lib/rubygems/ssl_certs/ca-bundle.pem
+++ /dev/null
@@ -1,3366 +0,0 @@
-##
-## ca-bundle.crt -- Bundle of CA Root Certificates
-##
-## Certificate data from Mozilla as of: Sun Feb 19 04:03:37 2012
-##
-## This is a bundle of X.509 certificates of public Certificate Authorities
-## (CA). These were automatically extracted from Mozilla's root certificates
-## file (certdata.txt). This file can be found in the mozilla source tree:
-## https://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1
-##
-## It contains the certificates in PEM format and therefore
-## can be directly used with curl / libcurl / php_curl, or with
-## an Apache+mod_ssl webserver for SSL client authentication.
-## Just configure this file as the SSLCACertificateFile.
-##
-
-# ***** BEGIN LICENSE BLOCK *****
-# Version: MPL 1.1/GPL 2.0/LGPL 2.1
-#
-# The contents of this file are subject to the Mozilla Public License Version
-# 1.1 (the "License"); you may not use this file except in compliance with
-# the License. You may obtain a copy of the License at
-# http://www.mozilla.org/MPL/
-#
-# Software distributed under the License is distributed on an "AS IS" basis,
-# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
-# for the specific language governing rights and limitations under the
-# License.
-#
-# The Original Code is the Netscape security libraries.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1994-2000
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-#
-# Alternatively, the contents of this file may be used under the terms of
-# either the GNU General Public License Version 2 or later (the "GPL"), or
-# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
-# in which case the provisions of the GPL or the LGPL are applicable instead
-# of those above. If you wish to allow use of your version of this file only
-# under the terms of either the GPL or the LGPL, and not to allow others to
-# use your version of this file under the terms of the MPL, indicate your
-# decision by deleting the provisions above and replace them with the notice
-# and other provisions required by the GPL or the LGPL. If you do not delete
-# the provisions above, a recipient may use your version of this file under
-# the terms of any one of the MPL, the GPL or the LGPL.
-#
-# ***** END LICENSE BLOCK *****
-# @(#) $RCSfile: certdata.txt,v $ $Revision: 1.82 $ $Date: 2012/02/18 21:41:46 $
-
-GTE CyberTrust Global Root
-==========================
------BEGIN CERTIFICATE-----
-MIICWjCCAcMCAgGlMA0GCSqGSIb3DQEBBAUAMHUxCzAJBgNVBAYTAlVTMRgwFgYDVQQKEw9HVEUg
-Q29ycG9yYXRpb24xJzAlBgNVBAsTHkdURSBDeWJlclRydXN0IFNvbHV0aW9ucywgSW5jLjEjMCEG
-A1UEAxMaR1RFIEN5YmVyVHJ1c3QgR2xvYmFsIFJvb3QwHhcNOTgwODEzMDAyOTAwWhcNMTgwODEz
-MjM1OTAwWjB1MQswCQYDVQQGEwJVUzEYMBYGA1UEChMPR1RFIENvcnBvcmF0aW9uMScwJQYDVQQL
-Ex5HVEUgQ3liZXJUcnVzdCBTb2x1dGlvbnMsIEluYy4xIzAhBgNVBAMTGkdURSBDeWJlclRydXN0
-IEdsb2JhbCBSb290MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCVD6C28FCc6HrHiM3dFw4u
-sJTQGz0O9pTAipTHBsiQl8i4ZBp6fmw8U+E3KHNgf7KXUwefU/ltWJTSr41tiGeA5u2ylc9yMcql
-HHK6XALnZELn+aks1joNrI1CqiQBOeacPwGFVw1Yh0X404Wqk2kmhXBIgD8SFcd5tB8FLztimQID
-AQABMA0GCSqGSIb3DQEBBAUAA4GBAG3rGwnpXtlR22ciYaQqPEh346B8pt5zohQDhT37qw4wxYMW
-M4ETCJ57NE7fQMh017l93PR2VX2bY1QY6fDq81yx2YtCHrnAlU66+tXifPVoYb+O7AWXX1uw16OF
-NMQkpw0PlZPvy5TYnh+dXIVtx6quTx8itc2VrbqnzPmrC3p/
------END CERTIFICATE-----
-
-Thawte Server CA
-================
------BEGIN CERTIFICATE-----
-MIIDEzCCAnygAwIBAgIBATANBgkqhkiG9w0BAQQFADCBxDELMAkGA1UEBhMCWkExFTATBgNVBAgT
-DFdlc3Rlcm4gQ2FwZTESMBAGA1UEBxMJQ2FwZSBUb3duMR0wGwYDVQQKExRUaGF3dGUgQ29uc3Vs
-dGluZyBjYzEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjEZMBcGA1UE
-AxMQVGhhd3RlIFNlcnZlciBDQTEmMCQGCSqGSIb3DQEJARYXc2VydmVyLWNlcnRzQHRoYXd0ZS5j
-b20wHhcNOTYwODAxMDAwMDAwWhcNMjAxMjMxMjM1OTU5WjCBxDELMAkGA1UEBhMCWkExFTATBgNV
-BAgTDFdlc3Rlcm4gQ2FwZTESMBAGA1UEBxMJQ2FwZSBUb3duMR0wGwYDVQQKExRUaGF3dGUgQ29u
-c3VsdGluZyBjYzEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjEZMBcG
-A1UEAxMQVGhhd3RlIFNlcnZlciBDQTEmMCQGCSqGSIb3DQEJARYXc2VydmVyLWNlcnRzQHRoYXd0
-ZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANOkUG7I/1Zr5s9dtuoMaHVHoqrC2oQl
-/Kj0R1HahbUgdJSGHg91yekIYfUGbTBuFRkC6VLAYttNmZ7iagxEOM3+vuNkCXDF/rFrKbYvScg7
-1CcEJRCXL+eQbcAoQpnXTEPew/UhbVSfXcNY4cDk2VuwuNy0e982OsK1ZiIS1ocNAgMBAAGjEzAR
-MA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEEBQADgYEAB/pMaVz7lcxG7oWDTSEwjsrZqG9J
-GubaUeNgcGyEYRGhGshIPllDfU+VPaGLtwtimHp1it2ITk6eQNuozDJ0uW8NxuOzRAvZim+aKZuZ
-GCg70eNAKJpaPNW15yAbi8qkq43pUdniTCxZqdq5snUb9kLy78fyGPmJvKP/iiMucEc=
------END CERTIFICATE-----
-
-Thawte Premium Server CA
-========================
------BEGIN CERTIFICATE-----
-MIIDJzCCApCgAwIBAgIBATANBgkqhkiG9w0BAQQFADCBzjELMAkGA1UEBhMCWkExFTATBgNVBAgT
-DFdlc3Rlcm4gQ2FwZTESMBAGA1UEBxMJQ2FwZSBUb3duMR0wGwYDVQQKExRUaGF3dGUgQ29uc3Vs
-dGluZyBjYzEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjEhMB8GA1UE
-AxMYVGhhd3RlIFByZW1pdW0gU2VydmVyIENBMSgwJgYJKoZIhvcNAQkBFhlwcmVtaXVtLXNlcnZl
-ckB0aGF3dGUuY29tMB4XDTk2MDgwMTAwMDAwMFoXDTIwMTIzMTIzNTk1OVowgc4xCzAJBgNVBAYT
-AlpBMRUwEwYDVQQIEwxXZXN0ZXJuIENhcGUxEjAQBgNVBAcTCUNhcGUgVG93bjEdMBsGA1UEChMU
-VGhhd3RlIENvbnN1bHRpbmcgY2MxKDAmBgNVBAsTH0NlcnRpZmljYXRpb24gU2VydmljZXMgRGl2
-aXNpb24xITAfBgNVBAMTGFRoYXd0ZSBQcmVtaXVtIFNlcnZlciBDQTEoMCYGCSqGSIb3DQEJARYZ
-cHJlbWl1bS1zZXJ2ZXJAdGhhd3RlLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA0jY2
-aovXwlue2oFBYo847kkEVdbQ7xwblRZH7xhINTpS9CtqBo87L+pW46+GjZ4X9560ZXUCTe/LCaIh
-Udib0GfQug2SBhRz1JPLlyoAnFxODLz6FVL88kRu2hFKbgifLy3j+ao6hnO2RlNYyIkFvYMRuHM/
-qgeN9EJN50CdHDcCAwEAAaMTMBEwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQQFAAOBgQAm
-SCwWwlj66BZ0DKqqX1Q/8tfJeGBeXm43YyJ3Nn6yF8Q0ufUIhfzJATj/Tb7yFkJD57taRvvBxhEf
-8UqwKEbJw8RCfbz6q1lu1bdRiBHjpIUZa4JMpAwSremkrj/xw0llmozFyD4lt5SZu5IycQfwhl7t
-UCemDaYj+bvLpgcUQg==
------END CERTIFICATE-----
-
-Equifax Secure CA
-=================
------BEGIN CERTIFICATE-----
-MIIDIDCCAomgAwIBAgIENd70zzANBgkqhkiG9w0BAQUFADBOMQswCQYDVQQGEwJVUzEQMA4GA1UE
-ChMHRXF1aWZheDEtMCsGA1UECxMkRXF1aWZheCBTZWN1cmUgQ2VydGlmaWNhdGUgQXV0aG9yaXR5
-MB4XDTk4MDgyMjE2NDE1MVoXDTE4MDgyMjE2NDE1MVowTjELMAkGA1UEBhMCVVMxEDAOBgNVBAoT
-B0VxdWlmYXgxLTArBgNVBAsTJEVxdWlmYXggU2VjdXJlIENlcnRpZmljYXRlIEF1dGhvcml0eTCB
-nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAwV2xWGcIYu6gmi0fCG2RFGiYCh7+2gRvE4RiIcPR
-fM6fBeC4AfBONOziipUEZKzxa1NfBbPLZ4C/QgKO/t0BCezhABRP/PvwDN1Dulsr4R+AcJkVV5MW
-8Q+XarfCaCMczE1ZMKxRHjuvK9buY0V7xdlfUNLjUA86iOe/FP3gx7kCAwEAAaOCAQkwggEFMHAG
-A1UdHwRpMGcwZaBjoGGkXzBdMQswCQYDVQQGEwJVUzEQMA4GA1UEChMHRXF1aWZheDEtMCsGA1UE
-CxMkRXF1aWZheCBTZWN1cmUgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MQ0wCwYDVQQDEwRDUkwxMBoG
-A1UdEAQTMBGBDzIwMTgwODIyMTY0MTUxWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAUSOZo+SvS
-spXXR9gjIBBPM5iQn9QwHQYDVR0OBBYEFEjmaPkr0rKV10fYIyAQTzOYkJ/UMAwGA1UdEwQFMAMB
-Af8wGgYJKoZIhvZ9B0EABA0wCxsFVjMuMGMDAgbAMA0GCSqGSIb3DQEBBQUAA4GBAFjOKer89961
-zgK5F7WF0bnj4JXMJTENAKaSbn+2kmOeUJXRmm/kEd5jhW6Y7qj/WsjTVbJmcVfewCHrPSqnI0kB
-BIZCe/zuf6IWUrVnZ9NA2zsmWLIodz2uFHdh1voqZiegDfqnc1zqcPGUIWVEX/r87yloqaKHee95
-70+sB3c4
------END CERTIFICATE-----
-
-Digital Signature Trust Co. Global CA 1
-=======================================
------BEGIN CERTIFICATE-----
-MIIDKTCCApKgAwIBAgIENnAVljANBgkqhkiG9w0BAQUFADBGMQswCQYDVQQGEwJVUzEkMCIGA1UE
-ChMbRGlnaXRhbCBTaWduYXR1cmUgVHJ1c3QgQ28uMREwDwYDVQQLEwhEU1RDQSBFMTAeFw05ODEy
-MTAxODEwMjNaFw0xODEyMTAxODQwMjNaMEYxCzAJBgNVBAYTAlVTMSQwIgYDVQQKExtEaWdpdGFs
-IFNpZ25hdHVyZSBUcnVzdCBDby4xETAPBgNVBAsTCERTVENBIEUxMIGdMA0GCSqGSIb3DQEBAQUA
-A4GLADCBhwKBgQCgbIGpzzQeJN3+hijM3oMv+V7UQtLodGBmE5gGHKlREmlvMVW5SXIACH7TpWJE
-NySZj9mDSI+ZbZUTu0M7LklOiDfBu1h//uG9+LthzfNHwJmm8fOR6Hh8AMthyUQncWlVSn5JTe2i
-o74CTADKAqjuAQIxZA9SLRN0dja1erQtcQIBA6OCASQwggEgMBEGCWCGSAGG+EIBAQQEAwIABzBo
-BgNVHR8EYTBfMF2gW6BZpFcwVTELMAkGA1UEBhMCVVMxJDAiBgNVBAoTG0RpZ2l0YWwgU2lnbmF0
-dXJlIFRydXN0IENvLjERMA8GA1UECxMIRFNUQ0EgRTExDTALBgNVBAMTBENSTDEwKwYDVR0QBCQw
-IoAPMTk5ODEyMTAxODEwMjNagQ8yMDE4MTIxMDE4MTAyM1owCwYDVR0PBAQDAgEGMB8GA1UdIwQY
-MBaAFGp5fpFpRhgTCgJ3pVlbYJglDqL4MB0GA1UdDgQWBBRqeX6RaUYYEwoCd6VZW2CYJQ6i+DAM
-BgNVHRMEBTADAQH/MBkGCSqGSIb2fQdBAAQMMAobBFY0LjADAgSQMA0GCSqGSIb3DQEBBQUAA4GB
-ACIS2Hod3IEGtgllsofIH160L+nEHvI8wbsEkBFKg05+k7lNQseSJqBcNJo4cvj9axY+IO6CizEq
-kzaFI4iKPANo08kJD038bKTaKHKTDomAsH3+gG9lbRgzl4vCa4nuYD3Im+9/KzJic5PLPON74nZ4
-RbyhkwS7hp86W0N6w4pl
------END CERTIFICATE-----
-
-Digital Signature Trust Co. Global CA 3
-=======================================
------BEGIN CERTIFICATE-----
-MIIDKTCCApKgAwIBAgIENm7TzjANBgkqhkiG9w0BAQUFADBGMQswCQYDVQQGEwJVUzEkMCIGA1UE
-ChMbRGlnaXRhbCBTaWduYXR1cmUgVHJ1c3QgQ28uMREwDwYDVQQLEwhEU1RDQSBFMjAeFw05ODEy
-MDkxOTE3MjZaFw0xODEyMDkxOTQ3MjZaMEYxCzAJBgNVBAYTAlVTMSQwIgYDVQQKExtEaWdpdGFs
-IFNpZ25hdHVyZSBUcnVzdCBDby4xETAPBgNVBAsTCERTVENBIEUyMIGdMA0GCSqGSIb3DQEBAQUA
-A4GLADCBhwKBgQC/k48Xku8zExjrEH9OFr//Bo8qhbxe+SSmJIi2A7fBw18DW9Fvrn5C6mYjuGOD
-VvsoLeE4i7TuqAHhzhy2iCoiRoX7n6dwqUcUP87eZfCocfdPJmyMvMa1795JJ/9IKn3oTQPMx7JS
-xhcxEzu1TdvIxPbDDyQq2gyd55FbgM2UnQIBA6OCASQwggEgMBEGCWCGSAGG+EIBAQQEAwIABzBo
-BgNVHR8EYTBfMF2gW6BZpFcwVTELMAkGA1UEBhMCVVMxJDAiBgNVBAoTG0RpZ2l0YWwgU2lnbmF0
-dXJlIFRydXN0IENvLjERMA8GA1UECxMIRFNUQ0EgRTIxDTALBgNVBAMTBENSTDEwKwYDVR0QBCQw
-IoAPMTk5ODEyMDkxOTE3MjZagQ8yMDE4MTIwOTE5MTcyNlowCwYDVR0PBAQDAgEGMB8GA1UdIwQY
-MBaAFB6CTShlgDzJQW6sNS5ay97u+DlbMB0GA1UdDgQWBBQegk0oZYA8yUFurDUuWsve7vg5WzAM
-BgNVHRMEBTADAQH/MBkGCSqGSIb2fQdBAAQMMAobBFY0LjADAgSQMA0GCSqGSIb3DQEBBQUAA4GB
-AEeNg61i8tuwnkUiBbmi1gMOOHLnnvx75pO2mqWilMg0HZHRxdf0CiUPPXiBng+xZ8SQTGPdXqfi
-up/1902lMXucKS1M/mQ+7LZT/uqb7YLbdHVLB3luHtgZg3Pe9T7Qtd7nS2h9Qy4qIOF+oHhEngj1
-mPnHfxsb1gYgAlihw6ID
------END CERTIFICATE-----
-
-Verisign Class 3 Public Primary Certification Authority
-=======================================================
------BEGIN CERTIFICATE-----
-MIICPDCCAaUCEHC65B0Q2Sk0tjjKewPMur8wDQYJKoZIhvcNAQECBQAwXzELMAkGA1UEBhMCVVMx
-FzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFzcyAzIFB1YmxpYyBQcmltYXJ5
-IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTk2MDEyOTAwMDAwMFoXDTI4MDgwMTIzNTk1OVow
-XzELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFzcyAz
-IFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIGfMA0GCSqGSIb3DQEBAQUA
-A4GNADCBiQKBgQDJXFme8huKARS0EN8EQNvjV69qRUCPhAwL0TPZ2RHP7gJYHyX3KqhEBarsAx94
-f56TuZoAqiN91qyFomNFx3InzPRMxnVx0jnvT0Lwdd8KkMaOIG+YD/isI19wKTakyYbnsZogy1Ol
-hec9vn2a/iRFM9x2Fe0PonFkTGUugWhFpwIDAQABMA0GCSqGSIb3DQEBAgUAA4GBALtMEivPLCYA
-TxQT3ab7/AoRhIzzKBxnki98tsX63/Dolbwdj2wsqFHMc9ikwFPwTtYmwHYBV4GSXiHx0bH/59Ah
-WM1pF+NEHJwZRDmJXNycAA9WjQKZ7aKQRUzkuxCkPfAyAw7xzvjoyVGM5mKf5p/AfbdynMk2Omuf
-Tqj/ZA1k
------END CERTIFICATE-----
-
-Verisign Class 3 Public Primary Certification Authority - G2
-============================================================
------BEGIN CERTIFICATE-----
-MIIDAjCCAmsCEH3Z/gfPqB63EHln+6eJNMYwDQYJKoZIhvcNAQEFBQAwgcExCzAJBgNVBAYTAlVT
-MRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5jLjE8MDoGA1UECxMzQ2xhc3MgMyBQdWJsaWMgUHJpbWFy
-eSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEcyMTowOAYDVQQLEzEoYykgMTk5OCBWZXJpU2ln
-biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MR8wHQYDVQQLExZWZXJpU2lnbiBUcnVz
-dCBOZXR3b3JrMB4XDTk4MDUxODAwMDAwMFoXDTI4MDgwMTIzNTk1OVowgcExCzAJBgNVBAYTAlVT
-MRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5jLjE8MDoGA1UECxMzQ2xhc3MgMyBQdWJsaWMgUHJpbWFy
-eSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEcyMTowOAYDVQQLEzEoYykgMTk5OCBWZXJpU2ln
-biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MR8wHQYDVQQLExZWZXJpU2lnbiBUcnVz
-dCBOZXR3b3JrMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDMXtERXVxp0KvTuWpMmR9ZmDCO
-FoUgRm1HP9SFIIThbbP4pO0M8RcPO/mn+SXXwc+EY/J8Y8+iR/LGWzOOZEAEaMGAuWQcRXfH2G71
-lSk8UOg013gfqLptQ5GVj0VXXn7F+8qkBOvqlzdUMG+7AUcyM83cV5tkaWH4mx0ciU9cZwIDAQAB
-MA0GCSqGSIb3DQEBBQUAA4GBAFFNzb5cy5gZnBWyATl4Lk0PZ3BwmcYQWpSkU01UbSuvDV1Ai2TT
-1+7eVmGSX6bEHRBhNtMsJzzoKQm5EWR0zLVznxxIqbxhAe7iF6YM40AIOw7n60RzKprxaZLvcRTD
-Oaxxp5EJb+RxBrO6WVcmeQD2+A2iMzAo1KpYoJ2daZH9
------END CERTIFICATE-----
-
-GlobalSign Root CA
-==================
------BEGIN CERTIFICATE-----
-MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx
-GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds
-b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV
-BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD
-VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa
-DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc
-THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb
-Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP
-c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX
-gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV
-HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF
-AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj
-Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG
-j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH
-hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC
-X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==
------END CERTIFICATE-----
-
-GlobalSign Root CA - R2
-=======================
------BEGIN CERTIFICATE-----
-MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEgMB4GA1UECxMXR2xv
-YmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkdsb2JhbFNpZ24xEzARBgNVBAMTCkdsb2Jh
-bFNpZ24wHhcNMDYxMjE1MDgwMDAwWhcNMjExMjE1MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxT
-aWduIFJvb3QgQ0EgLSBSMjETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2ln
-bjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8omUVCxKs+IVSbC9N/hHD6
-ErPLv4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe+3t+c4isUoh7SqbKSaZeqKeMWhG8eoLrvozp
-s6yWJQeXSpkqBy+0Hne/ig+1AnwblrjFuTosvNYSuetZfeLQBoZfXklqtTleiDTsvHgMCJiEbKjN
-S7SgfQx5TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzdC9XZzPnqJworc5HGnRusyMvo4KD0L5CL
-TfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pazq+r1feqCapgvdzZX99yqWATXgAByUr6P6TqBwMhAo6C
-ygPCm48CAwEAAaOBnDCBmTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E
-FgQUm+IHV2ccHsBqBt5ZtJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5nbG9i
-YWxzaWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG3lm0mi3f3BmGLjAN
-BgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4GsJ0/WwbgcQ3izDJr86iw8bmEbTUsp
-9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4h4hO291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu
-01yiPqFbQfXf5WRDLenVOavSot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG7
-9G+dwfCMNYxdAfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmgQWpzU/qlULRuJQ/7
-TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq/H5COEBkEveegeGTLg==
------END CERTIFICATE-----
-
-ValiCert Class 1 VA
-===================
------BEGIN CERTIFICATE-----
-MIIC5zCCAlACAQEwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRp
-b24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENs
-YXNzIDEgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZh
-bGljZXJ0LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTk5MDYyNTIy
-MjM0OFoXDTE5MDYyNTIyMjM0OFowgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRpb24gTmV0
-d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENsYXNzIDEg
-UG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0
-LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMIGfMA0GCSqGSIb3DQEBAQUA
-A4GNADCBiQKBgQDYWYJ6ibiWuqYvaG9YLqdUHAZu9OqNSLwxlBfw8068srg1knaw0KWlAdcAAxIi
-GQj4/xEjm84H9b9pGib+TunRf50sQB1ZaG6m+FiwnRqP0z/x3BkGgagO4DrdyFNFCQbmD3DD+kCm
-DuJWBQ8YTfwggtFzVXSNdnKgHZ0dwN0/cQIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAFBoPUn0LBwG
-lN+VYH+Wexf+T3GtZMjdd9LvWVXoP+iOBSoh8gfStadS/pyxtuJbdxdA6nLWI8sogTLDAHkY7FkX
-icnGah5xyf23dKUlRWnFSKsZ4UWKJWsZ7uW7EvV/96aNUcPwnXS3qT6gpf+2SQMT2iLM7XGCK5nP
-Orf1LXLI
------END CERTIFICATE-----
-
-ValiCert Class 2 VA
-===================
------BEGIN CERTIFICATE-----
-MIIC5zCCAlACAQEwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRp
-b24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENs
-YXNzIDIgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZh
-bGljZXJ0LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTk5MDYyNjAw
-MTk1NFoXDTE5MDYyNjAwMTk1NFowgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRpb24gTmV0
-d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENsYXNzIDIg
-UG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0
-LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMIGfMA0GCSqGSIb3DQEBAQUA
-A4GNADCBiQKBgQDOOnHK5avIWZJV16vYdA757tn2VUdZZUcOBVXc65g2PFxTXdMwzzjsvUGJ7SVC
-CSRrCl6zfN1SLUzm1NZ9WlmpZdRJEy0kTRxQb7XBhVQ7/nHk01xC+YDgkRoKWzk2Z/M/VXwbP7Rf
-ZHM047QSv4dk+NoS/zcnwbNDu+97bi5p9wIDAQABMA0GCSqGSIb3DQEBBQUAA4GBADt/UG9vUJSZ
-SWI4OB9L+KXIPqeCgfYrx+jFzug6EILLGACOTb2oWH+heQC1u+mNr0HZDzTuIYEZoDJJKPTEjlbV
-UjP9UNV+mWwD5MlM/Mtsq2azSiGM5bUMMj4QssxsodyamEwCW/POuZ6lcg5Ktz885hZo+L7tdEy8
-W9ViH0Pd
------END CERTIFICATE-----
-
-RSA Root Certificate 1
-======================
------BEGIN CERTIFICATE-----
-MIIC5zCCAlACAQEwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRp
-b24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENs
-YXNzIDMgUG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZh
-bGljZXJ0LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTk5MDYyNjAw
-MjIzM1oXDTE5MDYyNjAwMjIzM1owgbsxJDAiBgNVBAcTG1ZhbGlDZXJ0IFZhbGlkYXRpb24gTmV0
-d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIEluYy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENsYXNzIDMg
-UG9saWN5IFZhbGlkYXRpb24gQXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0
-LmNvbS8xIDAeBgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMIGfMA0GCSqGSIb3DQEBAQUA
-A4GNADCBiQKBgQDjmFGWHOjVsQaBalfDcnWTq8+epvzzFlLWLU2fNUSoLgRNB0mKOCn1dzfnt6td
-3zZxFJmP3MKS8edgkpfs2Ejcv8ECIMYkpChMMFp2bbFc893enhBxoYjHW5tBbcqwuI4V7q0zK89H
-BFx1cQqYJJgpp0lZpd34t0NiYfPT4tBVPwIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAFa7AliEZwgs
-3x/be0kz9dNnnfS0ChCzycUs4pJqcXgn8nCDQtM+z6lU9PHYkhaM0QTLS6vJn0WuPIqpsHEzXcjF
-V9+vqDWzf4mH6eglkrh/hXqu1rweN1gqZ8mRzyqBPu3GOd/APhmcGcwTTYJBtYze4D1gCCAPRX5r
-on+jjBXu
------END CERTIFICATE-----
-
-Verisign Class 3 Public Primary Certification Authority - G3
-============================================================
------BEGIN CERTIFICATE-----
-MIIEGjCCAwICEQCbfgZJoz5iudXukEhxKe9XMA0GCSqGSIb3DQEBBQUAMIHKMQswCQYDVQQGEwJV
-UzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdv
-cmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl
-IG9ubHkxRTBDBgNVBAMTPFZlcmlTaWduIENsYXNzIDMgUHVibGljIFByaW1hcnkgQ2VydGlmaWNh
-dGlvbiBBdXRob3JpdHkgLSBHMzAeFw05OTEwMDEwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMIHKMQsw
-CQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRy
-dXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhv
-cml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMTPFZlcmlTaWduIENsYXNzIDMgUHVibGljIFByaW1hcnkg
-Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
-ggEBAMu6nFL8eB8aHm8bN3O9+MlrlBIwT/A2R/XQkQr1F8ilYcEWQE37imGQ5XYgwREGfassbqb1
-EUGO+i2tKmFZpGcmTNDovFJbcCAEWNF6yaRpvIMXZK0Fi7zQWM6NjPXr8EJJC52XJ2cybuGukxUc
-cLwgTS8Y3pKI6GyFVxEa6X7jJhFUokWWVYPKMIno3Nij7SqAP395ZVc+FSBmCC+Vk7+qRy+oRpfw
-EuL+wgorUeZ25rdGt+INpsyow0xZVYnm6FNcHOqd8GIWC6fJXwzw3sJ2zq/3avL6QaaiMxTJ5Xpj
-055iN9WFZZ4O5lMkdBteHRJTW8cs54NJOxWuimi5V5cCAwEAATANBgkqhkiG9w0BAQUFAAOCAQEA
-ERSWwauSCPc/L8my/uRan2Te2yFPhpk0djZX3dAVL8WtfxUfN2JzPtTnX84XA9s1+ivbrmAJXx5f
-j267Cz3qWhMeDGBvtcC1IyIuBwvLqXTLR7sdwdela8wv0kL9Sd2nic9TutoAWii/gt/4uhMdUIaC
-/Y4wjylGsB49Ndo4YhYYSq3mtlFs3q9i6wHQHiT+eo8SGhJouPtmmRQURVyu565pF4ErWjfJXir0
-xuKhXFSbplQAz/DxwceYMBo7Nhbbo27q/a2ywtrvAkcTisDxszGtTxzhT5yvDwyd93gN2PQ1VoDa
-t20Xj50egWTh/sVFuq1ruQp6Tk9LhO5L8X3dEQ==
------END CERTIFICATE-----
-
-Verisign Class 4 Public Primary Certification Authority - G3
-============================================================
------BEGIN CERTIFICATE-----
-MIIEGjCCAwICEQDsoKeLbnVqAc/EfMwvlF7XMA0GCSqGSIb3DQEBBQUAMIHKMQswCQYDVQQGEwJV
-UzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdv
-cmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl
-IG9ubHkxRTBDBgNVBAMTPFZlcmlTaWduIENsYXNzIDQgUHVibGljIFByaW1hcnkgQ2VydGlmaWNh
-dGlvbiBBdXRob3JpdHkgLSBHMzAeFw05OTEwMDEwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMIHKMQsw
-CQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRy
-dXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhv
-cml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMTPFZlcmlTaWduIENsYXNzIDQgUHVibGljIFByaW1hcnkg
-Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
-ggEBAK3LpRFpxlmr8Y+1GQ9Wzsy1HyDkniYlS+BzZYlZ3tCD5PUPtbut8XzoIfzk6AzufEUiGXaS
-tBO3IFsJ+mGuqPKljYXCKtbeZjbSmwL0qJJgfJxptI8kHtCGUvYynEFYHiK9zUVilQhu0GbdU6LM
-8BDcVHOLBKFGMzNcF0C5nk3T875Vg+ixiY5afJqWIpA7iCXy0lOIAgwLePLmNxdLMEYH5IBtptiW
-Lugs+BGzOA1mppvqySNb247i8xOOGlktqgLw7KSHZtzBP/XYufTsgsbSPZUd5cBPhMnZo0QoBmrX
-Razwa2rvTl/4EYIeOGM0ZlDUPpNz+jDDZq3/ky2X7wMCAwEAATANBgkqhkiG9w0BAQUFAAOCAQEA
-j/ola09b5KROJ1WrIhVZPMq1CtRK26vdoV9TxaBXOcLORyu+OshWv8LZJxA6sQU8wHcxuzrTBXtt
-mhwwjIDLk5Mqg6sFUYICABFna/OIYUdfA5PVWw3g8dShMjWFsjrbsIKr0csKvE+MW8VLADsfKoKm
-fjaF3H48ZwC15DtS4KjrXRX5xm3wrR0OhbepmnMUWluPQSjA1egtTaRezarZ7c7c2NU8Qh0XwRJd
-RTjDOPP8hS6DRkiy1yBfkjaP53kPmF6Z6PDQpLv1U70qzlmwr25/bLvSHgCwIe34QWKCudiyxLtG
-UPMxxY8BqHTr9Xgn2uf3ZkPznoM+IKrDNWCRzg==
------END CERTIFICATE-----
-
-Entrust.net Secure Server CA
-============================
------BEGIN CERTIFICATE-----
-MIIE2DCCBEGgAwIBAgIEN0rSQzANBgkqhkiG9w0BAQUFADCBwzELMAkGA1UEBhMCVVMxFDASBgNV
-BAoTC0VudHJ1c3QubmV0MTswOQYDVQQLEzJ3d3cuZW50cnVzdC5uZXQvQ1BTIGluY29ycC4gYnkg
-cmVmLiAobGltaXRzIGxpYWIuKTElMCMGA1UECxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRl
-ZDE6MDgGA1UEAxMxRW50cnVzdC5uZXQgU2VjdXJlIFNlcnZlciBDZXJ0aWZpY2F0aW9uIEF1dGhv
-cml0eTAeFw05OTA1MjUxNjA5NDBaFw0xOTA1MjUxNjM5NDBaMIHDMQswCQYDVQQGEwJVUzEUMBIG
-A1UEChMLRW50cnVzdC5uZXQxOzA5BgNVBAsTMnd3dy5lbnRydXN0Lm5ldC9DUFMgaW5jb3JwLiBi
-eSByZWYuIChsaW1pdHMgbGlhYi4pMSUwIwYDVQQLExwoYykgMTk5OSBFbnRydXN0Lm5ldCBMaW1p
-dGVkMTowOAYDVQQDEzFFbnRydXN0Lm5ldCBTZWN1cmUgU2VydmVyIENlcnRpZmljYXRpb24gQXV0
-aG9yaXR5MIGdMA0GCSqGSIb3DQEBAQUAA4GLADCBhwKBgQDNKIM0VBuJ8w+vN5Ex/68xYMmo6LIQ
-aO2f55M28Qpku0f1BBc/I0dNxScZgSYMVHINiC3ZH5oSn7yzcdOAGT9HZnuMNSjSuQrfJNqc1lB5
-gXpa0zf3wkrYKZImZNHkmGw6AIr1NJtl+O3jEP/9uElY3KDegjlrgbEWGWG5VLbmQwIBA6OCAdcw
-ggHTMBEGCWCGSAGG+EIBAQQEAwIABzCCARkGA1UdHwSCARAwggEMMIHeoIHboIHYpIHVMIHSMQsw
-CQYDVQQGEwJVUzEUMBIGA1UEChMLRW50cnVzdC5uZXQxOzA5BgNVBAsTMnd3dy5lbnRydXN0Lm5l
-dC9DUFMgaW5jb3JwLiBieSByZWYuIChsaW1pdHMgbGlhYi4pMSUwIwYDVQQLExwoYykgMTk5OSBF
-bnRydXN0Lm5ldCBMaW1pdGVkMTowOAYDVQQDEzFFbnRydXN0Lm5ldCBTZWN1cmUgU2VydmVyIENl
-cnRpZmljYXRpb24gQXV0aG9yaXR5MQ0wCwYDVQQDEwRDUkwxMCmgJ6AlhiNodHRwOi8vd3d3LmVu
-dHJ1c3QubmV0L0NSTC9uZXQxLmNybDArBgNVHRAEJDAigA8xOTk5MDUyNTE2MDk0MFqBDzIwMTkw
-NTI1MTYwOTQwWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAU8BdiE1U9s/8KAGv7UISX8+1i0Bow
-HQYDVR0OBBYEFPAXYhNVPbP/CgBr+1CEl/PtYtAaMAwGA1UdEwQFMAMBAf8wGQYJKoZIhvZ9B0EA
-BAwwChsEVjQuMAMCBJAwDQYJKoZIhvcNAQEFBQADgYEAkNwwAvpkdMKnCqV8IY00F6j7Rw7/JXyN
-Ewr75Ji174z4xRAN95K+8cPV1ZVqBLssziY2ZcgxxufuP+NXdYR6Ee9GTxj005i7qIcyunL2POI9
-n9cd2cNgQ4xYDiKWL2KjLB+6rQXvqzJ4h6BUcxm1XAX5Uj5tLUUL9wqT6u0G+bI=
------END CERTIFICATE-----
-
-Entrust.net Premium 2048 Secure Server CA
-=========================================
------BEGIN CERTIFICATE-----
-MIIEXDCCA0SgAwIBAgIEOGO5ZjANBgkqhkiG9w0BAQUFADCBtDEUMBIGA1UEChMLRW50cnVzdC5u
-ZXQxQDA+BgNVBAsUN3d3dy5lbnRydXN0Lm5ldC9DUFNfMjA0OCBpbmNvcnAuIGJ5IHJlZi4gKGxp
-bWl0cyBsaWFiLikxJTAjBgNVBAsTHChjKSAxOTk5IEVudHJ1c3QubmV0IExpbWl0ZWQxMzAxBgNV
-BAMTKkVudHJ1c3QubmV0IENlcnRpZmljYXRpb24gQXV0aG9yaXR5ICgyMDQ4KTAeFw05OTEyMjQx
-NzUwNTFaFw0xOTEyMjQxODIwNTFaMIG0MRQwEgYDVQQKEwtFbnRydXN0Lm5ldDFAMD4GA1UECxQ3
-d3d3LmVudHJ1c3QubmV0L0NQU18yMDQ4IGluY29ycC4gYnkgcmVmLiAobGltaXRzIGxpYWIuKTEl
-MCMGA1UECxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEGA1UEAxMqRW50cnVzdC5u
-ZXQgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgKDIwNDgpMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A
-MIIBCgKCAQEArU1LqRKGsuqjIAcVFmQqK0vRvwtKTY7tgHalZ7d4QMBzQshowNtTK91euHaYNZOL
-Gp18EzoOH1u3Hs/lJBQesYGpjX24zGtLA/ECDNyrpUAkAH90lKGdCCmziAv1h3edVc3kw37XamSr
-hRSGlVuXMlBvPci6Zgzj/L24ScF2iUkZ/cCovYmjZy/Gn7xxGWC4LeksyZB2ZnuU4q941mVTXTzW
-nLLPKQP5L6RQstRIzgUyVYr9smRMDuSYB3Xbf9+5CFVghTAp+XtIpGmG4zU/HoZdenoVve8AjhUi
-VBcAkCaTvA5JaJG/+EfTnZVCwQ5N328mz8MYIWJmQ3DW1cAH4QIDAQABo3QwcjARBglghkgBhvhC
-AQEEBAMCAAcwHwYDVR0jBBgwFoAUVeSB0RGAvtiJuQijMfmhJAkWuXAwHQYDVR0OBBYEFFXkgdER
-gL7YibkIozH5oSQJFrlwMB0GCSqGSIb2fQdBAAQQMA4bCFY1LjA6NC4wAwIEkDANBgkqhkiG9w0B
-AQUFAAOCAQEAWUesIYSKF8mciVMeuoCFGsY8Tj6xnLZ8xpJdGGQC49MGCBFhfGPjK50xA3B20qMo
-oPS7mmNz7W3lKtvtFKkrxjYR0CvrB4ul2p5cGZ1WEvVUKcgF7bISKo30Axv/55IQh7A6tcOdBTcS
-o8f0FbnVpDkWm1M6I5HxqIKiaohowXkCIryqptau37AUX7iH0N18f3v/rxzP5tsHrV7bhZ3QKw0z
-2wTR5klAEyt2+z7pnIkPFc4YsIV4IU9rTw76NmfNB/L/CNDi3tm/Kq+4h4YhPATKt5Rof8886ZjX
-OP/swNlQ8C5LWK5Gb9Auw2DaclVyvUxFnmG6v4SBkgPR0ml8xQ==
------END CERTIFICATE-----
-
-Baltimore CyberTrust Root
-=========================
------BEGIN CERTIFICATE-----
-MIIDdzCCAl+gAwIBAgIEAgAAuTANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJJRTESMBAGA1UE
-ChMJQmFsdGltb3JlMRMwEQYDVQQLEwpDeWJlclRydXN0MSIwIAYDVQQDExlCYWx0aW1vcmUgQ3li
-ZXJUcnVzdCBSb290MB4XDTAwMDUxMjE4NDYwMFoXDTI1MDUxMjIzNTkwMFowWjELMAkGA1UEBhMC
-SUUxEjAQBgNVBAoTCUJhbHRpbW9yZTETMBEGA1UECxMKQ3liZXJUcnVzdDEiMCAGA1UEAxMZQmFs
-dGltb3JlIEN5YmVyVHJ1c3QgUm9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKME
-uyKrmD1X6CZymrV51Cni4eiVgLGw41uOKymaZN+hXe2wCQVt2yguzmKiYv60iNoS6zjrIZ3AQSsB
-UnuId9Mcj8e6uYi1agnnc+gRQKfRzMpijS3ljwumUNKoUMMo6vWrJYeKmpYcqWe4PwzV9/lSEy/C
-G9VwcPCPwBLKBsua4dnKM3p31vjsufFoREJIE9LAwqSuXmD+tqYF/LTdB1kC1FkYmGP1pWPgkAx9
-XbIGevOF6uvUA65ehD5f/xXtabz5OTZydc93Uk3zyZAsuT3lySNTPx8kmCFcB5kpvcY67Oduhjpr
-l3RjM71oGDHweI12v/yejl0qhqdNkNwnGjkCAwEAAaNFMEMwHQYDVR0OBBYEFOWdWTCCR1jMrPoI
-VDaGezq1BE3wMBIGA1UdEwEB/wQIMAYBAf8CAQMwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEB
-BQUAA4IBAQCFDF2O5G9RaEIFoN27TyclhAO992T9Ldcw46QQF+vaKSm2eT929hkTI7gQCvlYpNRh
-cL0EYWoSihfVCr3FvDB81ukMJY2GQE/szKN+OMY3EU/t3WgxjkzSswF07r51XgdIGn9w/xZchMB5
-hbgF/X++ZRGjD8ACtPhSNzkE1akxehi/oCr0Epn3o0WC4zxe9Z2etciefC7IpJ5OCBRLbf1wbWsa
-Y71k5h+3zvDyny67G7fyUIhzksLi4xaNmjICq44Y3ekQEe5+NauQrz4wlHrQMz2nZQ/1/I6eYs9H
-RCwBXbsdtTLSR9I4LtD+gdwyah617jzV/OeBHRnDJELqYzmp
------END CERTIFICATE-----
-
-Equifax Secure Global eBusiness CA
-==================================
------BEGIN CERTIFICATE-----
-MIICkDCCAfmgAwIBAgIBATANBgkqhkiG9w0BAQQFADBaMQswCQYDVQQGEwJVUzEcMBoGA1UEChMT
-RXF1aWZheCBTZWN1cmUgSW5jLjEtMCsGA1UEAxMkRXF1aWZheCBTZWN1cmUgR2xvYmFsIGVCdXNp
-bmVzcyBDQS0xMB4XDTk5MDYyMTA0MDAwMFoXDTIwMDYyMTA0MDAwMFowWjELMAkGA1UEBhMCVVMx
-HDAaBgNVBAoTE0VxdWlmYXggU2VjdXJlIEluYy4xLTArBgNVBAMTJEVxdWlmYXggU2VjdXJlIEds
-b2JhbCBlQnVzaW5lc3MgQ0EtMTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAuucXkAJlsTRV
-PEnCUdXfp9E3j9HngXNBUmCbnaEXJnitx7HoJpQytd4zjTov2/KaelpzmKNc6fuKcxtc58O/gGzN
-qfTWK8D3+ZmqY6KxRwIP1ORROhI8bIpaVIRw28HFkM9yRcuoWcDNM50/o5brhTMhHD4ePmBudpxn
-hcXIw2ECAwEAAaNmMGQwEQYJYIZIAYb4QgEBBAQDAgAHMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0j
-BBgwFoAUvqigdHJQa0S3ySPY+6j/s1draGwwHQYDVR0OBBYEFL6ooHRyUGtEt8kj2Puo/7NXa2hs
-MA0GCSqGSIb3DQEBBAUAA4GBADDiAVGqx+pf2rnQZQ8w1j7aDRRJbpGTJxQx78T3LUX47Me/okEN
-I7SS+RkAZ70Br83gcfxaz2TE4JaY0KNA4gGK7ycH8WUBikQtBmV1UsCGECAhX2xrD2yuCRyv8qIY
-NMR1pHMc8Y3c7635s3a0kr/clRAevsvIO1qEYBlWlKlV
------END CERTIFICATE-----
-
-Equifax Secure eBusiness CA 1
-=============================
------BEGIN CERTIFICATE-----
-MIICgjCCAeugAwIBAgIBBDANBgkqhkiG9w0BAQQFADBTMQswCQYDVQQGEwJVUzEcMBoGA1UEChMT
-RXF1aWZheCBTZWN1cmUgSW5jLjEmMCQGA1UEAxMdRXF1aWZheCBTZWN1cmUgZUJ1c2luZXNzIENB
-LTEwHhcNOTkwNjIxMDQwMDAwWhcNMjAwNjIxMDQwMDAwWjBTMQswCQYDVQQGEwJVUzEcMBoGA1UE
-ChMTRXF1aWZheCBTZWN1cmUgSW5jLjEmMCQGA1UEAxMdRXF1aWZheCBTZWN1cmUgZUJ1c2luZXNz
-IENBLTEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAM4vGbwXt3fek6lfWg0XTzQaDJj0ItlZ
-1MRoRvC0NcWFAyDGr0WlIVFFQesWWDYyb+JQYmT5/VGcqiTZ9J2DKocKIdMSODRsjQBuWqDZQu4a
-IZX5UkxVWsUPOE9G+m34LjXWHXzr4vCwdYDIqROsvojvOm6rXyo4YgKwEnv+j6YDAgMBAAGjZjBk
-MBEGCWCGSAGG+EIBAQQEAwIABzAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFEp4MlIR21kW
-Nl7fwRQ2QGpHfEyhMB0GA1UdDgQWBBRKeDJSEdtZFjZe38EUNkBqR3xMoTANBgkqhkiG9w0BAQQF
-AAOBgQB1W6ibAxHm6VZMzfmpTMANmvPMZWnmJXbMWbfWVMMdzZmsGd20hdXgPfxiIKeES1hl8eL5
-lSE/9dR+WB5Hh1Q+WKG1tfgq73HnvMP2sUlG4tega+VWeponmHxGYhTnyfxuAxJ5gDgdSIKN/Bf+
-KpYrtWKmpj29f5JZzVoqgrI3eQ==
------END CERTIFICATE-----
-
-Equifax Secure eBusiness CA 2
-=============================
------BEGIN CERTIFICATE-----
-MIIDIDCCAomgAwIBAgIEN3DPtTANBgkqhkiG9w0BAQUFADBOMQswCQYDVQQGEwJVUzEXMBUGA1UE
-ChMORXF1aWZheCBTZWN1cmUxJjAkBgNVBAsTHUVxdWlmYXggU2VjdXJlIGVCdXNpbmVzcyBDQS0y
-MB4XDTk5MDYyMzEyMTQ0NVoXDTE5MDYyMzEyMTQ0NVowTjELMAkGA1UEBhMCVVMxFzAVBgNVBAoT
-DkVxdWlmYXggU2VjdXJlMSYwJAYDVQQLEx1FcXVpZmF4IFNlY3VyZSBlQnVzaW5lc3MgQ0EtMjCB
-nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA5Dk5kx5SBhsoNviyoynF7Y6yEb3+6+e0dMKP/wXn
-2Z0GvxLIPw7y1tEkshHe0XMJitSxLJgJDR5QRrKDpkWNYmi7hRsgcDKqQM2mll/EcTc/BPO3QSQ5
-BxoeLmFYoBIL5aXfxavqN3HMHMg3OrmXUqesxWoklE6ce8/AatbfIb0CAwEAAaOCAQkwggEFMHAG
-A1UdHwRpMGcwZaBjoGGkXzBdMQswCQYDVQQGEwJVUzEXMBUGA1UEChMORXF1aWZheCBTZWN1cmUx
-JjAkBgNVBAsTHUVxdWlmYXggU2VjdXJlIGVCdXNpbmVzcyBDQS0yMQ0wCwYDVQQDEwRDUkwxMBoG
-A1UdEAQTMBGBDzIwMTkwNjIzMTIxNDQ1WjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAUUJ4L6q9e
-uSBIplBqy/3YIHqngnYwHQYDVR0OBBYEFFCeC+qvXrkgSKZQasv92CB6p4J2MAwGA1UdEwQFMAMB
-Af8wGgYJKoZIhvZ9B0EABA0wCxsFVjMuMGMDAgbAMA0GCSqGSIb3DQEBBQUAA4GBAAyGgq3oThr1
-jokn4jVYPSm0B482UJW/bsGe68SQsoWou7dC4A8HOd/7npCy0cE+U58DRLB+S/Rv5Hwf5+Kx5Lia
-78O9zt4LMjTZ3ijtM2vE1Nc9ElirfQkty3D1E4qUoSek1nDFbZS1yX2doNLGCEnZZpum0/QL3MUm
-V+GRMOrN
------END CERTIFICATE-----
-
-AddTrust Low-Value Services Root
-================================
------BEGIN CERTIFICATE-----
-MIIEGDCCAwCgAwIBAgIBATANBgkqhkiG9w0BAQUFADBlMQswCQYDVQQGEwJTRTEUMBIGA1UEChML
-QWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3b3JrMSEwHwYDVQQDExhBZGRU
-cnVzdCBDbGFzcyAxIENBIFJvb3QwHhcNMDAwNTMwMTAzODMxWhcNMjAwNTMwMTAzODMxWjBlMQsw
-CQYDVQQGEwJTRTEUMBIGA1UEChMLQWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBO
-ZXR3b3JrMSEwHwYDVQQDExhBZGRUcnVzdCBDbGFzcyAxIENBIFJvb3QwggEiMA0GCSqGSIb3DQEB
-AQUAA4IBDwAwggEKAoIBAQCWltQhSWDia+hBBwzexODcEyPNwTXH+9ZOEQpnXvUGW2ulCDtbKRY6
-54eyNAbFvAWlA3yCyykQruGIgb3WntP+LVbBFc7jJp0VLhD7Bo8wBN6ntGO0/7Gcrjyvd7ZWxbWr
-oulpOj0OM3kyP3CCkplhbY0wCI9xP6ZIVxn4JdxLZlyldI+Yrsj5wAYi56xz36Uu+1LcsRVlIPo1
-Zmne3yzxbrww2ywkEtvrNTVokMsAsJchPXQhI2U0K7t4WaPW4XY5mqRJjox0r26kmqPZm9I4XJui
-GMx1I4S+6+JNM3GOGvDC+Mcdoq0Dlyz4zyXG9rgkMbFjXZJ/Y/AlyVMuH79NAgMBAAGjgdIwgc8w
-HQYDVR0OBBYEFJWxtPCUtr3H2tERCSG+wa9J/RB7MAsGA1UdDwQEAwIBBjAPBgNVHRMBAf8EBTAD
-AQH/MIGPBgNVHSMEgYcwgYSAFJWxtPCUtr3H2tERCSG+wa9J/RB7oWmkZzBlMQswCQYDVQQGEwJT
-RTEUMBIGA1UEChMLQWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3b3JrMSEw
-HwYDVQQDExhBZGRUcnVzdCBDbGFzcyAxIENBIFJvb3SCAQEwDQYJKoZIhvcNAQEFBQADggEBACxt
-ZBsfzQ3duQH6lmM0MkhHma6X7f1yFqZzR1r0693p9db7RcwpiURdv0Y5PejuvE1Uhh4dbOMXJ0Ph
-iVYrqW9yTkkz43J8KiOavD7/KCrto/8cI7pDVwlnTUtiBi34/2ydYB7YHEt9tTEv2dB8Xfjea4MY
-eDdXL+gzB2ffHsdrKpV2ro9Xo/D0UrSpUwjP4E/TelOL/bscVjby/rK25Xa71SJlpz/+0WatC7xr
-mYbvP33zGDLKe8bjq2RGlfgmadlVg3sslgf/WSxEo8bl6ancoWOAWiFeIc9TVPC6b4nbqKqVz4vj
-ccweGyBECMB6tkD9xOQ14R0WHNC8K47Wcdk=
------END CERTIFICATE-----
-
-AddTrust External Root
-======================
------BEGIN CERTIFICATE-----
-MIIENjCCAx6gAwIBAgIBATANBgkqhkiG9w0BAQUFADBvMQswCQYDVQQGEwJTRTEUMBIGA1UEChML
-QWRkVHJ1c3QgQUIxJjAkBgNVBAsTHUFkZFRydXN0IEV4dGVybmFsIFRUUCBOZXR3b3JrMSIwIAYD
-VQQDExlBZGRUcnVzdCBFeHRlcm5hbCBDQSBSb290MB4XDTAwMDUzMDEwNDgzOFoXDTIwMDUzMDEw
-NDgzOFowbzELMAkGA1UEBhMCU0UxFDASBgNVBAoTC0FkZFRydXN0IEFCMSYwJAYDVQQLEx1BZGRU
-cnVzdCBFeHRlcm5hbCBUVFAgTmV0d29yazEiMCAGA1UEAxMZQWRkVHJ1c3QgRXh0ZXJuYWwgQ0Eg
-Um9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALf3GjPm8gAELTngTlvtH7xsD821
-+iO2zt6bETOXpClMfZOfvUq8k+0DGuOPz+VtUFrWlymUWoCwSXrbLpX9uMq/NzgtHj6RQa1wVsfw
-Tz/oMp50ysiQVOnGXw94nZpAPA6sYapeFI+eh6FqUNzXmk6vBbOmcZSccbNQYArHE504B4YCqOmo
-aSYYkKtMsE8jqzpPhNjfzp/haW+710LXa0Tkx63ubUFfclpxCDezeWWkWaCUN/cALw3CknLa0Dhy
-2xSoRcRdKn23tNbE7qzNE0S3ySvdQwAl+mG5aWpYIxG3pzOPVnVZ9c0p10a3CitlttNCbxWyuHv7
-7+ldU9U0WicCAwEAAaOB3DCB2TAdBgNVHQ4EFgQUrb2YejS0Jvf6xCZU7wO94CTLVBowCwYDVR0P
-BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wgZkGA1UdIwSBkTCBjoAUrb2YejS0Jvf6xCZU7wO94CTL
-VBqhc6RxMG8xCzAJBgNVBAYTAlNFMRQwEgYDVQQKEwtBZGRUcnVzdCBBQjEmMCQGA1UECxMdQWRk
-VHJ1c3QgRXh0ZXJuYWwgVFRQIE5ldHdvcmsxIjAgBgNVBAMTGUFkZFRydXN0IEV4dGVybmFsIENB
-IFJvb3SCAQEwDQYJKoZIhvcNAQEFBQADggEBALCb4IUlwtYj4g+WBpKdQZic2YR5gdkeWxQHIzZl
-j7DYd7usQWxHYINRsPkyPef89iYTx4AWpb9a/IfPeHmJIZriTAcKhjW88t5RxNKWt9x+Tu5w/Rw5
-6wwCURQtjr0W4MHfRnXnJK3s9EK0hZNwEGe6nQY1ShjTK3rMUUKhemPR5ruhxSvCNr4TDea9Y355
-e6cJDUCrat2PisP29owaQgVR1EX1n6diIWgVIEM8med8vSTYqZEXc4g/VhsxOBi0cQ+azcgOno4u
-G+GMmIPLHzHxREzGBHNJdmAPx/i9F4BrLunMTA5amnkPIAou1Z5jJh5VkpTYghdae9C8x49OhgQ=
------END CERTIFICATE-----
-
-AddTrust Public Services Root
-=============================
------BEGIN CERTIFICATE-----
-MIIEFTCCAv2gAwIBAgIBATANBgkqhkiG9w0BAQUFADBkMQswCQYDVQQGEwJTRTEUMBIGA1UEChML
-QWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3b3JrMSAwHgYDVQQDExdBZGRU
-cnVzdCBQdWJsaWMgQ0EgUm9vdDAeFw0wMDA1MzAxMDQxNTBaFw0yMDA1MzAxMDQxNTBaMGQxCzAJ
-BgNVBAYTAlNFMRQwEgYDVQQKEwtBZGRUcnVzdCBBQjEdMBsGA1UECxMUQWRkVHJ1c3QgVFRQIE5l
-dHdvcmsxIDAeBgNVBAMTF0FkZFRydXN0IFB1YmxpYyBDQSBSb290MIIBIjANBgkqhkiG9w0BAQEF
-AAOCAQ8AMIIBCgKCAQEA6Rowj4OIFMEg2Dybjxt+A3S72mnTRqX4jsIMEZBRpS9mVEBV6tsfSlbu
-nyNu9DnLoblv8n75XYcmYZ4c+OLspoH4IcUkzBEMP9smcnrHAZcHF/nXGCwwfQ56HmIexkvA/X1i
-d9NEHif2P0tEs7c42TkfYNVRknMDtABp4/MUTu7R3AnPdzRGULD4EfL+OHn3Bzn+UZKXC1sIXzSG
-Aa2Il+tmzV7R/9x98oTaunet3IAIx6eH1lWfl2royBFkuucZKT8Rs3iQhCBSWxHveNCD9tVIkNAw
-HM+A+WD+eeSI8t0A65RF62WUaUC6wNW0uLp9BBGo6zEFlpROWCGOn9Bg/QIDAQABo4HRMIHOMB0G
-A1UdDgQWBBSBPjfYkrAfd59ctKtzquf2NGAv+jALBgNVHQ8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB
-/zCBjgYDVR0jBIGGMIGDgBSBPjfYkrAfd59ctKtzquf2NGAv+qFopGYwZDELMAkGA1UEBhMCU0Ux
-FDASBgNVBAoTC0FkZFRydXN0IEFCMR0wGwYDVQQLExRBZGRUcnVzdCBUVFAgTmV0d29yazEgMB4G
-A1UEAxMXQWRkVHJ1c3QgUHVibGljIENBIFJvb3SCAQEwDQYJKoZIhvcNAQEFBQADggEBAAP3FUr4
-JNojVhaTdt02KLmuG7jD8WS6IBh4lSknVwW8fCr0uVFV2ocC3g8WFzH4qnkuCRO7r7IgGRLlk/lL
-+YPoRNWyQSW/iHVv/xD8SlTQX/D67zZzfRs2RcYhbbQVuE7PnFylPVoAjgbjPGsye/Kf8Lb93/Ao
-GEjwxrzQvzSAlsJKsW2Ox5BF3i9nrEUEo3rcVZLJR2bYGozH7ZxOmuASu7VqTITh4SINhwBk/ox9
-Yjllpu9CtoAlEmEBqCQTcAARJl/6NVDFSMwGR+gn2HCNX2TmoUQmXiLsks3/QppEIW1cxeMiHV9H
-EufOX1362KqxMy3ZdvJOOjMMK7MtkAY=
------END CERTIFICATE-----
-
-AddTrust Qualified Certificates Root
-====================================
------BEGIN CERTIFICATE-----
-MIIEHjCCAwagAwIBAgIBATANBgkqhkiG9w0BAQUFADBnMQswCQYDVQQGEwJTRTEUMBIGA1UEChML
-QWRkVHJ1c3QgQUIxHTAbBgNVBAsTFEFkZFRydXN0IFRUUCBOZXR3b3JrMSMwIQYDVQQDExpBZGRU
-cnVzdCBRdWFsaWZpZWQgQ0EgUm9vdDAeFw0wMDA1MzAxMDQ0NTBaFw0yMDA1MzAxMDQ0NTBaMGcx
-CzAJBgNVBAYTAlNFMRQwEgYDVQQKEwtBZGRUcnVzdCBBQjEdMBsGA1UECxMUQWRkVHJ1c3QgVFRQ
-IE5ldHdvcmsxIzAhBgNVBAMTGkFkZFRydXN0IFF1YWxpZmllZCBDQSBSb290MIIBIjANBgkqhkiG
-9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5B6a/twJWoekn0e+EV+vhDTbYjx5eLfpMLXsDBwqxBb/4Oxx
-64r1EW7tTw2R0hIYLUkVAcKkIhPHEWT/IhKauY5cLwjPcWqzZwFZ8V1G87B4pfYOQnrjfxvM0PC3
-KP0q6p6zsLkEqv32x7SxuCqg+1jxGaBvcCV+PmlKfw8i2O+tCBGaKZnhqkRFmhJePp1tUvznoD1o
-L/BLcHwTOK28FSXx1s6rosAx1i+f4P8UWfyEk9mHfExUE+uf0S0R+Bg6Ot4l2ffTQO2kBhLEO+GR
-wVY18BTcZTYJbqukB8c10cIDMzZbdSZtQvESa0NvS3GU+jQd7RNuyoB/mC9suWXY6QIDAQABo4HU
-MIHRMB0GA1UdDgQWBBQ5lYtii1zJ1IC6WA+XPxUIQ8yYpzALBgNVHQ8EBAMCAQYwDwYDVR0TAQH/
-BAUwAwEB/zCBkQYDVR0jBIGJMIGGgBQ5lYtii1zJ1IC6WA+XPxUIQ8yYp6FrpGkwZzELMAkGA1UE
-BhMCU0UxFDASBgNVBAoTC0FkZFRydXN0IEFCMR0wGwYDVQQLExRBZGRUcnVzdCBUVFAgTmV0d29y
-azEjMCEGA1UEAxMaQWRkVHJ1c3QgUXVhbGlmaWVkIENBIFJvb3SCAQEwDQYJKoZIhvcNAQEFBQAD
-ggEBABmrder4i2VhlRO6aQTvhsoToMeqT2QbPxj2qC0sVY8FtzDqQmodwCVRLae/DLPt7wh/bDxG
-GuoYQ992zPlmhpwsaPXpF/gxsxjE1kh9I0xowX67ARRvxdlu3rsEQmr49lx95dr6h+sNNVJn0J6X
-dgWTP5XHAeZpVTh/EGGZyeNfpso+gmNIquIISD6q8rKFYqa0p9m9N5xotS1WfbC3P6CxB9bpT9ze
-RXEwMn8bLgn5v1Kh7sKAPgZcLlVAwRv1cEWw3F369nJad9Jjzc9YiQBCYz95OdBEsIJuQRno3eDB
-iFrRHnGTHyQwdOUeqN48Jzd/g66ed8/wMLH/S5noxqE=
------END CERTIFICATE-----
-
-Entrust Root Certification Authority
-====================================
------BEGIN CERTIFICATE-----
-MIIEkTCCA3mgAwIBAgIERWtQVDANBgkqhkiG9w0BAQUFADCBsDELMAkGA1UEBhMCVVMxFjAUBgNV
-BAoTDUVudHJ1c3QsIEluYy4xOTA3BgNVBAsTMHd3dy5lbnRydXN0Lm5ldC9DUFMgaXMgaW5jb3Jw
-b3JhdGVkIGJ5IHJlZmVyZW5jZTEfMB0GA1UECxMWKGMpIDIwMDYgRW50cnVzdCwgSW5jLjEtMCsG
-A1UEAxMkRW50cnVzdCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA2MTEyNzIwMjM0
-MloXDTI2MTEyNzIwNTM0MlowgbAxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1FbnRydXN0LCBJbmMu
-MTkwNwYDVQQLEzB3d3cuZW50cnVzdC5uZXQvQ1BTIGlzIGluY29ycG9yYXRlZCBieSByZWZlcmVu
-Y2UxHzAdBgNVBAsTFihjKSAyMDA2IEVudHJ1c3QsIEluYy4xLTArBgNVBAMTJEVudHJ1c3QgUm9v
-dCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
-ALaVtkNC+sZtKm9I35RMOVcF7sN5EUFoNu3s/poBj6E4KPz3EEZmLk0eGrEaTsbRwJWIsMn/MYsz
-A9u3g3s+IIRe7bJWKKf44LlAcTfFy0cOlypowCKVYhXbR9n10Cv/gkvJrT7eTNuQgFA/CYqEAOww
-Cj0Yzfv9KlmaI5UXLEWeH25DeW0MXJj+SKfFI0dcXv1u5x609mhF0YaDW6KKjbHjKYD+JXGIrb68
-j6xSlkuqUY3kEzEZ6E5Nn9uss2rVvDlUccp6en+Q3X0dgNmBu1kmwhH+5pPi94DkZfs0Nw4pgHBN
-rziGLp5/V6+eF67rHMsoIV+2HNjnogQi+dPa2MsCAwEAAaOBsDCBrTAOBgNVHQ8BAf8EBAMCAQYw
-DwYDVR0TAQH/BAUwAwEB/zArBgNVHRAEJDAigA8yMDA2MTEyNzIwMjM0MlqBDzIwMjYxMTI3MjA1
-MzQyWjAfBgNVHSMEGDAWgBRokORnpKZTgMeGZqTx90tD+4S9bTAdBgNVHQ4EFgQUaJDkZ6SmU4DH
-hmak8fdLQ/uEvW0wHQYJKoZIhvZ9B0EABBAwDhsIVjcuMTo0LjADAgSQMA0GCSqGSIb3DQEBBQUA
-A4IBAQCT1DCw1wMgKtD5Y+iRDAUgqV8ZyntyTtSx29CW+1RaGSwMCPeyvIWonX9tO1KzKtvn1ISM
-Y/YPyyYBkVBs9F8U4pN0wBOeMDpQ47RgxRzwIkSNcUesyBrJ6ZuaAGAT/3B+XxFNSRuzFVJ7yVTa
-v52Vr2ua2J7p8eRDjeIRRDq/r72DQnNSi6q7pynP9WQcCk3RvKqsnyrQ/39/2n3qse0wJcGE2jTS
-W3iDVuycNsMm4hH2Z0kdkquM++v/eu6FSqdQgPCnXEqULl8FmTxSQeDNtGPPAUO6nIPcj2A781q0
-tHuu2guQOHXvgR1m0vdXcDazv/wor3ElhVsT/h5/WrQ8
------END CERTIFICATE-----
-
-RSA Security 2048 v3
-====================
------BEGIN CERTIFICATE-----
-MIIDYTCCAkmgAwIBAgIQCgEBAQAAAnwAAAAKAAAAAjANBgkqhkiG9w0BAQUFADA6MRkwFwYDVQQK
-ExBSU0EgU2VjdXJpdHkgSW5jMR0wGwYDVQQLExRSU0EgU2VjdXJpdHkgMjA0OCBWMzAeFw0wMTAy
-MjIyMDM5MjNaFw0yNjAyMjIyMDM5MjNaMDoxGTAXBgNVBAoTEFJTQSBTZWN1cml0eSBJbmMxHTAb
-BgNVBAsTFFJTQSBTZWN1cml0eSAyMDQ4IFYzMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC
-AQEAt49VcdKA3XtpeafwGFAyPGJn9gqVB93mG/Oe2dJBVGutn3y+Gc37RqtBaB4Y6lXIL5F4iSj7
-Jylg/9+PjDvJSZu1pJTOAeo+tWN7fyb9Gd3AIb2E0S1PRsNO3Ng3OTsor8udGuorryGlwSMiuLgb
-WhOHV4PR8CDn6E8jQrAApX2J6elhc5SYcSa8LWrg903w8bYqODGBDSnhAMFRD0xS+ARaqn1y07iH
-KrtjEAMqs6FPDVpeRrc9DvV07Jmf+T0kgYim3WBU6JU2PcYJk5qjEoAAVZkZR73QpXzDuvsf9/UP
-+Ky5tfQ3mBMY3oVbtwyCO4dvlTlYMNpuAWgXIszACwIDAQABo2MwYTAPBgNVHRMBAf8EBTADAQH/
-MA4GA1UdDwEB/wQEAwIBBjAfBgNVHSMEGDAWgBQHw1EwpKrpRa41JPr/JCwz0LGdjDAdBgNVHQ4E
-FgQUB8NRMKSq6UWuNST6/yQsM9CxnYwwDQYJKoZIhvcNAQEFBQADggEBAF8+hnZuuDU8TjYcHnmY
-v/3VEhF5Ug7uMYm83X/50cYVIeiKAVQNOvtUudZj1LGqlk2iQk3UUx+LEN5/Zb5gEydxiKRz44Rj
-0aRV4VCT5hsOedBnvEbIvz8XDZXmxpBp3ue0L96VfdASPz0+f00/FGj1EVDVwfSQpQgdMWD/YIwj
-VAqv/qFuxdF6Kmh4zx6CCiC0H63lhbJqaHVOrSU3lIW+vaHU6rcMSzyd6BIA8F+sDeGscGNz9395
-nzIlQnQFgCi/vcEkllgVsRch6YlL2weIZ/QVrXA+L02FO8K32/6YaCOJ4XQP3vTFhGMpG8zLB8kA
-pKnXwiJPZ9d37CAFYd4=
------END CERTIFICATE-----
-
-GeoTrust Global CA
-==================
------BEGIN CERTIFICATE-----
-MIIDVDCCAjygAwIBAgIDAjRWMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVTMRYwFAYDVQQK
-Ew1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9iYWwgQ0EwHhcNMDIwNTIxMDQw
-MDAwWhcNMjIwNTIxMDQwMDAwWjBCMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5j
-LjEbMBkGA1UEAxMSR2VvVHJ1c3QgR2xvYmFsIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
-CgKCAQEA2swYYzD99BcjGlZ+W988bDjkcbd4kdS8odhM+KhDtgPpTSEHCIjaWC9mOSm9BXiLnTjo
-BbdqfnGk5sRgprDvgOSJKA+eJdbtg/OtppHHmMlCGDUUna2YRpIuT8rxh0PBFpVXLVDviS2Aelet
-8u5fa9IAjbkU+BQVNdnARqN7csiRv8lVK83Qlz6cJmTM386DGXHKTubU1XupGc1V3sjs0l44U+Vc
-T4wt/lAjNvxm5suOpDkZALeVAjmRCw7+OC7RHQWa9k0+bw8HHa8sHo9gOeL6NlMTOdReJivbPagU
-vTLrGAMoUgRx5aszPeE4uwc2hGKceeoWMPRfwCvocWvk+QIDAQABo1MwUTAPBgNVHRMBAf8EBTAD
-AQH/MB0GA1UdDgQWBBTAephojYn7qwVkDBF9qn1luMrMTjAfBgNVHSMEGDAWgBTAephojYn7qwVk
-DBF9qn1luMrMTjANBgkqhkiG9w0BAQUFAAOCAQEANeMpauUvXVSOKVCUn5kaFOSPeCpilKInZ57Q
-zxpeR+nBsqTP3UEaBU6bS+5Kb1VSsyShNwrrZHYqLizz/Tt1kL/6cdjHPTfStQWVYrmm3ok9Nns4
-d0iXrKYgjy6myQzCsplFAMfOEVEiIuCl6rYVSAlk6l5PdPcFPseKUgzbFbS9bZvlxrFUaKnjaZC2
-mqUPuLk/IH2uSrW4nOQdtqvmlKXBx4Ot2/Unhw4EbNX/3aBd7YdStysVAq45pmp06drE57xNNB6p
-XE0zX5IJL4hmXXeXxx12E6nV5fEWCRE11azbJHFwLJhWC9kXtNHjUStedejV0NxPNO3CBWaAocvm
-Mw==
------END CERTIFICATE-----
-
-GeoTrust Global CA 2
-====================
------BEGIN CERTIFICATE-----
-MIIDZjCCAk6gAwIBAgIBATANBgkqhkiG9w0BAQUFADBEMQswCQYDVQQGEwJVUzEWMBQGA1UEChMN
-R2VvVHJ1c3QgSW5jLjEdMBsGA1UEAxMUR2VvVHJ1c3QgR2xvYmFsIENBIDIwHhcNMDQwMzA0MDUw
-MDAwWhcNMTkwMzA0MDUwMDAwWjBEMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5j
-LjEdMBsGA1UEAxMUR2VvVHJ1c3QgR2xvYmFsIENBIDIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
-ggEKAoIBAQDvPE1APRDfO1MA4Wf+lGAVPoWI8YkNkMgoI5kF6CsgncbzYEbYwbLVjDHZ3CB5JIG/
-NTL8Y2nbsSpr7iFY8gjpeMtvy/wWUsiRxP89c96xPqfCfWbB9X5SJBri1WeR0IIQ13hLTytCOb1k
-LUCgsBDTOEhGiKEMuzozKmKY+wCdE1l/bztyqu6mD4b5BWHqZ38MN5aL5mkWRxHCJ1kDs6ZgwiFA
-Vvqgx306E+PsV8ez1q6diYD3Aecs9pYrEw15LNnA5IZ7S4wMcoKK+xfNAGw6EzywhIdLFnopsk/b
-HdQL82Y3vdj2V7teJHq4PIu5+pIaGoSe2HSPqht/XvT+RSIhAgMBAAGjYzBhMA8GA1UdEwEB/wQF
-MAMBAf8wHQYDVR0OBBYEFHE4NvICMVNHK266ZUapEBVYIAUJMB8GA1UdIwQYMBaAFHE4NvICMVNH
-K266ZUapEBVYIAUJMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQUFAAOCAQEAA/e1K6tdEPx7
-srJerJsOflN4WT5CBP51o62sgU7XAotexC3IUnbHLB/8gTKY0UvGkpMzNTEv/NgdRN3ggX+d6Yvh
-ZJFiCzkIjKx0nVnZellSlxG5FntvRdOW2TF9AjYPnDtuzywNA0ZF66D0f0hExghAzN4bcLUprbqL
-OzRldRtxIR0sFAqwlpW41uryZfspuk/qkZN0abby/+Ea0AzRdoXLiiW9l14sbxWZJue2Kf8i7MkC
-x1YAzUm5s2x7UwQa4qjJqhIFI8LO57sEAszAR6LkxCkvW0VXiVHuPOtSCP8HNR6fNWpHSlaY0VqF
-H4z1Ir+rzoPz4iIprn2DQKi6bA==
------END CERTIFICATE-----
-
-GeoTrust Universal CA
-=====================
------BEGIN CERTIFICATE-----
-MIIFaDCCA1CgAwIBAgIBATANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJVUzEWMBQGA1UEChMN
-R2VvVHJ1c3QgSW5jLjEeMBwGA1UEAxMVR2VvVHJ1c3QgVW5pdmVyc2FsIENBMB4XDTA0MDMwNDA1
-MDAwMFoXDTI5MDMwNDA1MDAwMFowRTELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IElu
-Yy4xHjAcBgNVBAMTFUdlb1RydXN0IFVuaXZlcnNhbCBDQTCCAiIwDQYJKoZIhvcNAQEBBQADggIP
-ADCCAgoCggIBAKYVVaCjxuAfjJ0hUNfBvitbtaSeodlyWL0AG0y/YckUHUWCq8YdgNY96xCcOq9t
-JPi8cQGeBvV8Xx7BDlXKg5pZMK4ZyzBIle0iN430SppyZj6tlcDgFgDgEB8rMQ7XlFTTQjOgNB0e
-RXbdT8oYN+yFFXoZCPzVx5zw8qkuEKmS5j1YPakWaDwvdSEYfyh3peFhF7em6fgemdtzbvQKoiFs
-7tqqhZJmr/Z6a4LauiIINQ/PQvE1+mrufislzDoR5G2vc7J2Ha3QsnhnGqQ5HFELZ1aD/ThdDc7d
-8Lsrlh/eezJS/R27tQahsiFepdaVaH/wmZ7cRQg+59IJDTWU3YBOU5fXtQlEIGQWFwMCTFMNaN7V
-qnJNk22CDtucvc+081xdVHppCZbW2xHBjXWotM85yM48vCR85mLK4b19p71XZQvk/iXttmkQ3Cga
-Rr0BHdCXteGYO8A3ZNY9lO4L4fUorgtWv3GLIylBjobFS1J72HGrH4oVpjuDWtdYAVHGTEHZf9hB
-Z3KiKN9gg6meyHv8U3NyWfWTehd2Ds735VzZC1U0oqpbtWpU5xPKV+yXbfReBi9Fi1jUIxaS5BZu
-KGNZMN9QAZxjiRqf2xeUgnA3wySemkfWWspOqGmJch+RbNt+nhutxx9z3SxPGWX9f5NAEC7S8O08
-ni4oPmkmM8V7AgMBAAGjYzBhMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFNq7LqqwDLiIJlF0
-XG0D08DYj3rWMB8GA1UdIwQYMBaAFNq7LqqwDLiIJlF0XG0D08DYj3rWMA4GA1UdDwEB/wQEAwIB
-hjANBgkqhkiG9w0BAQUFAAOCAgEAMXjmx7XfuJRAyXHEqDXsRh3ChfMoWIawC/yOsjmPRFWrZIRc
-aanQmjg8+uUfNeVE44B5lGiku8SfPeE0zTBGi1QrlaXv9z+ZhP015s8xxtxqv6fXIwjhmF7DWgh2
-qaavdy+3YL1ERmrvl/9zlcGO6JP7/TG37FcREUWbMPEaiDnBTzynANXH/KttgCJwpQzgXQQpAvvL
-oJHRfNbDflDVnVi+QTjruXU8FdmbyUqDWcDaU/0zuzYYm4UPFd3uLax2k7nZAY1IEKj79TiG8dsK
-xr2EoyNB3tZ3b4XUhRxQ4K5RirqNPnbiucon8l+f725ZDQbYKxek0nxru18UGkiPGkzns0ccjkxF
-KyDuSN/n3QmOGKjaQI2SJhFTYXNd673nxE0pN2HrrDktZy4W1vUAg4WhzH92xH3kt0tm7wNFYGm2
-DFKWkoRepqO1pD4r2czYG0eq8kTaT/kD6PAUyz/zg97QwVTjt+gKN02LIFkDMBmhLMi9ER/frslK
-xfMnZmaGrGiR/9nmUxwPi1xpZQomyB40w11Re9epnAahNt3ViZS82eQtDF4JbAiXfKM9fJP/P6EU
-p8+1Xevb2xzEdt+Iub1FBZUbrvxGakyvSOPOrg/SfuvmbJxPgWp6ZKy7PtXny3YuxadIwVyQD8vI
-P/rmMuGNG2+k5o7Y+SlIis5z/iw=
------END CERTIFICATE-----
-
-GeoTrust Universal CA 2
-=======================
------BEGIN CERTIFICATE-----
-MIIFbDCCA1SgAwIBAgIBATANBgkqhkiG9w0BAQUFADBHMQswCQYDVQQGEwJVUzEWMBQGA1UEChMN
-R2VvVHJ1c3QgSW5jLjEgMB4GA1UEAxMXR2VvVHJ1c3QgVW5pdmVyc2FsIENBIDIwHhcNMDQwMzA0
-MDUwMDAwWhcNMjkwMzA0MDUwMDAwWjBHMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3Qg
-SW5jLjEgMB4GA1UEAxMXR2VvVHJ1c3QgVW5pdmVyc2FsIENBIDIwggIiMA0GCSqGSIb3DQEBAQUA
-A4ICDwAwggIKAoICAQCzVFLByT7y2dyxUxpZKeexw0Uo5dfR7cXFS6GqdHtXr0om/Nj1XqduGdt0
-DE81WzILAePb63p3NeqqWuDW6KFXlPCQo3RWlEQwAx5cTiuFJnSCegx2oG9NzkEtoBUGFF+3Qs17
-j1hhNNwqCPkuwwGmIkQcTAeC5lvO0Ep8BNMZcyfwqph/Lq9O64ceJHdqXbboW0W63MOhBW9Wjo8Q
-JqVJwy7XQYci4E+GymC16qFjwAGXEHm9ADwSbSsVsaxLse4YuU6W3Nx2/zu+z18DwPw76L5GG//a
-QMJS9/7jOvdqdzXQ2o3rXhhqMcceujwbKNZrVMaqW9eiLBsZzKIC9ptZvTdrhrVtgrrY6slWvKk2
-WP0+GfPtDCapkzj4T8FdIgbQl+rhrcZV4IErKIM6+vR7IVEAvlI4zs1meaj0gVbi0IMJR1FbUGrP
-20gaXT73y/Zl92zxlfgCOzJWgjl6W70viRu/obTo/3+NjN8D8WBOWBFM66M/ECuDmgFz2ZRthAAn
-ZqzwcEAJQpKtT5MNYQlRJNiS1QuUYbKHsu3/mjX/hVTK7URDrBs8FmtISgocQIgfksILAAX/8sgC
-SqSqqcyZlpwvWOB94b67B9xfBHJcMTTD7F8t4D1kkCLm0ey4Lt1ZrtmhN79UNdxzMk+MBB4zsslG
-8dhcyFVQyWi9qLo2CQIDAQABo2MwYTAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR281Xh+qQ2
-+/CfXGJx7Tz0RzgQKzAfBgNVHSMEGDAWgBR281Xh+qQ2+/CfXGJx7Tz0RzgQKzAOBgNVHQ8BAf8E
-BAMCAYYwDQYJKoZIhvcNAQEFBQADggIBAGbBxiPz2eAubl/oz66wsCVNK/g7WJtAJDday6sWSf+z
-dXkzoS9tcBc0kf5nfo/sm+VegqlVHy/c1FEHEv6sFj4sNcZj/NwQ6w2jqtB8zNHQL1EuxBRa3ugZ
-4T7GzKQp5y6EqgYweHZUcyiYWTjgAA1i00J9IZ+uPTqM1fp3DRgrFg5fNuH8KrUwJM/gYwx7WBr+
-mbpCErGR9Hxo4sjoryzqyX6uuyo9DRXcNJW2GHSoag/HtPQTxORb7QrSpJdMKu0vbBKJPfEncKpq
-A1Ihn0CoZ1Dy81of398j9tx4TuaYT1U6U+Pv8vSfx3zYWK8pIpe44L2RLrB27FcRz+8pRPPphXpg
-Y+RdM4kX2TGq2tbzGDVyz4crL2MjhF2EjD9XoIj8mZEoJmmZ1I+XRL6O1UixpCgp8RW04eWe3fiP
-pm8m1wk8OhwRDqZsN/etRIcsKMfYdIKz0G9KV7s1KSegi+ghp4dkNl3M2Basx7InQJJVOCiNUW7d
-FGdTbHFcJoRNdVq2fmBWqU2t+5sel/MN2dKXVHfaPRK34B7vCAas+YWH6aLcr34YEoP9VhdBLtUp
-gn2Z9DH2canPLAEnpQW5qrJITirvn5NSUZU8UnOOVkwXQMAJKOSLakhT2+zNVVXxxvjpoixMptEm
-X36vWkzaH6byHCx+rgIW0lbQL1dTR+iS
------END CERTIFICATE-----
-
-America Online Root Certification Authority 1
-=============================================
------BEGIN CERTIFICATE-----
-MIIDpDCCAoygAwIBAgIBATANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEcMBoGA1UEChMT
-QW1lcmljYSBPbmxpbmUgSW5jLjE2MDQGA1UEAxMtQW1lcmljYSBPbmxpbmUgUm9vdCBDZXJ0aWZp
-Y2F0aW9uIEF1dGhvcml0eSAxMB4XDTAyMDUyODA2MDAwMFoXDTM3MTExOTIwNDMwMFowYzELMAkG
-A1UEBhMCVVMxHDAaBgNVBAoTE0FtZXJpY2EgT25saW5lIEluYy4xNjA0BgNVBAMTLUFtZXJpY2Eg
-T25saW5lIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgMTCCASIwDQYJKoZIhvcNAQEBBQAD
-ggEPADCCAQoCggEBAKgv6KRpBgNHw+kqmP8ZonCaxlCyfqXfaE0bfA+2l2h9LaaLl+lkhsmj76CG
-v2BlnEtUiMJIxUo5vxTjWVXlGbR0yLQFOVwWpeKVBeASrlmLojNoWBym1BW32J/X3HGrfpq/m44z
-DyL9Hy7nBzbvYjnF3cu6JRQj3gzGPTzOggjmZj7aUTsWOqMFf6Dch9Wc/HKpoH145LcxVR5lu9Rh
-sCFg7RAycsWSJR74kEoYeEfffjA3PlAb2xzTa5qGUwew76wGePiEmf4hjUyAtgyC9mZweRrTT6PP
-8c9GsEsPPt2IYriMqQkoO3rHl+Ee5fSfwMCuJKDIodkP1nsmgmkyPacCAwEAAaNjMGEwDwYDVR0T
-AQH/BAUwAwEB/zAdBgNVHQ4EFgQUAK3Zo/Z59m50qX8zPYEX10zPM94wHwYDVR0jBBgwFoAUAK3Z
-o/Z59m50qX8zPYEX10zPM94wDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBBQUAA4IBAQB8itEf
-GDeC4Liwo+1WlchiYZwFos3CYiZhzRAW18y0ZTTQEYqtqKkFZu90821fnZmv9ov761KyBZiibyrF
-VL0lvV+uyIbqRizBs73B6UlwGBaXCBOMIOAbLjpHyx7kADCVW/RFo8AasAFOq73AI25jP4BKxQft
-3OJvx8Fi8eNy1gTIdGcL+oiroQHIb/AUr9KZzVGTfu0uOMe9zkZQPXLjeSWdm4grECDdpbgyn43g
-Kd8hdIaC2y+CMMbHNYaz+ZZfRtsMRf3zUMNvxsNIrUam4SdHCh0Om7bCd39j8uB9Gr784N/Xx6ds
-sPmuujz9dLQR6FgNgLzTqIA6me11zEZ7
------END CERTIFICATE-----
-
-America Online Root Certification Authority 2
-=============================================
------BEGIN CERTIFICATE-----
-MIIFpDCCA4ygAwIBAgIBATANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEcMBoGA1UEChMT
-QW1lcmljYSBPbmxpbmUgSW5jLjE2MDQGA1UEAxMtQW1lcmljYSBPbmxpbmUgUm9vdCBDZXJ0aWZp
-Y2F0aW9uIEF1dGhvcml0eSAyMB4XDTAyMDUyODA2MDAwMFoXDTM3MDkyOTE0MDgwMFowYzELMAkG
-A1UEBhMCVVMxHDAaBgNVBAoTE0FtZXJpY2EgT25saW5lIEluYy4xNjA0BgNVBAMTLUFtZXJpY2Eg
-T25saW5lIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgMjCCAiIwDQYJKoZIhvcNAQEBBQAD
-ggIPADCCAgoCggIBAMxBRR3pPU0Q9oyxQcngXssNt79Hc9PwVU3dxgz6sWYFas14tNwC206B89en
-fHG8dWOgXeMHDEjsJcQDIPT/DjsS/5uN4cbVG7RtIuOx238hZK+GvFciKtZHgVdEglZTvYYUAQv8
-f3SkWq7xuhG1m1hagLQ3eAkzfDJHA1zEpYNI9FdWboE2JxhP7JsowtS013wMPgwr38oE18aO6lhO
-qKSlGBxsRZijQdEt0sdtjRnxrXm3gT+9BoInLRBYBbV4Bbkv2wxrkJB+FFk4u5QkE+XRnRTf04JN
-RvCAOVIyD+OEsnpD8l7eXz8d3eOyG6ChKiMDbi4BFYdcpnV1x5dhvt6G3NRI270qv0pV2uh9UPu0
-gBe4lL8BPeraunzgWGcXuVjgiIZGZ2ydEEdYMtA1fHkqkKJaEBEjNa0vzORKW6fIJ/KD3l67Xnfn
-6KVuY8INXWHQjNJsWiEOyiijzirplcdIz5ZvHZIlyMbGwcEMBawmxNJ10uEqZ8A9W6Wa6897Gqid
-FEXlD6CaZd4vKL3Ob5Rmg0gp2OpljK+T2WSfVVcmv2/LNzGZo2C7HK2JNDJiuEMhBnIMoVxtRsX6
-Kc8w3onccVvdtjc+31D1uAclJuW8tf48ArO3+L5DwYcRlJ4jbBeKuIonDFRH8KmzwICMoCfrHRnj
-B453cMor9H124HhnAgMBAAGjYzBhMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFE1FwWg4u3Op
-aaEg5+31IqEjFNeeMB8GA1UdIwQYMBaAFE1FwWg4u3OpaaEg5+31IqEjFNeeMA4GA1UdDwEB/wQE
-AwIBhjANBgkqhkiG9w0BAQUFAAOCAgEAZ2sGuV9FOypLM7PmG2tZTiLMubekJcmnxPBUlgtk87FY
-T15R/LKXeydlwuXK5w0MJXti4/qftIe3RUavg6WXSIylvfEWK5t2LHo1YGwRgJfMqZJS5ivmae2p
-+DYtLHe/YUjRYwu5W1LtGLBDQiKmsXeu3mnFzcccobGlHBD7GL4acN3Bkku+KVqdPzW+5X1R+FXg
-JXUjhx5c3LqdsKyzadsXg8n33gy8CNyRnqjQ1xU3c6U1uPx+xURABsPr+CKAXEfOAuMRn0T//Zoy
-zH1kUQ7rVyZ2OuMeIjzCpjbdGe+n/BLzJsBZMYVMnNjP36TMzCmT/5RtdlwTCJfy7aULTd3oyWgO
-ZtMADjMSW7yV5TKQqLPGbIOtd+6Lfn6xqavT4fG2wLHqiMDn05DpKJKUe2h7lyoKZy2FAjgQ5ANh
-1NolNscIWC2hp1GvMApJ9aZphwctREZ2jirlmjvXGKL8nDgQzMY70rUXOm/9riW99XJZZLF0Kjhf
-GEzfz3EEWjbUvy+ZnOjZurGV5gJLIaFb1cFPj65pbVPbAZO1XB4Y3WRayhgoPmMEEf0cjQAPuDff
-Z4qdZqkCapH/E8ovXYO8h5Ns3CRRFgQlZvqz2cK6Kb6aSDiCmfS/O0oxGfm/jiEzFMpPVF/7zvuP
-cX/9XhmgD0uRuMRUvAawRY8mkaKO/qk=
------END CERTIFICATE-----
-
-Visa eCommerce Root
-===================
------BEGIN CERTIFICATE-----
-MIIDojCCAoqgAwIBAgIQE4Y1TR0/BvLB+WUF1ZAcYjANBgkqhkiG9w0BAQUFADBrMQswCQYDVQQG
-EwJVUzENMAsGA1UEChMEVklTQTEvMC0GA1UECxMmVmlzYSBJbnRlcm5hdGlvbmFsIFNlcnZpY2Ug
-QXNzb2NpYXRpb24xHDAaBgNVBAMTE1Zpc2EgZUNvbW1lcmNlIFJvb3QwHhcNMDIwNjI2MDIxODM2
-WhcNMjIwNjI0MDAxNjEyWjBrMQswCQYDVQQGEwJVUzENMAsGA1UEChMEVklTQTEvMC0GA1UECxMm
-VmlzYSBJbnRlcm5hdGlvbmFsIFNlcnZpY2UgQXNzb2NpYXRpb24xHDAaBgNVBAMTE1Zpc2EgZUNv
-bW1lcmNlIFJvb3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvV95WHm6h2mCxlCfL
-F9sHP4CFT8icttD0b0/Pmdjh28JIXDqsOTPHH2qLJj0rNfVIsZHBAk4ElpF7sDPwsRROEW+1QK8b
-RaVK7362rPKgH1g/EkZgPI2h4H3PVz4zHvtH8aoVlwdVZqW1LS7YgFmypw23RuwhY/81q6UCzyr0
-TP579ZRdhE2o8mCP2w4lPJ9zcc+U30rq299yOIzzlr3xF7zSujtFWsan9sYXiwGd/BmoKoMWuDpI
-/k4+oKsGGelT84ATB+0tvz8KPFUgOSwsAGl0lUq8ILKpeeUYiZGo3BxN77t+Nwtd/jmliFKMAGzs
-GHxBvfaLdXe6YJ2E5/4tAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEG
-MB0GA1UdDgQWBBQVOIMPPyw/cDMezUb+B4wg4NfDtzANBgkqhkiG9w0BAQUFAAOCAQEAX/FBfXxc
-CLkr4NWSR/pnXKUTwwMhmytMiUbPWU3J/qVAtmPN3XEolWcRzCSs00Rsca4BIGsDoo8Ytyk6feUW
-YFN4PMCvFYP3j1IzJL1kk5fui/fbGKhtcbP3LBfQdCVp9/5rPJS+TUtBjE7ic9DjkCJzQ83z7+pz
-zkWKsKZJ/0x9nXGIxHYdkFsd7v3M9+79YKWxehZx0RbQfBI8bGmX265fOZpwLwU8GUYEmSA20GBu
-YQa7FkKMcPcw++DbZqMAAb3mLNqRX6BGi01qnD093QVG/na/oAo85ADmJ7f/hC3euiInlhBx6yLt
-398znM/jra6O1I7mT1GvFpLgXPYHDw==
------END CERTIFICATE-----
-
-Certum Root CA
-==============
------BEGIN CERTIFICATE-----
-MIIDDDCCAfSgAwIBAgIDAQAgMA0GCSqGSIb3DQEBBQUAMD4xCzAJBgNVBAYTAlBMMRswGQYDVQQK
-ExJVbml6ZXRvIFNwLiB6IG8uby4xEjAQBgNVBAMTCUNlcnR1bSBDQTAeFw0wMjA2MTExMDQ2Mzla
-Fw0yNzA2MTExMDQ2MzlaMD4xCzAJBgNVBAYTAlBMMRswGQYDVQQKExJVbml6ZXRvIFNwLiB6IG8u
-by4xEjAQBgNVBAMTCUNlcnR1bSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAM6x
-wS7TT3zNJc4YPk/EjG+AanPIW1H4m9LcuwBcsaD8dQPugfCI7iNS6eYVM42sLQnFdvkrOYCJ5JdL
-kKWoePhzQ3ukYbDYWMzhbGZ+nPMJXlVjhNWo7/OxLjBos8Q82KxujZlakE403Daaj4GIULdtlkIJ
-89eVgw1BS7Bqa/j8D35in2fE7SZfECYPCE/wpFcozo+47UX2bu4lXapuOb7kky/ZR6By6/qmW6/K
-Uz/iDsaWVhFu9+lmqSbYf5VT7QqFiLpPKaVCjF62/IUgAKpoC6EahQGcxEZjgoi2IrHu/qpGWX7P
-NSzVttpd90gzFFS269lvzs2I1qsb2pY7HVkCAwEAAaMTMBEwDwYDVR0TAQH/BAUwAwEB/zANBgkq
-hkiG9w0BAQUFAAOCAQEAuI3O7+cUus/usESSbLQ5PqKEbq24IXfS1HeCh+YgQYHu4vgRt2PRFze+
-GXYkHAQaTOs9qmdvLdTN/mUxcMUbpgIKumB7bVjCmkn+YzILa+M6wKyrO7Do0wlRjBCDxjTgxSvg
-GrZgFCdsMneMvLJymM/NzD+5yCRCFNZX/OYmQ6kd5YCQzgNUKD73P9P4Te1qCjqTE5s7FCMTY5w/
-0YcneeVMUeMBrYVdGjux1XMQpNPyvG5k9VpWkKjHDkx0Dy5xO/fIR/RpbxXyEV6DHpx8Uq79AtoS
-qFlnGNu8cN2bsWntgM6JQEhqDjXKKWYVIZQs6GAqm4VKQPNriiTsBhYscw==
------END CERTIFICATE-----
-
-Comodo AAA Services root
-========================
------BEGIN CERTIFICATE-----
-MIIEMjCCAxqgAwIBAgIBATANBgkqhkiG9w0BAQUFADB7MQswCQYDVQQGEwJHQjEbMBkGA1UECAwS
-R3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRowGAYDVQQKDBFDb21vZG8gQ0Eg
-TGltaXRlZDEhMB8GA1UEAwwYQUFBIENlcnRpZmljYXRlIFNlcnZpY2VzMB4XDTA0MDEwMTAwMDAw
-MFoXDTI4MTIzMTIzNTk1OVowezELMAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFuY2hl
-c3RlcjEQMA4GA1UEBwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxITAfBgNV
-BAMMGEFBQSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
-ggEBAL5AnfRu4ep2hxxNRUSOvkbIgwadwSr+GB+O5AL686tdUIoWMQuaBtDFcCLNSS1UY8y2bmhG
-C1Pqy0wkwLxyTurxFa70VJoSCsN6sjNg4tqJVfMiWPPe3M/vg4aijJRPn2jymJBGhCfHdr/jzDUs
-i14HZGWCwEiwqJH5YZ92IFCokcdmtet4YgNW8IoaE+oxox6gmf049vYnMlhvB/VruPsUK6+3qszW
-Y19zjNoFmag4qMsXeDZRrOme9Hg6jc8P2ULimAyrL58OAd7vn5lJ8S3frHRNG5i1R8XlKdH5kBjH
-Ypy+g8cmez6KJcfA3Z3mNWgQIJ2P2N7Sw4ScDV7oL8kCAwEAAaOBwDCBvTAdBgNVHQ4EFgQUoBEK
-Iz6W8Qfs4q8p74Klf9AwpLQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wewYDVR0f
-BHQwcjA4oDagNIYyaHR0cDovL2NybC5jb21vZG9jYS5jb20vQUFBQ2VydGlmaWNhdGVTZXJ2aWNl
-cy5jcmwwNqA0oDKGMGh0dHA6Ly9jcmwuY29tb2RvLm5ldC9BQUFDZXJ0aWZpY2F0ZVNlcnZpY2Vz
-LmNybDANBgkqhkiG9w0BAQUFAAOCAQEACFb8AvCb6P+k+tZ7xkSAzk/ExfYAWMymtrwUSWgEdujm
-7l3sAg9g1o1QGE8mTgHj5rCl7r+8dFRBv/38ErjHT1r0iWAFf2C3BUrz9vHCv8S5dIa2LX1rzNLz
-Rt0vxuBqw8M0Ayx9lt1awg6nCpnBBYurDC/zXDrPbDdVCYfeU0BsWO/8tqtlbgT2G9w84FoVxp7Z
-8VlIMCFlA2zs6SFz7JsDoeA3raAVGI/6ugLOpyypEBMs1OUIJqsil2D4kF501KKaU73yqWjgom7C
-12yxow+ev+to51byrvLjKzg6CYG1a4XXvi3tPxq3smPi9WIsgtRqAEFQ8TmDn5XpNpaYbg==
------END CERTIFICATE-----
-
-Comodo Secure Services root
-===========================
------BEGIN CERTIFICATE-----
-MIIEPzCCAyegAwIBAgIBATANBgkqhkiG9w0BAQUFADB+MQswCQYDVQQGEwJHQjEbMBkGA1UECAwS
-R3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRowGAYDVQQKDBFDb21vZG8gQ0Eg
-TGltaXRlZDEkMCIGA1UEAwwbU2VjdXJlIENlcnRpZmljYXRlIFNlcnZpY2VzMB4XDTA0MDEwMTAw
-MDAwMFoXDTI4MTIzMTIzNTk1OVowfjELMAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFu
-Y2hlc3RlcjEQMA4GA1UEBwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxJDAi
-BgNVBAMMG1NlY3VyZSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczCCASIwDQYJKoZIhvcNAQEBBQADggEP
-ADCCAQoCggEBAMBxM4KK0HDrc4eCQNUd5MvJDkKQ+d40uaG6EfQlhfPMcm3ye5drswfxdySRXyWP
-9nQ95IDC+DwN879A6vfIUtFyb+/Iq0G4bi4XKpVpDM3SHpR7LZQdqnXXs5jLrLxkU0C8j6ysNstc
-rbvd4JQX7NFc0L/vpZXJkMWwrPsbQ996CF23uPJAGysnnlDOXmWCiIxe004MeuoIkbY2qitC++rC
-oznl2yY4rYsK7hljxxwk3wN42ubqwUcaCwtGCd0C/N7Lh1/XMGNooa7cMqG6vv5Eq2i2pRcV/b3V
-p6ea5EQz6YiO/O1R65NxTq0B50SOqy3LqP4BSUjwwN3HaNiS/j0CAwEAAaOBxzCBxDAdBgNVHQ4E
-FgQUPNiTiMLAggnMAZkGkyDpnnAJY08wDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8w
-gYEGA1UdHwR6MHgwO6A5oDeGNWh0dHA6Ly9jcmwuY29tb2RvY2EuY29tL1NlY3VyZUNlcnRpZmlj
-YXRlU2VydmljZXMuY3JsMDmgN6A1hjNodHRwOi8vY3JsLmNvbW9kby5uZXQvU2VjdXJlQ2VydGlm
-aWNhdGVTZXJ2aWNlcy5jcmwwDQYJKoZIhvcNAQEFBQADggEBAIcBbSMdflsXfcFhMs+P5/OKlFlm
-4J4oqF7Tt/Q05qo5spcWxYJvMqTpjOev/e/C6LlLqqP05tqNZSH7uoDrJiiFGv45jN5bBAS0VPmj
-Z55B+glSzAVIqMk/IQQezkhr/IXownuvf7fM+F86/TXGDe+X3EyrEeFryzHRbPtIgKvcnDe4IRRL
-DXE97IMzbtFuMhbsmMcWi1mmNKsFVy2T96oTy9IT4rcuO81rUBcJaD61JlfutuC23bkpgHl9j6Pw
-pCikFcSF9CfUa7/lXORlAnZUtOM3ZiTTGWHIUhDlizeauan5Hb/qmZJhlv8BzaFfDbxxvA6sCx1H
-RR3B7Hzs/Sk=
------END CERTIFICATE-----
-
-Comodo Trusted Services root
-============================
------BEGIN CERTIFICATE-----
-MIIEQzCCAyugAwIBAgIBATANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJHQjEbMBkGA1UECAwS
-R3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRowGAYDVQQKDBFDb21vZG8gQ0Eg
-TGltaXRlZDElMCMGA1UEAwwcVHJ1c3RlZCBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczAeFw0wNDAxMDEw
-MDAwMDBaFw0yODEyMzEyMzU5NTlaMH8xCzAJBgNVBAYTAkdCMRswGQYDVQQIDBJHcmVhdGVyIE1h
-bmNoZXN0ZXIxEDAOBgNVBAcMB1NhbGZvcmQxGjAYBgNVBAoMEUNvbW9kbyBDQSBMaW1pdGVkMSUw
-IwYDVQQDDBxUcnVzdGVkIENlcnRpZmljYXRlIFNlcnZpY2VzMIIBIjANBgkqhkiG9w0BAQEFAAOC
-AQ8AMIIBCgKCAQEA33FvNlhTWvI2VFeAxHQIIO0Yfyod5jWaHiWsnOWWfnJSoBVC21ndZHoa0Lh7
-3TkVvFVIxO06AOoxEbrycXQaZ7jPM8yoMa+j49d/vzMtTGo87IvDktJTdyR0nAducPy9C1t2ul/y
-/9c3S0pgePfw+spwtOpZqqPOSC+pw7ILfhdyFgymBwwbOM/JYrc/oJOlh0Hyt3BAd9i+FHzjqMB6
-juljatEPmsbS9Is6FARW1O24zG71++IsWL1/T2sr92AkWCTOJu80kTrV44HQsvAEAtdbtz6SrGsS
-ivnkBbA7kUlcsutT6vifR4buv5XAwAaf0lteERv0xwQ1KdJVXOTt6wIDAQABo4HJMIHGMB0GA1Ud
-DgQWBBTFe1i97doladL3WRaoszLAeydb9DAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB
-/zCBgwYDVR0fBHwwejA8oDqgOIY2aHR0cDovL2NybC5jb21vZG9jYS5jb20vVHJ1c3RlZENlcnRp
-ZmljYXRlU2VydmljZXMuY3JsMDqgOKA2hjRodHRwOi8vY3JsLmNvbW9kby5uZXQvVHJ1c3RlZENl
-cnRpZmljYXRlU2VydmljZXMuY3JsMA0GCSqGSIb3DQEBBQUAA4IBAQDIk4E7ibSvuIQSTI3S8Ntw
-uleGFTQQuS9/HrCoiWChisJ3DFBKmwCL2Iv0QeLQg4pKHBQGsKNoBXAxMKdTmw7pSqBYaWcOrp32
-pSxBvzwGa+RZzG0Q8ZZvH9/0BAKkn0U+yNj6NkZEUD+Cl5EfKNsYEYwq5GWDVxISjBc/lDb+XbDA
-BHcTuPQV1T84zJQ6VdCsmPW6AF/ghhmBeC8owH7TzEIK9a5QoNE+xqFx7D+gIIxmOom0jtTYsU0l
-R+4viMi14QVFwL4Ucd56/Y57fU0IlqUSc/AtyjcndBInTMu2l+nZrghtWjlA3QVHdWpaIbOjGM9O
-9y5Xt5hwXsjEeLBi
------END CERTIFICATE-----
-
-QuoVadis Root CA
-================
------BEGIN CERTIFICATE-----
-MIIF0DCCBLigAwIBAgIEOrZQizANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJCTTEZMBcGA1UE
-ChMQUXVvVmFkaXMgTGltaXRlZDElMCMGA1UECxMcUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0
-eTEuMCwGA1UEAxMlUXVvVmFkaXMgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wMTAz
-MTkxODMzMzNaFw0yMTAzMTcxODMzMzNaMH8xCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRp
-cyBMaW1pdGVkMSUwIwYDVQQLExxSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MS4wLAYDVQQD
-EyVRdW9WYWRpcyBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEF
-AAOCAQ8AMIIBCgKCAQEAv2G1lVO6V/z68mcLOhrfEYBklbTRvM16z/Ypli4kVEAkOPcahdxYTMuk
-J0KX0J+DisPkBgNbAKVRHnAEdOLB1Dqr1607BxgFjv2DrOpm2RgbaIr1VxqYuvXtdj182d6UajtL
-F8HVj71lODqV0D1VNk7feVcxKh7YWWVJWCCYfqtffp/p1k3sg3Spx2zY7ilKhSoGFPlU5tPaZQeL
-YzcS19Dsw3sgQUSj7cugF+FxZc4dZjH3dgEZyH0DWLaVSR2mEiboxgx24ONmy+pdpibu5cxfvWen
-AScOospUxbF6lR1xHkopigPcakXBpBlebzbNw6Kwt/5cOOJSvPhEQ+aQuwIDAQABo4ICUjCCAk4w
-PQYIKwYBBQUHAQEEMTAvMC0GCCsGAQUFBzABhiFodHRwczovL29jc3AucXVvdmFkaXNvZmZzaG9y
-ZS5jb20wDwYDVR0TAQH/BAUwAwEB/zCCARoGA1UdIASCAREwggENMIIBCQYJKwYBBAG+WAABMIH7
-MIHUBggrBgEFBQcCAjCBxxqBxFJlbGlhbmNlIG9uIHRoZSBRdW9WYWRpcyBSb290IENlcnRpZmlj
-YXRlIGJ5IGFueSBwYXJ0eSBhc3N1bWVzIGFjY2VwdGFuY2Ugb2YgdGhlIHRoZW4gYXBwbGljYWJs
-ZSBzdGFuZGFyZCB0ZXJtcyBhbmQgY29uZGl0aW9ucyBvZiB1c2UsIGNlcnRpZmljYXRpb24gcHJh
-Y3RpY2VzLCBhbmQgdGhlIFF1b1ZhZGlzIENlcnRpZmljYXRlIFBvbGljeS4wIgYIKwYBBQUHAgEW
-Fmh0dHA6Ly93d3cucXVvdmFkaXMuYm0wHQYDVR0OBBYEFItLbe3TKbkGGew5Oanwl4Rqy+/fMIGu
-BgNVHSMEgaYwgaOAFItLbe3TKbkGGew5Oanwl4Rqy+/foYGEpIGBMH8xCzAJBgNVBAYTAkJNMRkw
-FwYDVQQKExBRdW9WYWRpcyBMaW1pdGVkMSUwIwYDVQQLExxSb290IENlcnRpZmljYXRpb24gQXV0
-aG9yaXR5MS4wLAYDVQQDEyVRdW9WYWRpcyBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggQ6
-tlCLMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQUFAAOCAQEAitQUtf70mpKnGdSkfnIYj9lo
-fFIk3WdvOXrEql494liwTXCYhGHoG+NpGA7O+0dQoE7/8CQfvbLO9Sf87C9TqnN7Az10buYWnuul
-LsS/VidQK2K6vkscPFVcQR0kvoIgR13VRH56FmjffU1RcHhXHTMe/QKZnAzNCgVPx7uOpHX6Sm2x
-gI4JVrmcGmD+XcHXetwReNDWXcG31a0ymQM6isxUJTkxgXsTIlG6Rmyhu576BGxJJnSP0nPrzDCi
-5upZIof4l/UO/erMkqQWxFIY6iHOsfHmhIHluqmGKPJDWl0Snawe2ajlCmqnf6CHKc/yiU3U7MXi
-5nrQNiOKSnQ2+Q==
------END CERTIFICATE-----
-
-QuoVadis Root CA 2
-==================
------BEGIN CERTIFICATE-----
-MIIFtzCCA5+gAwIBAgICBQkwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQk0xGTAXBgNVBAoT
-EFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMTElF1b1ZhZGlzIFJvb3QgQ0EgMjAeFw0wNjExMjQx
-ODI3MDBaFw0zMTExMjQxODIzMzNaMEUxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM
-aW1pdGVkMRswGQYDVQQDExJRdW9WYWRpcyBSb290IENBIDIwggIiMA0GCSqGSIb3DQEBAQUAA4IC
-DwAwggIKAoICAQCaGMpLlA0ALa8DKYrwD4HIrkwZhR0In6spRIXzL4GtMh6QRr+jhiYaHv5+HBg6
-XJxgFyo6dIMzMH1hVBHL7avg5tKifvVrbxi3Cgst/ek+7wrGsxDp3MJGF/hd/aTa/55JWpzmM+Yk
-lvc/ulsrHHo1wtZn/qtmUIttKGAr79dgw8eTvI02kfN/+NsRE8Scd3bBrrcCaoF6qUWD4gXmuVbB
-lDePSHFjIuwXZQeVikvfj8ZaCuWw419eaxGrDPmF60Tp+ARz8un+XJiM9XOva7R+zdRcAitMOeGy
-lZUtQofX1bOQQ7dsE/He3fbE+Ik/0XX1ksOR1YqI0JDs3G3eicJlcZaLDQP9nL9bFqyS2+r+eXyt
-66/3FsvbzSUr5R/7mp/iUcw6UwxI5g69ybR2BlLmEROFcmMDBOAENisgGQLodKcftslWZvB1Jdxn
-wQ5hYIizPtGo/KPaHbDRsSNU30R2be1B2MGyIrZTHN81Hdyhdyox5C315eXbyOD/5YDXC2Og/zOh
-D7osFRXql7PSorW+8oyWHhqPHWykYTe5hnMz15eWniN9gqRMgeKh0bpnX5UHoycR7hYQe7xFSkyy
-BNKr79X9DFHOUGoIMfmR2gyPZFwDwzqLID9ujWc9Otb+fVuIyV77zGHcizN300QyNQliBJIWENie
-J0f7OyHj+OsdWwIDAQABo4GwMIGtMA8GA1UdEwEB/wQFMAMBAf8wCwYDVR0PBAQDAgEGMB0GA1Ud
-DgQWBBQahGK8SEwzJQTU7tD2A8QZRtGUazBuBgNVHSMEZzBlgBQahGK8SEwzJQTU7tD2A8QZRtGU
-a6FJpEcwRTELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMT
-ElF1b1ZhZGlzIFJvb3QgQ0EgMoICBQkwDQYJKoZIhvcNAQEFBQADggIBAD4KFk2fBluornFdLwUv
-Z+YTRYPENvbzwCYMDbVHZF34tHLJRqUDGCdViXh9duqWNIAXINzng/iN/Ae42l9NLmeyhP3ZRPx3
-UIHmfLTJDQtyU/h2BwdBR5YM++CCJpNVjP4iH2BlfF/nJrP3MpCYUNQ3cVX2kiF495V5+vgtJodm
-VjB3pjd4M1IQWK4/YY7yarHvGH5KWWPKjaJW1acvvFYfzznB4vsKqBUsfU16Y8Zsl0Q80m/DShcK
-+JDSV6IZUaUtl0HaB0+pUNqQjZRG4T7wlP0QADj1O+hA4bRuVhogzG9Yje0uRY/W6ZM/57Es3zrW
-IozchLsib9D45MY56QSIPMO661V6bYCZJPVsAfv4l7CUW+v90m/xd2gNNWQjrLhVoQPRTUIZ3Ph1
-WVaj+ahJefivDrkRoHy3au000LYmYjgahwz46P0u05B/B5EqHdZ+XIWDmbA4CD/pXvk1B+TJYm5X
-f6dQlfe6yJvmjqIBxdZmv3lh8zwc4bmCXF2gw+nYSL0ZohEUGW6yhhtoPkg3Goi3XZZenMfvJ2II
-4pEZXNLxId26F0KCl3GBUzGpn/Z9Yr9y4aOTHcyKJloJONDO1w2AFrR4pTqHTI2KpdVGl/IsELm8
-VCLAAVBpQ570su9t+Oza8eOx79+Rj1QqCyXBJhnEUhAFZdWCEOrCMc0u
------END CERTIFICATE-----
-
-QuoVadis Root CA 3
-==================
------BEGIN CERTIFICATE-----
-MIIGnTCCBIWgAwIBAgICBcYwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQk0xGTAXBgNVBAoT
-EFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMTElF1b1ZhZGlzIFJvb3QgQ0EgMzAeFw0wNjExMjQx
-OTExMjNaFw0zMTExMjQxOTA2NDRaMEUxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM
-aW1pdGVkMRswGQYDVQQDExJRdW9WYWRpcyBSb290IENBIDMwggIiMA0GCSqGSIb3DQEBAQUAA4IC
-DwAwggIKAoICAQDMV0IWVJzmmNPTTe7+7cefQzlKZbPoFog02w1ZkXTPkrgEQK0CSzGrvI2RaNgg
-DhoB4hp7Thdd4oq3P5kazethq8Jlph+3t723j/z9cI8LoGe+AaJZz3HmDyl2/7FWeUUrH556VOij
-KTVopAFPD6QuN+8bv+OPEKhyq1hX51SGyMnzW9os2l2ObjyjPtr7guXd8lyyBTNvijbO0BNO/79K
-DDRMpsMhvVAEVeuxu537RR5kFd5VAYwCdrXLoT9CabwvvWhDFlaJKjdhkf2mrk7AyxRllDdLkgbv
-BNDInIjbC3uBr7E9KsRlOni27tyAsdLTmZw67mtaa7ONt9XOnMK+pUsvFrGeaDsGb659n/je7Mwp
-p5ijJUMv7/FfJuGITfhebtfZFG4ZM2mnO4SJk8RTVROhUXhA+LjJou57ulJCg54U7QVSWllWp5f8
-nT8KKdjcT5EOE7zelaTfi5m+rJsziO+1ga8bxiJTyPbH7pcUsMV8eFLI8M5ud2CEpukqdiDtWAEX
-MJPpGovgc2PZapKUSU60rUqFxKMiMPwJ7Wgic6aIDFUhWMXhOp8q3crhkODZc6tsgLjoC2SToJyM
-Gf+z0gzskSaHirOi4XCPLArlzW1oUevaPwV/izLmE1xr/l9A4iLItLRkT9a6fUg+qGkM17uGcclz
-uD87nSVL2v9A6wIDAQABo4IBlTCCAZEwDwYDVR0TAQH/BAUwAwEB/zCB4QYDVR0gBIHZMIHWMIHT
-BgkrBgEEAb5YAAMwgcUwgZMGCCsGAQUFBwICMIGGGoGDQW55IHVzZSBvZiB0aGlzIENlcnRpZmlj
-YXRlIGNvbnN0aXR1dGVzIGFjY2VwdGFuY2Ugb2YgdGhlIFF1b1ZhZGlzIFJvb3QgQ0EgMyBDZXJ0
-aWZpY2F0ZSBQb2xpY3kgLyBDZXJ0aWZpY2F0aW9uIFByYWN0aWNlIFN0YXRlbWVudC4wLQYIKwYB
-BQUHAgEWIWh0dHA6Ly93d3cucXVvdmFkaXNnbG9iYWwuY29tL2NwczALBgNVHQ8EBAMCAQYwHQYD
-VR0OBBYEFPLAE+CCQz777i9nMpY1XNu4ywLQMG4GA1UdIwRnMGWAFPLAE+CCQz777i9nMpY1XNu4
-ywLQoUmkRzBFMQswCQYDVQQGEwJCTTEZMBcGA1UEChMQUXVvVmFkaXMgTGltaXRlZDEbMBkGA1UE
-AxMSUXVvVmFkaXMgUm9vdCBDQSAzggIFxjANBgkqhkiG9w0BAQUFAAOCAgEAT62gLEz6wPJv92ZV
-qyM07ucp2sNbtrCD2dDQ4iH782CnO11gUyeim/YIIirnv6By5ZwkajGxkHon24QRiSemd1o417+s
-hvzuXYO8BsbRd2sPbSQvS3pspweWyuOEn62Iix2rFo1bZhfZFvSLgNLd+LJ2w/w4E6oM3kJpK27z
-POuAJ9v1pkQNn1pVWQvVDVJIxa6f8i+AxeoyUDUSly7B4f/xI4hROJ/yZlZ25w9Rl6VSDE1JUZU2
-Pb+iSwwQHYaZTKrzchGT5Or2m9qoXadNt54CrnMAyNojA+j56hl0YgCUyyIgvpSnWbWCar6ZeXqp
-8kokUvd0/bpO5qgdAm6xDYBEwa7TIzdfu4V8K5Iu6H6li92Z4b8nby1dqnuH/grdS/yO9SbkbnBC
-bjPsMZ57k8HkyWkaPcBrTiJt7qtYTcbQQcEr6k8Sh17rRdhs9ZgC06DYVYoGmRmioHfRMJ6szHXu
-g/WwYjnPbFfiTNKRCw51KBuav/0aQ/HKd/s7j2G4aSgWQgRecCocIdiP4b0jWy10QJLZYxkNc91p
-vGJHvOB0K7Lrfb5BG7XARsWhIstfTsEokt4YutUqKLsRixeTmJlglFwjz1onl14LBQaTNx47aTbr
-qZ5hHY8y2o4M1nQ+ewkk2gF3R8Q7zTSMmfXK4SVhM7JZG+Ju1zdXtg2pEto=
------END CERTIFICATE-----
-
-Security Communication Root CA
-==============================
------BEGIN CERTIFICATE-----
-MIIDWjCCAkKgAwIBAgIBADANBgkqhkiG9w0BAQUFADBQMQswCQYDVQQGEwJKUDEYMBYGA1UEChMP
-U0VDT00gVHJ1c3QubmV0MScwJQYDVQQLEx5TZWN1cml0eSBDb21tdW5pY2F0aW9uIFJvb3RDQTEw
-HhcNMDMwOTMwMDQyMDQ5WhcNMjMwOTMwMDQyMDQ5WjBQMQswCQYDVQQGEwJKUDEYMBYGA1UEChMP
-U0VDT00gVHJ1c3QubmV0MScwJQYDVQQLEx5TZWN1cml0eSBDb21tdW5pY2F0aW9uIFJvb3RDQTEw
-ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCzs/5/022x7xZ8V6UMbXaKL0u/ZPtM7orw
-8yl89f/uKuDp6bpbZCKamm8sOiZpUQWZJtzVHGpxxpp9Hp3dfGzGjGdnSj74cbAZJ6kJDKaVv0uM
-DPpVmDvY6CKhS3E4eayXkmmziX7qIWgGmBSWh9JhNrxtJ1aeV+7AwFb9Ms+k2Y7CI9eNqPPYJayX
-5HA49LY6tJ07lyZDo6G8SVlyTCMwhwFY9k6+HGhWZq/NQV3Is00qVUarH9oe4kA92819uZKAnDfd
-DJZkndwi92SL32HeFZRSFaB9UslLqCHJxrHty8OVYNEP8Ktw+N/LTX7s1vqr2b1/VPKl6Xn62dZ2
-JChzAgMBAAGjPzA9MB0GA1UdDgQWBBSgc0mZaNyFW2XjmygvV5+9M7wHSDALBgNVHQ8EBAMCAQYw
-DwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAaECpqLvkT115swW1F7NgE+vGkl3g
-0dNq/vu+m22/xwVtWSDEHPC32oRYAmP6SBbvT6UL90qY8j+eG61Ha2POCEfrUj94nK9NrvjVT8+a
-mCoQQTlSxN3Zmw7vkwGusi7KaEIkQmywszo+zenaSMQVy+n5Bw+SUEmK3TGXX8npN6o7WWWXlDLJ
-s58+OmJYxUmtYg5xpTKqL8aJdkNAExNnPaJUJRDL8Try2frbSVa7pv6nQTXD4IhhyYjH3zYQIphZ
-6rBK+1YWc26sTfcioU+tHXotRSflMMFe8toTyyVCUZVHA4xsIcx0Qu1T/zOLjw9XARYvz6buyXAi
-FL39vmwLAw==
------END CERTIFICATE-----
-
-Sonera Class 2 Root CA
-======================
------BEGIN CERTIFICATE-----
-MIIDIDCCAgigAwIBAgIBHTANBgkqhkiG9w0BAQUFADA5MQswCQYDVQQGEwJGSTEPMA0GA1UEChMG
-U29uZXJhMRkwFwYDVQQDExBTb25lcmEgQ2xhc3MyIENBMB4XDTAxMDQwNjA3Mjk0MFoXDTIxMDQw
-NjA3Mjk0MFowOTELMAkGA1UEBhMCRkkxDzANBgNVBAoTBlNvbmVyYTEZMBcGA1UEAxMQU29uZXJh
-IENsYXNzMiBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJAXSjWdyvANlsdE+hY3
-/Ei9vX+ALTU74W+oZ6m/AxxNjG8yR9VBaKQTBME1DJqEQ/xcHf+Js+gXGM2RX/uJ4+q/Tl18GybT
-dXnt5oTjV+WtKcT0OijnpXuENmmz/V52vaMtmdOQTiMofRhj8VQ7Jp12W5dCsv+u8E7s3TmVToMG
-f+dJQMjFAbJUWmYdPfz56TwKnoG4cPABi+QjVHzIrviQHgCWctRUz2EjvOr7nQKV0ba5cTppCD8P
-tOFCx4j1P5iop7oc4HFx71hXgVB6XGt0Rg6DA5jDjqhu8nYybieDwnPz3BjotJPqdURrBGAgcVeH
-nfO+oJAjPYok4doh28MCAwEAAaMzMDEwDwYDVR0TAQH/BAUwAwEB/zARBgNVHQ4ECgQISqCqWITT
-XjwwCwYDVR0PBAQDAgEGMA0GCSqGSIb3DQEBBQUAA4IBAQBazof5FnIVV0sd2ZvnoiYw7JNn39Yt
-0jSv9zilzqsWuasvfDXLrNAPtEwr/IDva4yRXzZ299uzGxnq9LIR/WFxRL8oszodv7ND6J+/3DEI
-cbCdjdY0RzKQxmUk96BKfARzjzlvF4xytb1LyHr4e4PDKE6cCepnP7JnBBvDFNr450kkkdAdavph
-Oe9r5yF1BgfYErQhIHBCcYHaPJo2vqZbDWpsmh+Re/n570K6Tk6ezAyNlNzZRZxe7EJQY670XcSx
-EtzKO6gunRRaBXW37Ndj4ro1tgQIkejanZz2ZrUYrAqmVCY0M9IbwdR/GjqOC6oybtv8TyWf2TLH
-llpwrN9M
------END CERTIFICATE-----
-
-Staat der Nederlanden Root CA
-=============================
------BEGIN CERTIFICATE-----
-MIIDujCCAqKgAwIBAgIEAJiWijANBgkqhkiG9w0BAQUFADBVMQswCQYDVQQGEwJOTDEeMBwGA1UE
-ChMVU3RhYXQgZGVyIE5lZGVybGFuZGVuMSYwJAYDVQQDEx1TdGFhdCBkZXIgTmVkZXJsYW5kZW4g
-Um9vdCBDQTAeFw0wMjEyMTcwOTIzNDlaFw0xNTEyMTYwOTE1MzhaMFUxCzAJBgNVBAYTAk5MMR4w
-HAYDVQQKExVTdGFhdCBkZXIgTmVkZXJsYW5kZW4xJjAkBgNVBAMTHVN0YWF0IGRlciBOZWRlcmxh
-bmRlbiBSb290IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmNK1URF6gaYUmHFt
-vsznExvWJw56s2oYHLZhWtVhCb/ekBPHZ+7d89rFDBKeNVU+LCeIQGv33N0iYfXCxw719tV2U02P
-jLwYdjeFnejKScfST5gTCaI+Ioicf9byEGW07l8Y1Rfj+MX94p2i71MOhXeiD+EwR+4A5zN9RGca
-C1Hoi6CeUJhoNFIfLm0B8mBF8jHrqTFoKbt6QZ7GGX+UtFE5A3+y3qcym7RHjm+0Sq7lr7HcsBth
-vJly3uSJt3omXdozSVtSnA71iq3DuD3oBmrC1SoLbHuEvVYFy4ZlkuxEK7COudxwC0barbxjiDn6
-22r+I/q85Ej0ZytqERAhSQIDAQABo4GRMIGOMAwGA1UdEwQFMAMBAf8wTwYDVR0gBEgwRjBEBgRV
-HSAAMDwwOgYIKwYBBQUHAgEWLmh0dHA6Ly93d3cucGtpb3ZlcmhlaWQubmwvcG9saWNpZXMvcm9v
-dC1wb2xpY3kwDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBSofeu8Y6R0E3QA7Jbg0zTBLL9s+DAN
-BgkqhkiG9w0BAQUFAAOCAQEABYSHVXQ2YcG70dTGFagTtJ+k/rvuFbQvBgwp8qiSpGEN/KtcCFtR
-EytNwiphyPgJWPwtArI5fZlmgb9uXJVFIGzmeafR2Bwp/MIgJ1HI8XxdNGdphREwxgDS1/PTfLbw
-MVcoEoJz6TMvplW0C5GUR5z6u3pCMuiufi3IvKwUv9kP2Vv8wfl6leF9fpb8cbDCTMjfRTTJzg3y
-nGQI0DvDKcWy7ZAEwbEpkcUwb8GpcjPM/l0WFywRaed+/sWDCN+83CI6LiBpIzlWYGeQiy52OfsR
-iJf2fL1LuCAWZwWN4jvBcj+UlTfHXbme2JOhF4//DGYVwSR8MnwDHTuhWEUykw==
------END CERTIFICATE-----
-
-TDC Internet Root CA
-====================
------BEGIN CERTIFICATE-----
-MIIEKzCCAxOgAwIBAgIEOsylTDANBgkqhkiG9w0BAQUFADBDMQswCQYDVQQGEwJESzEVMBMGA1UE
-ChMMVERDIEludGVybmV0MR0wGwYDVQQLExRUREMgSW50ZXJuZXQgUm9vdCBDQTAeFw0wMTA0MDUx
-NjMzMTdaFw0yMTA0MDUxNzAzMTdaMEMxCzAJBgNVBAYTAkRLMRUwEwYDVQQKEwxUREMgSW50ZXJu
-ZXQxHTAbBgNVBAsTFFREQyBJbnRlcm5ldCBSb290IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A
-MIIBCgKCAQEAxLhAvJHVYx/XmaCLDEAedLdInUaMArLgJF/wGROnN4NrXceO+YQwzho7+vvOi20j
-xsNuZp+Jpd/gQlBn+h9sHvTQBda/ytZO5GhgbEaqHF1j4QeGDmUApy6mcca8uYGoOn0a0vnRrEvL
-znWv3Hv6gXPU/Lq9QYjUdLP5Xjg6PEOo0pVOd20TDJ2PeAG3WiAfAzc14izbSysseLlJ28TQx5yc
-5IogCSEWVmb/Bexb4/DPqyQkXsN/cHoSxNK1EKC2IeGNeGlVRGn1ypYcNIUXJXfi9i8nmHj9eQY6
-otZaQ8H/7AQ77hPv01ha/5Lr7K7a8jcDR0G2l8ktCkEiu7vmpwIDAQABo4IBJTCCASEwEQYJYIZI
-AYb4QgEBBAQDAgAHMGUGA1UdHwReMFwwWqBYoFakVDBSMQswCQYDVQQGEwJESzEVMBMGA1UEChMM
-VERDIEludGVybmV0MR0wGwYDVQQLExRUREMgSW50ZXJuZXQgUm9vdCBDQTENMAsGA1UEAxMEQ1JM
-MTArBgNVHRAEJDAigA8yMDAxMDQwNTE2MzMxN1qBDzIwMjEwNDA1MTcwMzE3WjALBgNVHQ8EBAMC
-AQYwHwYDVR0jBBgwFoAUbGQBx/2FbazI2p5QCIUItTxWqFAwHQYDVR0OBBYEFGxkAcf9hW2syNqe
-UAiFCLU8VqhQMAwGA1UdEwQFMAMBAf8wHQYJKoZIhvZ9B0EABBAwDhsIVjUuMDo0LjADAgSQMA0G
-CSqGSIb3DQEBBQUAA4IBAQBOQ8zR3R0QGwZ/t6T609lN+yOfI1Rb5osvBCiLtSdtiaHsmGnc540m
-gwV5dOy0uaOXwTUA/RXaOYE6lTGQ3pfphqiZdwzlWqCE/xIWrG64jcN7ksKsLtB9KOy282A4aW8+
-2ARVPp7MVdK6/rtHBNcK2RYKNCn1WBPVT8+PVkuzHu7TmHnaCB4Mb7j4Fifvwm899qNLPg7kbWzb
-O0ESm70NRyN/PErQr8Cv9u8btRXE64PECV90i9kR+8JWsTz4cMo0jUNAE4z9mQNUecYu6oah9jrU
-Cbz0vGbMPVjQV0kK7iXiQe4T+Zs4NNEA9X7nlB38aQNiuJkFBT1reBK9sG9l
------END CERTIFICATE-----
-
-TDC OCES Root CA
-================
------BEGIN CERTIFICATE-----
-MIIFGTCCBAGgAwIBAgIEPki9xDANBgkqhkiG9w0BAQUFADAxMQswCQYDVQQGEwJESzEMMAoGA1UE
-ChMDVERDMRQwEgYDVQQDEwtUREMgT0NFUyBDQTAeFw0wMzAyMTEwODM5MzBaFw0zNzAyMTEwOTA5
-MzBaMDExCzAJBgNVBAYTAkRLMQwwCgYDVQQKEwNUREMxFDASBgNVBAMTC1REQyBPQ0VTIENBMIIB
-IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArGL2YSCyz8DGhdfjeebM7fI5kqSXLmSjhFuH
-nEz9pPPEXyG9VhDr2y5h7JNp46PMvZnDBfwGuMo2HP6QjklMxFaaL1a8z3sM8W9Hpg1DTeLpHTk0
-zY0s2RKY+ePhwUp8hjjEqcRhiNJerxomTdXkoCJHhNlktxmW/OwZ5LKXJk5KTMuPJItUGBxIYXvV
-iGjaXbXqzRowwYCDdlCqT9HU3Tjw7xb04QxQBr/q+3pJoSgrHPb8FTKjdGqPqcNiKXEx5TukYBde
-dObaE+3pHx8b0bJoc8YQNHVGEBDjkAB2QMuLt0MJIf+rTpPGWOmlgtt3xDqZsXKVSQTwtyv6e1mO
-3QIDAQABo4ICNzCCAjMwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwgewGA1UdIASB
-5DCB4TCB3gYIKoFQgSkBAQEwgdEwLwYIKwYBBQUHAgEWI2h0dHA6Ly93d3cuY2VydGlmaWthdC5k
-ay9yZXBvc2l0b3J5MIGdBggrBgEFBQcCAjCBkDAKFgNUREMwAwIBARqBgUNlcnRpZmlrYXRlciBm
-cmEgZGVubmUgQ0EgdWRzdGVkZXMgdW5kZXIgT0lEIDEuMi4yMDguMTY5LjEuMS4xLiBDZXJ0aWZp
-Y2F0ZXMgZnJvbSB0aGlzIENBIGFyZSBpc3N1ZWQgdW5kZXIgT0lEIDEuMi4yMDguMTY5LjEuMS4x
-LjARBglghkgBhvhCAQEEBAMCAAcwgYEGA1UdHwR6MHgwSKBGoESkQjBAMQswCQYDVQQGEwJESzEM
-MAoGA1UEChMDVERDMRQwEgYDVQQDEwtUREMgT0NFUyBDQTENMAsGA1UEAxMEQ1JMMTAsoCqgKIYm
-aHR0cDovL2NybC5vY2VzLmNlcnRpZmlrYXQuZGsvb2Nlcy5jcmwwKwYDVR0QBCQwIoAPMjAwMzAy
-MTEwODM5MzBagQ8yMDM3MDIxMTA5MDkzMFowHwYDVR0jBBgwFoAUYLWF7FZkfhIZJ2cdUBVLc647
-+RIwHQYDVR0OBBYEFGC1hexWZH4SGSdnHVAVS3OuO/kSMB0GCSqGSIb2fQdBAAQQMA4bCFY2LjA6
-NC4wAwIEkDANBgkqhkiG9w0BAQUFAAOCAQEACromJkbTc6gJ82sLMJn9iuFXehHTuJTXCRBuo7E4
-A9G28kNBKWKnctj7fAXmMXAnVBhOinxO5dHKjHiIzxvTkIvmI/gLDjNDfZziChmPyQE+dF10yYsc
-A+UYyAFMP8uXBV2YcaaYb7Z8vTd/vuGTJW1v8AqtFxjhA7wHKcitJuj4YfD9IQl+mo6paH1IYnK9
-AOoBmbgGglGBTvH1tJFUuSN6AJqfXY3gPGS5GhKSKseCRHI53OI8xthV9RVOyAUO28bQYqbsFbS1
-AoLbrIyigfCbmTH1ICCoiGEKB5+U/NDXG8wuF/MEJ3Zn61SD/aSQfgY9BKNDLdr8C2LqL19iUw==
------END CERTIFICATE-----
-
-UTN DATACorp SGC Root CA
-========================
------BEGIN CERTIFICATE-----
-MIIEXjCCA0agAwIBAgIQRL4Mi1AAIbQR0ypoBqmtaTANBgkqhkiG9w0BAQUFADCBkzELMAkGA1UE
-BhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2UgQ2l0eTEeMBwGA1UEChMVVGhl
-IFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xGzAZ
-BgNVBAMTElVUTiAtIERBVEFDb3JwIFNHQzAeFw05OTA2MjQxODU3MjFaFw0xOTA2MjQxOTA2MzBa
-MIGTMQswCQYDVQQGEwJVUzELMAkGA1UECBMCVVQxFzAVBgNVBAcTDlNhbHQgTGFrZSBDaXR5MR4w
-HAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxITAfBgNVBAsTGGh0dHA6Ly93d3cudXNlcnRy
-dXN0LmNvbTEbMBkGA1UEAxMSVVROIC0gREFUQUNvcnAgU0dDMIIBIjANBgkqhkiG9w0BAQEFAAOC
-AQ8AMIIBCgKCAQEA3+5YEKIrblXEjr8uRgnn4AgPLit6E5Qbvfa2gI5lBZMAHryv4g+OGQ0SR+ys
-raP6LnD43m77VkIVni5c7yPeIbkFdicZD0/Ww5y0vpQZY/KmEQrrU0icvvIpOxboGqBMpsn0GFlo
-wHDyUwDAXlCCpVZvNvlK4ESGoE1O1kduSUrLZ9emxAW5jh70/P/N5zbgnAVssjMiFdC04MwXwLLA
-9P4yPykqlXvY8qdOD1R8oQ2AswkDwf9c3V6aPryuvEeKaq5xyh+xKrhfQgUL7EYw0XILyulWbfXv
-33i+Ybqypa4ETLyorGkVl73v67SMvzX41MPRKA5cOp9wGDMgd8SirwIDAQABo4GrMIGoMAsGA1Ud
-DwQEAwIBxjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRTMtGzz3/64PGgXYVOktKeRR20TzA9
-BgNVHR8ENjA0MDKgMKAuhixodHRwOi8vY3JsLnVzZXJ0cnVzdC5jb20vVVROLURBVEFDb3JwU0dD
-LmNybDAqBgNVHSUEIzAhBggrBgEFBQcDAQYKKwYBBAGCNwoDAwYJYIZIAYb4QgQBMA0GCSqGSIb3
-DQEBBQUAA4IBAQAnNZcAiosovcYzMB4p/OL31ZjUQLtgyr+rFywJNn9Q+kHcrpY6CiM+iVnJowft
-Gzet/Hy+UUla3joKVAgWRcKZsYfNjGjgaQPpxE6YsjuMFrMOoAyYUJuTqXAJyCyjj98C5OBxOvG0
-I3KgqgHf35g+FFCgMSa9KOlaMCZ1+XtgHI3zzVAmbQQnmt/VDUVHKWss5nbZqSl9Mt3JNjy9rjXx
-EZ4du5A/EkdOjtd+D2JzHVImOBwYSf0wdJrE5SIv2MCN7ZF6TACPcn9d2t0bi0Vr591pl6jFVkwP
-DPafepE39peC4N1xaf92P2BNPM/3mfnGV/TJVTl4uix5yaaIK/QI
------END CERTIFICATE-----
-
-UTN USERFirst Hardware Root CA
-==============================
------BEGIN CERTIFICATE-----
-MIIEdDCCA1ygAwIBAgIQRL4Mi1AAJLQR0zYq/mUK/TANBgkqhkiG9w0BAQUFADCBlzELMAkGA1UE
-BhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2UgQ2l0eTEeMBwGA1UEChMVVGhl
-IFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHzAd
-BgNVBAMTFlVUTi1VU0VSRmlyc3QtSGFyZHdhcmUwHhcNOTkwNzA5MTgxMDQyWhcNMTkwNzA5MTgx
-OTIyWjCBlzELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2UgQ2l0
-eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExhodHRwOi8vd3d3LnVz
-ZXJ0cnVzdC5jb20xHzAdBgNVBAMTFlVUTi1VU0VSRmlyc3QtSGFyZHdhcmUwggEiMA0GCSqGSIb3
-DQEBAQUAA4IBDwAwggEKAoIBAQCx98M4P7Sof885glFn0G2f0v9Y8+efK+wNiVSZuTiZFvfgIXlI
-wrthdBKWHTxqctU8EGc6Oe0rE81m65UJM6Rsl7HoxuzBdXmcRl6Nq9Bq/bkqVRcQVLMZ8Jr28bFd
-tqdt++BxF2uiiPsA3/4aMXcMmgF6sTLjKwEHOG7DpV4jvEWbe1DByTCP2+UretNb+zNAHqDVmBe8
-i4fDidNdoI6yqqr2jmmIBsX6iSHzCJ1pLgkzmykNRg+MzEk0sGlRvfkGzWitZky8PqxhvQqIDsjf
-Pe58BEydCl5rkdbux+0ojatNh4lz0G6k0B4WixThdkQDf2Os5M1JnMWS9KsyoUhbAgMBAAGjgbkw
-gbYwCwYDVR0PBAQDAgHGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFKFyXyYbKJhDlV0HN9WF
-lp1L0sNFMEQGA1UdHwQ9MDswOaA3oDWGM2h0dHA6Ly9jcmwudXNlcnRydXN0LmNvbS9VVE4tVVNF
-UkZpcnN0LUhhcmR3YXJlLmNybDAxBgNVHSUEKjAoBggrBgEFBQcDAQYIKwYBBQUHAwUGCCsGAQUF
-BwMGBggrBgEFBQcDBzANBgkqhkiG9w0BAQUFAAOCAQEARxkP3nTGmZev/K0oXnWO6y1n7k57K9cM
-//bey1WiCuFMVGWTYGufEpytXoMs61quwOQt9ABjHbjAbPLPSbtNk28GpgoiskliCE7/yMgUsogW
-XecB5BKV5UU0s4tpvc+0hY91UZ59Ojg6FEgSxvunOxqNDYJAB+gECJChicsZUN/KHAG8HQQZexB2
-lzvukJDKxA4fFm517zP4029bHpbj4HR3dHuKom4t3XbWOTCC8KucUvIqx69JXn7HaOWCgchqJ/kn
-iCrVWFCVH/A7HFe7fRQ5YiuayZSSKqMiDP+JJn1fIytH1xUdqWqeUQ0qUZ6B+dQ7XnASfxAynB67
-nfhmqA==
------END CERTIFICATE-----
-
-Camerfirma Chambers of Commerce Root
-====================================
------BEGIN CERTIFICATE-----
-MIIEvTCCA6WgAwIBAgIBADANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJFVTEnMCUGA1UEChMe
-QUMgQ2FtZXJmaXJtYSBTQSBDSUYgQTgyNzQzMjg3MSMwIQYDVQQLExpodHRwOi8vd3d3LmNoYW1i
-ZXJzaWduLm9yZzEiMCAGA1UEAxMZQ2hhbWJlcnMgb2YgQ29tbWVyY2UgUm9vdDAeFw0wMzA5MzAx
-NjEzNDNaFw0zNzA5MzAxNjEzNDRaMH8xCzAJBgNVBAYTAkVVMScwJQYDVQQKEx5BQyBDYW1lcmZp
-cm1hIFNBIENJRiBBODI3NDMyODcxIzAhBgNVBAsTGmh0dHA6Ly93d3cuY2hhbWJlcnNpZ24ub3Jn
-MSIwIAYDVQQDExlDaGFtYmVycyBvZiBDb21tZXJjZSBSb290MIIBIDANBgkqhkiG9w0BAQEFAAOC
-AQ0AMIIBCAKCAQEAtzZV5aVdGDDg2olUkfzIx1L4L1DZ77F1c2VHfRtbunXF/KGIJPov7coISjlU
-xFF6tdpg6jg8gbLL8bvZkSM/SAFwdakFKq0fcfPJVD0dBmpAPrMMhe5cG3nCYsS4No41XQEMIwRH
-NaqbYE6gZj3LJgqcQKH0XZi/caulAGgq7YN6D6IUtdQis4CwPAxaUWktWBiP7Zme8a7ileb2R6jW
-DA+wWFjbw2Y3npuRVDM30pQcakjJyfKl2qUMI/cjDpwyVV5xnIQFUZot/eZOKjRa3spAN2cMVCFV
-d9oKDMyXroDclDZK9D7ONhMeU+SsTjoF7Nuucpw4i9A5O4kKPnf+dQIBA6OCAUQwggFAMBIGA1Ud
-EwEB/wQIMAYBAf8CAQwwPAYDVR0fBDUwMzAxoC+gLYYraHR0cDovL2NybC5jaGFtYmVyc2lnbi5v
-cmcvY2hhbWJlcnNyb290LmNybDAdBgNVHQ4EFgQU45T1sU3p26EpW1eLTXYGduHRooowDgYDVR0P
-AQH/BAQDAgEGMBEGCWCGSAGG+EIBAQQEAwIABzAnBgNVHREEIDAegRxjaGFtYmVyc3Jvb3RAY2hh
-bWJlcnNpZ24ub3JnMCcGA1UdEgQgMB6BHGNoYW1iZXJzcm9vdEBjaGFtYmVyc2lnbi5vcmcwWAYD
-VR0gBFEwTzBNBgsrBgEEAYGHLgoDATA+MDwGCCsGAQUFBwIBFjBodHRwOi8vY3BzLmNoYW1iZXJz
-aWduLm9yZy9jcHMvY2hhbWJlcnNyb290Lmh0bWwwDQYJKoZIhvcNAQEFBQADggEBAAxBl8IahsAi
-fJ/7kPMa0QOx7xP5IV8EnNrJpY0nbJaHkb5BkAFyk+cefV/2icZdp0AJPaxJRUXcLo0waLIJuvvD
-L8y6C98/d3tGfToSJI6WjzwFCm/SlCgdbQzALogi1djPHRPH8EjX1wWnz8dHnjs8NMiAT9QUu/wN
-UPf6s+xCX6ndbcj0dc97wXImsQEcXCz9ek60AcUFV7nnPKoF2YjpB0ZBzu9Bga5Y34OirsrXdx/n
-ADydb47kMgkdTXg0eDQ8lJsm7U9xxhl6vSAiSFr+S30Dt+dYvsYyTnQeaN2oaFuzPu5ifdmA6Ap1
-erfutGWaIZDgqtCYvDi1czyL+Nw=
------END CERTIFICATE-----
-
-Camerfirma Global Chambersign Root
-==================================
------BEGIN CERTIFICATE-----
-MIIExTCCA62gAwIBAgIBADANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQGEwJFVTEnMCUGA1UEChMe
-QUMgQ2FtZXJmaXJtYSBTQSBDSUYgQTgyNzQzMjg3MSMwIQYDVQQLExpodHRwOi8vd3d3LmNoYW1i
-ZXJzaWduLm9yZzEgMB4GA1UEAxMXR2xvYmFsIENoYW1iZXJzaWduIFJvb3QwHhcNMDMwOTMwMTYx
-NDE4WhcNMzcwOTMwMTYxNDE4WjB9MQswCQYDVQQGEwJFVTEnMCUGA1UEChMeQUMgQ2FtZXJmaXJt
-YSBTQSBDSUYgQTgyNzQzMjg3MSMwIQYDVQQLExpodHRwOi8vd3d3LmNoYW1iZXJzaWduLm9yZzEg
-MB4GA1UEAxMXR2xvYmFsIENoYW1iZXJzaWduIFJvb3QwggEgMA0GCSqGSIb3DQEBAQUAA4IBDQAw
-ggEIAoIBAQCicKLQn0KuWxfH2H3PFIP8T8mhtxOviteePgQKkotgVvq0Mi+ITaFgCPS3CU6gSS9J
-1tPfnZdan5QEcOw/Wdm3zGaLmFIoCQLfxS+EjXqXd7/sQJ0lcqu1PzKY+7e3/HKE5TWH+VX6ox8O
-by4o3Wmg2UIQxvi1RMLQQ3/bvOSiPGpVeAp3qdjqGTK3L/5cPxvusZjsyq16aUXjlg9V9ubtdepl
-6DJWk0aJqCWKZQbua795B9Dxt6/tLE2Su8CoX6dnfQTyFQhwrJLWfQTSM/tMtgsL+xrJxI0DqX5c
-8lCrEqWhz0hQpe/SyBoT+rB/sYIcd2oPX9wLlY/vQ37mRQklAgEDo4IBUDCCAUwwEgYDVR0TAQH/
-BAgwBgEB/wIBDDA/BgNVHR8EODA2MDSgMqAwhi5odHRwOi8vY3JsLmNoYW1iZXJzaWduLm9yZy9j
-aGFtYmVyc2lnbnJvb3QuY3JsMB0GA1UdDgQWBBRDnDafsJ4wTcbOX60Qq+UDpfqpFDAOBgNVHQ8B
-Af8EBAMCAQYwEQYJYIZIAYb4QgEBBAQDAgAHMCoGA1UdEQQjMCGBH2NoYW1iZXJzaWducm9vdEBj
-aGFtYmVyc2lnbi5vcmcwKgYDVR0SBCMwIYEfY2hhbWJlcnNpZ25yb290QGNoYW1iZXJzaWduLm9y
-ZzBbBgNVHSAEVDBSMFAGCysGAQQBgYcuCgEBMEEwPwYIKwYBBQUHAgEWM2h0dHA6Ly9jcHMuY2hh
-bWJlcnNpZ24ub3JnL2Nwcy9jaGFtYmVyc2lnbnJvb3QuaHRtbDANBgkqhkiG9w0BAQUFAAOCAQEA
-PDtwkfkEVCeR4e3t/mh/YV3lQWVPMvEYBZRqHN4fcNs+ezICNLUMbKGKfKX0j//U2K0X1S0E0T9Y
-gOKBWYi+wONGkyT+kL0mojAt6JcmVzWJdJYY9hXiryQZVgICsroPFOrGimbBhkVVi76SvpykBMdJ
-PJ7oKXqJ1/6v/2j1pReQvayZzKWGVwlnRtvWFsJG8eSpUPWP0ZIV018+xgBJOm5YstHRJw0lyDL4
-IBHNfTIzSJRUTN3cecQwn+uOuFW114hcxWokPbLTBQNRxgfvzBRydD1ucs4YKIxKoHflCStFREes
-t2d/AYoFWpO+ocH/+OcOZ6RHSXZddZAa9SaP8A==
------END CERTIFICATE-----
-
-NetLock Notary (Class A) Root
-=============================
------BEGIN CERTIFICATE-----
-MIIGfTCCBWWgAwIBAgICAQMwDQYJKoZIhvcNAQEEBQAwga8xCzAJBgNVBAYTAkhVMRAwDgYDVQQI
-EwdIdW5nYXJ5MREwDwYDVQQHEwhCdWRhcGVzdDEnMCUGA1UEChMeTmV0TG9jayBIYWxvemF0Yml6
-dG9uc2FnaSBLZnQuMRowGAYDVQQLExFUYW51c2l0dmFueWtpYWRvazE2MDQGA1UEAxMtTmV0TG9j
-ayBLb3pqZWd5em9pIChDbGFzcyBBKSBUYW51c2l0dmFueWtpYWRvMB4XDTk5MDIyNDIzMTQ0N1oX
-DTE5MDIxOTIzMTQ0N1owga8xCzAJBgNVBAYTAkhVMRAwDgYDVQQIEwdIdW5nYXJ5MREwDwYDVQQH
-EwhCdWRhcGVzdDEnMCUGA1UEChMeTmV0TG9jayBIYWxvemF0Yml6dG9uc2FnaSBLZnQuMRowGAYD
-VQQLExFUYW51c2l0dmFueWtpYWRvazE2MDQGA1UEAxMtTmV0TG9jayBLb3pqZWd5em9pIChDbGFz
-cyBBKSBUYW51c2l0dmFueWtpYWRvMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvHSM
-D7tM9DceqQWC2ObhbHDqeLVu0ThEDaiDzl3S1tWBxdRL51uUcCbbO51qTGL3cfNk1mE7PetzozfZ
-z+qMkjvN9wfcZnSX9EUi3fRc4L9t875lM+QVOr/bmJBVOMTtplVjC7B4BPTjbsE/jvxReB+SnoPC
-/tmwqcm8WgD/qaiYdPv2LD4VOQ22BFWoDpggQrOxJa1+mm9dU7GrDPzr4PN6s6iz/0b2Y6LYOph7
-tqyF/7AlT3Rj5xMHpQqPBffAZG9+pyeAlt7ULoZgx2srXnN7F+eRP2QM2EsiNCubMvJIH5+hCoR6
-4sKtlz2O1cH5VqNQ6ca0+pii7pXmKgOM3wIDAQABo4ICnzCCApswDgYDVR0PAQH/BAQDAgAGMBIG
-A1UdEwEB/wQIMAYBAf8CAQQwEQYJYIZIAYb4QgEBBAQDAgAHMIICYAYJYIZIAYb4QgENBIICURaC
-Ak1GSUdZRUxFTSEgRXplbiB0YW51c2l0dmFueSBhIE5ldExvY2sgS2Z0LiBBbHRhbGFub3MgU3pv
-bGdhbHRhdGFzaSBGZWx0ZXRlbGVpYmVuIGxlaXJ0IGVsamFyYXNvayBhbGFwamFuIGtlc3p1bHQu
-IEEgaGl0ZWxlc2l0ZXMgZm9seWFtYXRhdCBhIE5ldExvY2sgS2Z0LiB0ZXJtZWtmZWxlbG9zc2Vn
-LWJpenRvc2l0YXNhIHZlZGkuIEEgZGlnaXRhbGlzIGFsYWlyYXMgZWxmb2dhZGFzYW5hayBmZWx0
-ZXRlbGUgYXogZWxvaXJ0IGVsbGVub3J6ZXNpIGVsamFyYXMgbWVndGV0ZWxlLiBBeiBlbGphcmFz
-IGxlaXJhc2EgbWVndGFsYWxoYXRvIGEgTmV0TG9jayBLZnQuIEludGVybmV0IGhvbmxhcGphbiBh
-IGh0dHBzOi8vd3d3Lm5ldGxvY2submV0L2RvY3MgY2ltZW4gdmFneSBrZXJoZXRvIGF6IGVsbGVu
-b3J6ZXNAbmV0bG9jay5uZXQgZS1tYWlsIGNpbWVuLiBJTVBPUlRBTlQhIFRoZSBpc3N1YW5jZSBh
-bmQgdGhlIHVzZSBvZiB0aGlzIGNlcnRpZmljYXRlIGlzIHN1YmplY3QgdG8gdGhlIE5ldExvY2sg
-Q1BTIGF2YWlsYWJsZSBhdCBodHRwczovL3d3dy5uZXRsb2NrLm5ldC9kb2NzIG9yIGJ5IGUtbWFp
-bCBhdCBjcHNAbmV0bG9jay5uZXQuMA0GCSqGSIb3DQEBBAUAA4IBAQBIJEb3ulZv+sgoA0BO5TE5
-ayZrU3/b39/zcT0mwBQOxmd7I6gMc90Bu8bKbjc5VdXHjFYgDigKDtIqpLBJUsY4B/6+CgmM0ZjP
-ytoUMaFP0jn8DxEsQ8Pdq5PHVT5HfBgaANzze9jyf1JsIPQLX2lS9O74silg6+NJMSEN1rUQQeJB
-CWziGppWS3cC9qCbmieH6FUpccKQn0V4GuEVZD3QDtigdp+uxdAu6tYPVuxkf1qbFFgBJ34TUMdr
-KuZoPL9coAob4Q566eKAw+np9v1sEZ7Q5SgnK1QyQhSCdeZK8CtmdWOMovsEPoMOmzbwGOQmIMOM
-8CgHrTwXZoi1/baI
------END CERTIFICATE-----
-
-NetLock Business (Class B) Root
-===============================
------BEGIN CERTIFICATE-----
-MIIFSzCCBLSgAwIBAgIBaTANBgkqhkiG9w0BAQQFADCBmTELMAkGA1UEBhMCSFUxETAPBgNVBAcT
-CEJ1ZGFwZXN0MScwJQYDVQQKEx5OZXRMb2NrIEhhbG96YXRiaXp0b25zYWdpIEtmdC4xGjAYBgNV
-BAsTEVRhbnVzaXR2YW55a2lhZG9rMTIwMAYDVQQDEylOZXRMb2NrIFV6bGV0aSAoQ2xhc3MgQikg
-VGFudXNpdHZhbnlraWFkbzAeFw05OTAyMjUxNDEwMjJaFw0xOTAyMjAxNDEwMjJaMIGZMQswCQYD
-VQQGEwJIVTERMA8GA1UEBxMIQnVkYXBlc3QxJzAlBgNVBAoTHk5ldExvY2sgSGFsb3phdGJpenRv
-bnNhZ2kgS2Z0LjEaMBgGA1UECxMRVGFudXNpdHZhbnlraWFkb2sxMjAwBgNVBAMTKU5ldExvY2sg
-VXpsZXRpIChDbGFzcyBCKSBUYW51c2l0dmFueWtpYWRvMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB
-iQKBgQCx6gTsIKAjwo84YM/HRrPVG/77uZmeBNwcf4xKgZjupNTKihe5In+DCnVMm8Bp2GQ5o+2S
-o/1bXHQawEfKOml2mrriRBf8TKPV/riXiK+IA4kfpPIEPsgHC+b5sy96YhQJRhTKZPWLgLViqNhr
-1nGTLbO/CVRY7QbrqHvcQ7GhaQIDAQABo4ICnzCCApswEgYDVR0TAQH/BAgwBgEB/wIBBDAOBgNV
-HQ8BAf8EBAMCAAYwEQYJYIZIAYb4QgEBBAQDAgAHMIICYAYJYIZIAYb4QgENBIICURaCAk1GSUdZ
-RUxFTSEgRXplbiB0YW51c2l0dmFueSBhIE5ldExvY2sgS2Z0LiBBbHRhbGFub3MgU3pvbGdhbHRh
-dGFzaSBGZWx0ZXRlbGVpYmVuIGxlaXJ0IGVsamFyYXNvayBhbGFwamFuIGtlc3p1bHQuIEEgaGl0
-ZWxlc2l0ZXMgZm9seWFtYXRhdCBhIE5ldExvY2sgS2Z0LiB0ZXJtZWtmZWxlbG9zc2VnLWJpenRv
-c2l0YXNhIHZlZGkuIEEgZGlnaXRhbGlzIGFsYWlyYXMgZWxmb2dhZGFzYW5hayBmZWx0ZXRlbGUg
-YXogZWxvaXJ0IGVsbGVub3J6ZXNpIGVsamFyYXMgbWVndGV0ZWxlLiBBeiBlbGphcmFzIGxlaXJh
-c2EgbWVndGFsYWxoYXRvIGEgTmV0TG9jayBLZnQuIEludGVybmV0IGhvbmxhcGphbiBhIGh0dHBz
-Oi8vd3d3Lm5ldGxvY2submV0L2RvY3MgY2ltZW4gdmFneSBrZXJoZXRvIGF6IGVsbGVub3J6ZXNA
-bmV0bG9jay5uZXQgZS1tYWlsIGNpbWVuLiBJTVBPUlRBTlQhIFRoZSBpc3N1YW5jZSBhbmQgdGhl
-IHVzZSBvZiB0aGlzIGNlcnRpZmljYXRlIGlzIHN1YmplY3QgdG8gdGhlIE5ldExvY2sgQ1BTIGF2
-YWlsYWJsZSBhdCBodHRwczovL3d3dy5uZXRsb2NrLm5ldC9kb2NzIG9yIGJ5IGUtbWFpbCBhdCBj
-cHNAbmV0bG9jay5uZXQuMA0GCSqGSIb3DQEBBAUAA4GBAATbrowXr/gOkDFOzT4JwG06sPgzTEdM
-43WIEJessDgVkcYplswhwG08pXTP2IKlOcNl40JwuyKQ433bNXbhoLXan3BukxowOR0w2y7jfLKR
-stE3Kfq51hdcR0/jHTjrn9V7lagonhVK0dHQKwCXoOKSNitjrFgBazMpUIaD8QFI
------END CERTIFICATE-----
-
-NetLock Express (Class C) Root
-==============================
------BEGIN CERTIFICATE-----
-MIIFTzCCBLigAwIBAgIBaDANBgkqhkiG9w0BAQQFADCBmzELMAkGA1UEBhMCSFUxETAPBgNVBAcT
-CEJ1ZGFwZXN0MScwJQYDVQQKEx5OZXRMb2NrIEhhbG96YXRiaXp0b25zYWdpIEtmdC4xGjAYBgNV
-BAsTEVRhbnVzaXR2YW55a2lhZG9rMTQwMgYDVQQDEytOZXRMb2NrIEV4cHJlc3N6IChDbGFzcyBD
-KSBUYW51c2l0dmFueWtpYWRvMB4XDTk5MDIyNTE0MDgxMVoXDTE5MDIyMDE0MDgxMVowgZsxCzAJ
-BgNVBAYTAkhVMREwDwYDVQQHEwhCdWRhcGVzdDEnMCUGA1UEChMeTmV0TG9jayBIYWxvemF0Yml6
-dG9uc2FnaSBLZnQuMRowGAYDVQQLExFUYW51c2l0dmFueWtpYWRvazE0MDIGA1UEAxMrTmV0TG9j
-ayBFeHByZXNzeiAoQ2xhc3MgQykgVGFudXNpdHZhbnlraWFkbzCBnzANBgkqhkiG9w0BAQEFAAOB
-jQAwgYkCgYEA6+ywbGGKIyWvYCDj2Z/8kwvbXY2wobNAOoLO/XXgeDIDhlqGlZHtU/qdQPzm6N3Z
-W3oDvV3zOwzDUXmbrVWg6dADEK8KuhRC2VImESLH0iDMgqSaqf64gXadarfSNnU+sYYJ9m5tfk63
-euyucYT2BDMIJTLrdKwWRMbkQJMdf60CAwEAAaOCAp8wggKbMBIGA1UdEwEB/wQIMAYBAf8CAQQw
-DgYDVR0PAQH/BAQDAgAGMBEGCWCGSAGG+EIBAQQEAwIABzCCAmAGCWCGSAGG+EIBDQSCAlEWggJN
-RklHWUVMRU0hIEV6ZW4gdGFudXNpdHZhbnkgYSBOZXRMb2NrIEtmdC4gQWx0YWxhbm9zIFN6b2xn
-YWx0YXRhc2kgRmVsdGV0ZWxlaWJlbiBsZWlydCBlbGphcmFzb2sgYWxhcGphbiBrZXN6dWx0LiBB
-IGhpdGVsZXNpdGVzIGZvbHlhbWF0YXQgYSBOZXRMb2NrIEtmdC4gdGVybWVrZmVsZWxvc3NlZy1i
-aXp0b3NpdGFzYSB2ZWRpLiBBIGRpZ2l0YWxpcyBhbGFpcmFzIGVsZm9nYWRhc2FuYWsgZmVsdGV0
-ZWxlIGF6IGVsb2lydCBlbGxlbm9yemVzaSBlbGphcmFzIG1lZ3RldGVsZS4gQXogZWxqYXJhcyBs
-ZWlyYXNhIG1lZ3RhbGFsaGF0byBhIE5ldExvY2sgS2Z0LiBJbnRlcm5ldCBob25sYXBqYW4gYSBo
-dHRwczovL3d3dy5uZXRsb2NrLm5ldC9kb2NzIGNpbWVuIHZhZ3kga2VyaGV0byBheiBlbGxlbm9y
-emVzQG5ldGxvY2submV0IGUtbWFpbCBjaW1lbi4gSU1QT1JUQU5UISBUaGUgaXNzdWFuY2UgYW5k
-IHRoZSB1c2Ugb2YgdGhpcyBjZXJ0aWZpY2F0ZSBpcyBzdWJqZWN0IHRvIHRoZSBOZXRMb2NrIENQ
-UyBhdmFpbGFibGUgYXQgaHR0cHM6Ly93d3cubmV0bG9jay5uZXQvZG9jcyBvciBieSBlLW1haWwg
-YXQgY3BzQG5ldGxvY2submV0LjANBgkqhkiG9w0BAQQFAAOBgQAQrX/XDDKACtiG8XmYta3UzbM2
-xJZIwVzNmtkFLp++UOv0JhQQLdRmF/iewSf98e3ke0ugbLWrmldwpu2gpO0u9f38vf5NNwgMvOOW
-gyL1SRt/Syu0VMGAfJlOHdCM7tCs5ZL6dVb+ZKATj7i4Fp1hBWeAyNDYpQcCNJgEjTME1A==
------END CERTIFICATE-----
-
-XRamp Global CA Root
-====================
------BEGIN CERTIFICATE-----
-MIIEMDCCAxigAwIBAgIQUJRs7Bjq1ZxN1ZfvdY+grTANBgkqhkiG9w0BAQUFADCBgjELMAkGA1UE
-BhMCVVMxHjAcBgNVBAsTFXd3dy54cmFtcHNlY3VyaXR5LmNvbTEkMCIGA1UEChMbWFJhbXAgU2Vj
-dXJpdHkgU2VydmljZXMgSW5jMS0wKwYDVQQDEyRYUmFtcCBHbG9iYWwgQ2VydGlmaWNhdGlvbiBB
-dXRob3JpdHkwHhcNMDQxMTAxMTcxNDA0WhcNMzUwMTAxMDUzNzE5WjCBgjELMAkGA1UEBhMCVVMx
-HjAcBgNVBAsTFXd3dy54cmFtcHNlY3VyaXR5LmNvbTEkMCIGA1UEChMbWFJhbXAgU2VjdXJpdHkg
-U2VydmljZXMgSW5jMS0wKwYDVQQDEyRYUmFtcCBHbG9iYWwgQ2VydGlmaWNhdGlvbiBBdXRob3Jp
-dHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCYJB69FbS638eMpSe2OAtp87ZOqCwu
-IR1cRN8hXX4jdP5efrRKt6atH67gBhbim1vZZ3RrXYCPKZ2GG9mcDZhtdhAoWORlsH9KmHmf4MMx
-foArtYzAQDsRhtDLooY2YKTVMIJt2W7QDxIEM5dfT2Fa8OT5kavnHTu86M/0ay00fOJIYRyO82FE
-zG+gSqmUsE3a56k0enI4qEHMPJQRfevIpoy3hsvKMzvZPTeL+3o+hiznc9cKV6xkmxnr9A8ECIqs
-AxcZZPRaJSKNNCyy9mgdEm3Tih4U2sSPpuIjhdV6Db1q4Ons7Be7QhtnqiXtRYMh/MHJfNViPvry
-xS3T/dRlAgMBAAGjgZ8wgZwwEwYJKwYBBAGCNxQCBAYeBABDAEEwCwYDVR0PBAQDAgGGMA8GA1Ud
-EwEB/wQFMAMBAf8wHQYDVR0OBBYEFMZPoj0GY4QJnM5i5ASsjVy16bYbMDYGA1UdHwQvMC0wK6Ap
-oCeGJWh0dHA6Ly9jcmwueHJhbXBzZWN1cml0eS5jb20vWEdDQS5jcmwwEAYJKwYBBAGCNxUBBAMC
-AQEwDQYJKoZIhvcNAQEFBQADggEBAJEVOQMBG2f7Shz5CmBbodpNl2L5JFMn14JkTpAuw0kbK5rc
-/Kh4ZzXxHfARvbdI4xD2Dd8/0sm2qlWkSLoC295ZLhVbO50WfUfXN+pfTXYSNrsf16GBBEYgoyxt
-qZ4Bfj8pzgCT3/3JknOJiWSe5yvkHJEs0rnOfc5vMZnT5r7SHpDwCRR5XCOrTdLaIR9NmXmd4c8n
-nxCbHIgNsIpkQTG4DmyQJKSbXHGPurt+HBvbaoAPIbzp26a3QPSyi6mx5O+aGtA9aZnuqCij4Tyz
-8LIRnM98QObd50N9otg6tamN8jSZxNQQ4Qb9CYQQO+7ETPTsJ3xCwnR8gooJybQDJbw=
------END CERTIFICATE-----
-
-Go Daddy Class 2 CA
-===================
------BEGIN CERTIFICATE-----
-MIIEADCCAuigAwIBAgIBADANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEhMB8GA1UEChMY
-VGhlIEdvIERhZGR5IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBEYWRkeSBDbGFzcyAyIENlcnRp
-ZmljYXRpb24gQXV0aG9yaXR5MB4XDTA0MDYyOTE3MDYyMFoXDTM0MDYyOTE3MDYyMFowYzELMAkG
-A1UEBhMCVVMxITAfBgNVBAoTGFRoZSBHbyBEYWRkeSBHcm91cCwgSW5jLjExMC8GA1UECxMoR28g
-RGFkZHkgQ2xhc3MgMiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASAwDQYJKoZIhvcNAQEBBQAD
-ggENADCCAQgCggEBAN6d1+pXGEmhW+vXX0iG6r7d/+TvZxz0ZWizV3GgXne77ZtJ6XCAPVYYYwhv
-2vLM0D9/AlQiVBDYsoHUwHU9S3/Hd8M+eKsaA7Ugay9qK7HFiH7Eux6wwdhFJ2+qN1j3hybX2C32
-qRe3H3I2TqYXP2WYktsqbl2i/ojgC95/5Y0V4evLOtXiEqITLdiOr18SPaAIBQi2XKVlOARFmR6j
-YGB0xUGlcmIbYsUfb18aQr4CUWWoriMYavx4A6lNf4DD+qta/KFApMoZFv6yyO9ecw3ud72a9nmY
-vLEHZ6IVDd2gWMZEewo+YihfukEHU1jPEX44dMX4/7VpkI+EdOqXG68CAQOjgcAwgb0wHQYDVR0O
-BBYEFNLEsNKR1EwRcbNhyz2h/t2oatTjMIGNBgNVHSMEgYUwgYKAFNLEsNKR1EwRcbNhyz2h/t2o
-atTjoWekZTBjMQswCQYDVQQGEwJVUzEhMB8GA1UEChMYVGhlIEdvIERhZGR5IEdyb3VwLCBJbmMu
-MTEwLwYDVQQLEyhHbyBEYWRkeSBDbGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggEAMAwG
-A1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBADJL87LKPpH8EsahB4yOd6AzBhRckB4Y9wim
-PQoZ+YeAEW5p5JYXMP80kWNyOO7MHAGjHZQopDH2esRU1/blMVgDoszOYtuURXO1v0XJJLXVggKt
-I3lpjbi2Tc7PTMozI+gciKqdi0FuFskg5YmezTvacPd+mSYgFFQlq25zheabIZ0KbIIOqPjCDPoQ
-HmyW74cNxA9hi63ugyuV+I6ShHI56yDqg+2DzZduCLzrTia2cyvk0/ZM/iZx4mERdEr/VxqHD3VI
-Ls9RaRegAhJhldXRQLIQTO7ErBBDpqWeCtWVYpoNz4iCxTIM5CufReYNnyicsbkqWletNw+vHX/b
-vZ8=
------END CERTIFICATE-----
-
-Starfield Class 2 CA
-====================
------BEGIN CERTIFICATE-----
-MIIEDzCCAvegAwIBAgIBADANBgkqhkiG9w0BAQUFADBoMQswCQYDVQQGEwJVUzElMCMGA1UEChMc
-U3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMpU3RhcmZpZWxkIENsYXNzIDIg
-Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDQwNjI5MTczOTE2WhcNMzQwNjI5MTczOTE2WjBo
-MQswCQYDVQQGEwJVUzElMCMGA1UEChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAG
-A1UECxMpU3RhcmZpZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggEgMA0GCSqG
-SIb3DQEBAQUAA4IBDQAwggEIAoIBAQC3Msj+6XGmBIWtDBFk385N78gDGIc/oav7PKaf8MOh2tTY
-bitTkPskpD6E8J7oX+zlJ0T1KKY/e97gKvDIr1MvnsoFAZMej2YcOadN+lq2cwQlZut3f+dZxkqZ
-JRRU6ybH838Z1TBwj6+wRir/resp7defqgSHo9T5iaU0X9tDkYI22WY8sbi5gv2cOj4QyDvvBmVm
-epsZGD3/cVE8MC5fvj13c7JdBmzDI1aaK4UmkhynArPkPw2vCHmCuDY96pzTNbO8acr1zJ3o/WSN
-F4Azbl5KXZnJHoe0nRrA1W4TNSNe35tfPe/W93bC6j67eA0cQmdrBNj41tpvi/JEoAGrAgEDo4HF
-MIHCMB0GA1UdDgQWBBS/X7fRzt0fhvRbVazc1xDCDqmI5zCBkgYDVR0jBIGKMIGHgBS/X7fRzt0f
-hvRbVazc1xDCDqmI56FspGowaDELMAkGA1UEBhMCVVMxJTAjBgNVBAoTHFN0YXJmaWVsZCBUZWNo
-bm9sb2dpZXMsIEluYy4xMjAwBgNVBAsTKVN0YXJmaWVsZCBDbGFzcyAyIENlcnRpZmljYXRpb24g
-QXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAAWdP4id0ckaVaGs
-afPzWdqbAYcaT1epoXkJKtv3L7IezMdeatiDh6GX70k1PncGQVhiv45YuApnP+yz3SFmH8lU+nLM
-PUxA2IGvd56Deruix/U0F47ZEUD0/CwqTRV/p2JdLiXTAAsgGh1o+Re49L2L7ShZ3U0WixeDyLJl
-xy16paq8U4Zt3VekyvggQQto8PT7dL5WXXp59fkdheMtlb71cZBDzI0fmgAKhynpVSJYACPq4xJD
-KVtHCN2MQWplBqjlIapBtJUhlbl90TSrE9atvNziPTnNvT51cKEYWQPJIrSPnNVeKtelttQKbfi3
-QBFGmh95DmK/D5fs4C8fF5Q=
------END CERTIFICATE-----
-
-StartCom Certification Authority
-================================
------BEGIN CERTIFICATE-----
-MIIHyTCCBbGgAwIBAgIBATANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQGEwJJTDEWMBQGA1UEChMN
-U3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2lnbmlu
-ZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDYwOTE3MTk0
-NjM2WhcNMzYwOTE3MTk0NjM2WjB9MQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRk
-LjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMg
-U3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAw
-ggIKAoICAQDBiNsJvGxGfHiflXu1M5DycmLWwTYgIiRezul38kMKogZkpMyONvg45iPwbm2xPN1y
-o4UcodM9tDMr0y+v/uqwQVlntsQGfQqedIXWeUyAN3rfOQVSWff0G0ZDpNKFhdLDcfN1YjS6LIp/
-Ho/u7TTQEceWzVI9ujPW3U3eCztKS5/CJi/6tRYccjV3yjxd5srhJosaNnZcAdt0FCX+7bWgiA/d
-eMotHweXMAEtcnn6RtYTKqi5pquDSR3l8u/d5AGOGAqPY1MWhWKpDhk6zLVmpsJrdAfkK+F2PrRt
-2PZE4XNiHzvEvqBTViVsUQn3qqvKv3b9bZvzndu/PWa8DFaqr5hIlTpL36dYUNk4dalb6kMMAv+Z
-6+hsTXBbKWWc3apdzK8BMewM69KN6Oqce+Zu9ydmDBpI125C4z/eIT574Q1w+2OqqGwaVLRcJXrJ
-osmLFqa7LH4XXgVNWG4SHQHuEhANxjJ/GP/89PrNbpHoNkm+Gkhpi8KWTRoSsmkXwQqQ1vp5Iki/
-untp+HDH+no32NgN0nZPV/+Qt+OR0t3vwmC3Zzrd/qqc8NSLf3Iizsafl7b4r4qgEKjZ+xjGtrVc
-UjyJthkqcwEKDwOzEmDyei+B26Nu/yYwl/WL3YlXtq09s68rxbd2AvCl1iuahhQqcvbjM4xdCUsT
-37uMdBNSSwIDAQABo4ICUjCCAk4wDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAa4wHQYDVR0OBBYE
-FE4L7xqkQFulF2mHMMo0aEPQQa7yMGQGA1UdHwRdMFswLKAqoCiGJmh0dHA6Ly9jZXJ0LnN0YXJ0
-Y29tLm9yZy9zZnNjYS1jcmwuY3JsMCugKaAnhiVodHRwOi8vY3JsLnN0YXJ0Y29tLm9yZy9zZnNj
-YS1jcmwuY3JsMIIBXQYDVR0gBIIBVDCCAVAwggFMBgsrBgEEAYG1NwEBATCCATswLwYIKwYBBQUH
-AgEWI2h0dHA6Ly9jZXJ0LnN0YXJ0Y29tLm9yZy9wb2xpY3kucGRmMDUGCCsGAQUFBwIBFilodHRw
-Oi8vY2VydC5zdGFydGNvbS5vcmcvaW50ZXJtZWRpYXRlLnBkZjCB0AYIKwYBBQUHAgIwgcMwJxYg
-U3RhcnQgQ29tbWVyY2lhbCAoU3RhcnRDb20pIEx0ZC4wAwIBARqBl0xpbWl0ZWQgTGlhYmlsaXR5
-LCByZWFkIHRoZSBzZWN0aW9uICpMZWdhbCBMaW1pdGF0aW9ucyogb2YgdGhlIFN0YXJ0Q29tIENl
-cnRpZmljYXRpb24gQXV0aG9yaXR5IFBvbGljeSBhdmFpbGFibGUgYXQgaHR0cDovL2NlcnQuc3Rh
-cnRjb20ub3JnL3BvbGljeS5wZGYwEQYJYIZIAYb4QgEBBAQDAgAHMDgGCWCGSAGG+EIBDQQrFilT
-dGFydENvbSBGcmVlIFNTTCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTANBgkqhkiG9w0BAQUFAAOC
-AgEAFmyZ9GYMNPXQhV59CuzaEE44HF7fpiUFS5Eyweg78T3dRAlbB0mKKctmArexmvclmAk8jhvh
-3TaHK0u7aNM5Zj2gJsfyOZEdUauCe37Vzlrk4gNXcGmXCPleWKYK34wGmkUWFjgKXlf2Ysd6AgXm
-vB618p70qSmD+LIU424oh0TDkBreOKk8rENNZEXO3SipXPJzewT4F+irsfMuXGRuczE6Eri8sxHk
-fY+BUZo7jYn0TZNmezwD7dOaHZrzZVD1oNB1ny+v8OqCQ5j4aZyJecRDjkZy42Q2Eq/3JR44iZB3
-fsNrarnDy0RLrHiQi+fHLB5LEUTINFInzQpdn4XBidUaePKVEFMy3YCEZnXZtWgo+2EuvoSoOMCZ
-EoalHmdkrQYuL6lwhceWD3yJZfWOQ1QOq92lgDmUYMA0yZZwLKMS9R9Ie70cfmu3nZD0Ijuu+Pwq
-yvqCUqDvr0tVk+vBtfAii6w0TiYiBKGHLHVKt+V9E9e4DGTANtLJL4YSjCMJwRuCO3NJo2pXh5Tl
-1njFmUNj403gdy3hZZlyaQQaRwnmDwFWJPsfvw55qVguucQJAX6Vum0ABj6y6koQOdjQK/W/7HW/
-lwLFCRsI3FU34oH7N4RDYiDK51ZLZer+bMEkkyShNOsF/5oirpt9P/FlUQqmMGqz9IgcgA38coro
-g14=
------END CERTIFICATE-----
-
-Taiwan GRCA
-===========
------BEGIN CERTIFICATE-----
-MIIFcjCCA1qgAwIBAgIQH51ZWtcvwgZEpYAIaeNe9jANBgkqhkiG9w0BAQUFADA/MQswCQYDVQQG
-EwJUVzEwMC4GA1UECgwnR292ZXJubWVudCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4X
-DTAyMTIwNTEzMjMzM1oXDTMyMTIwNTEzMjMzM1owPzELMAkGA1UEBhMCVFcxMDAuBgNVBAoMJ0dv
-dmVybm1lbnQgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCAiIwDQYJKoZIhvcNAQEBBQAD
-ggIPADCCAgoCggIBAJoluOzMonWoe/fOW1mKydGGEghU7Jzy50b2iPN86aXfTEc2pBsBHH8eV4qN
-w8XRIePaJD9IK/ufLqGU5ywck9G/GwGHU5nOp/UKIXZ3/6m3xnOUT0b3EEk3+qhZSV1qgQdW8or5
-BtD3cCJNtLdBuTK4sfCxw5w/cP1T3YGq2GN49thTbqGsaoQkclSGxtKyyhwOeYHWtXBiCAEuTk8O
-1RGvqa/lmr/czIdtJuTJV6L7lvnM4T9TjGxMfptTCAtsF/tnyMKtsc2AtJfcdgEWFelq16TheEfO
-htX7MfP6Mb40qij7cEwdScevLJ1tZqa2jWR+tSBqnTuBto9AAGdLiYa4zGX+FVPpBMHWXx1E1wov
-J5pGfaENda1UhhXcSTvxls4Pm6Dso3pdvtUqdULle96ltqqvKKyskKw4t9VoNSZ63Pc78/1Fm9G7
-Q3hub/FCVGqY8A2tl+lSXunVanLeavcbYBT0peS2cWeqH+riTcFCQP5nRhc4L0c/cZyu5SHKYS1t
-B6iEfC3uUSXxY5Ce/eFXiGvviiNtsea9P63RPZYLhY3Naye7twWb7LuRqQoHEgKXTiCQ8P8NHuJB
-O9NAOueNXdpm5AKwB1KYXA6OM5zCppX7VRluTI6uSw+9wThNXo+EHWbNxWCWtFJaBYmOlXqYwZE8
-lSOyDvR5tMl8wUohAgMBAAGjajBoMB0GA1UdDgQWBBTMzO/MKWCkO7GStjz6MmKPrCUVOzAMBgNV
-HRMEBTADAQH/MDkGBGcqBwAEMTAvMC0CAQAwCQYFKw4DAhoFADAHBgVnKgMAAAQUA5vwIhP/lSg2
-09yewDL7MTqKUWUwDQYJKoZIhvcNAQEFBQADggIBAECASvomyc5eMN1PhnR2WPWus4MzeKR6dBcZ
-TulStbngCnRiqmjKeKBMmo4sIy7VahIkv9Ro04rQ2JyftB8M3jh+Vzj8jeJPXgyfqzvS/3WXy6Tj
-Zwj/5cAWtUgBfen5Cv8b5Wppv3ghqMKnI6mGq3ZW6A4M9hPdKmaKZEk9GhiHkASfQlK3T8v+R0F2
-Ne//AHY2RTKbxkaFXeIksB7jSJaYV0eUVXoPQbFEJPPB/hprv4j9wabak2BegUqZIJxIZhm1AHlU
-D7gsL0u8qV1bYH+Mh6XgUmMqvtg7hUAV/h62ZT/FS9p+tXo1KaMuephgIqP0fSdOLeq0dDzpD6Qz
-DxARvBMB1uUO07+1EqLhRSPAzAhuYbeJq4PjJB7mXQfnHyA+z2fI56wwbSdLaG5LKlwCCDTb+Hbk
-Z6MmnD+iMsJKxYEYMRBWqoTvLQr/uB930r+lWKBi5NdLkXWNiYCYfm3LU05er/ayl4WXudpVBrkk
-7tfGOB5jGxI7leFYrPLfhNVfmS8NVVvmONsuP3LpSIXLuykTjx44VbnzssQwmSNOXfJIoRIM3BKQ
-CZBUkQM8R+XVyWXgt0t97EfTsws+rZ7QdAAO671RrcDeLMDDav7v3Aun+kbfYNucpllQdSNpc5Oy
-+fwC00fmcc4QAu4njIT/rEUNE1yDMuAlpYYsfPQS
------END CERTIFICATE-----
-
-Firmaprofesional Root CA
-========================
------BEGIN CERTIFICATE-----
-MIIEVzCCAz+gAwIBAgIBATANBgkqhkiG9w0BAQUFADCBnTELMAkGA1UEBhMCRVMxIjAgBgNVBAcT
-GUMvIE11bnRhbmVyIDI0NCBCYXJjZWxvbmExQjBABgNVBAMTOUF1dG9yaWRhZCBkZSBDZXJ0aWZp
-Y2FjaW9uIEZpcm1hcHJvZmVzaW9uYWwgQ0lGIEE2MjYzNDA2ODEmMCQGCSqGSIb3DQEJARYXY2FA
-ZmlybWFwcm9mZXNpb25hbC5jb20wHhcNMDExMDI0MjIwMDAwWhcNMTMxMDI0MjIwMDAwWjCBnTEL
-MAkGA1UEBhMCRVMxIjAgBgNVBAcTGUMvIE11bnRhbmVyIDI0NCBCYXJjZWxvbmExQjBABgNVBAMT
-OUF1dG9yaWRhZCBkZSBDZXJ0aWZpY2FjaW9uIEZpcm1hcHJvZmVzaW9uYWwgQ0lGIEE2MjYzNDA2
-ODEmMCQGCSqGSIb3DQEJARYXY2FAZmlybWFwcm9mZXNpb25hbC5jb20wggEiMA0GCSqGSIb3DQEB
-AQUAA4IBDwAwggEKAoIBAQDnIwNvbyOlXnjOlSztlB5uCp4Bx+ow0Syd3Tfom5h5VtP8c9/Qit5V
-j1H5WuretXDE7aTt/6MNbg9kUDGvASdYrv5sp0ovFy3Tc9UTHI9ZpTQsHVQERc1ouKDAA6XPhUJH
-lShbz++AbOCQl4oBPB3zhxAwJkh91/zpnZFx/0GaqUC1N5wpIE8fUuOgfRNtVLcK3ulqTgesrBlf
-3H5idPayBQC6haD9HThuy1q7hryUZzM1gywfI834yJFxzJeL764P3CkDG8A563DtwW4O2GcLiam8
-NeTvtjS0pbbELaW+0MOUJEjb35bTALVmGotmBQ/dPz/LP6pemkr4tErvlTcbAgMBAAGjgZ8wgZww
-KgYDVR0RBCMwIYYfaHR0cDovL3d3dy5maXJtYXByb2Zlc2lvbmFsLmNvbTASBgNVHRMBAf8ECDAG
-AQH/AgEBMCsGA1UdEAQkMCKADzIwMDExMDI0MjIwMDAwWoEPMjAxMzEwMjQyMjAwMDBaMA4GA1Ud
-DwEB/wQEAwIBBjAdBgNVHQ4EFgQUMwugZtHq2s7eYpMEKFK1FH84aLcwDQYJKoZIhvcNAQEFBQAD
-ggEBAEdz/o0nVPD11HecJ3lXV7cVVuzH2Fi3AQL0M+2TUIiefEaxvT8Ub/GzR0iLjJcG1+p+o1wq
-u00vR+L4OQbJnC4xGgN49Lw4xiKLMzHwFgQEffl25EvXwOaD7FnMP97/T2u3Z36mhoEyIwOdyPdf
-wUpgpZKpsaSgYMN4h7Mi8yrrW6ntBas3D7Hi05V2Y1Z0jFhyGzflZKG+TQyTmAyX9odtsz/ny4Cm
-7YjHX1BiAuiZdBbQ5rQ58SfLyEDW44YQqSMSkuBpQWOnryULwMWSyx6Yo1q6xTMPoJcB3X/ge9YG
-VM+h4k0460tQtcsm9MracEpqoeJ5quGnM/b9Sh/22WA=
------END CERTIFICATE-----
-
-Wells Fargo Root CA
-===================
------BEGIN CERTIFICATE-----
-MIID5TCCAs2gAwIBAgIEOeSXnjANBgkqhkiG9w0BAQUFADCBgjELMAkGA1UEBhMCVVMxFDASBgNV
-BAoTC1dlbGxzIEZhcmdvMSwwKgYDVQQLEyNXZWxscyBGYXJnbyBDZXJ0aWZpY2F0aW9uIEF1dGhv
-cml0eTEvMC0GA1UEAxMmV2VsbHMgRmFyZ28gUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwHhcN
-MDAxMDExMTY0MTI4WhcNMjEwMTE0MTY0MTI4WjCBgjELMAkGA1UEBhMCVVMxFDASBgNVBAoTC1dl
-bGxzIEZhcmdvMSwwKgYDVQQLEyNXZWxscyBGYXJnbyBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTEv
-MC0GA1UEAxMmV2VsbHMgRmFyZ28gUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwggEiMA0GCSqG
-SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDVqDM7Jvk0/82bfuUER84A4n135zHCLielTWi5MbqNQ1mX
-x3Oqfz1cQJ4F5aHiidlMuD+b+Qy0yGIZLEWukR5zcUHESxP9cMIlrCL1dQu3U+SlK93OvRw6esP3
-E48mVJwWa2uv+9iWsWCaSOAlIiR5NM4OJgALTqv9i86C1y8IcGjBqAr5dE8Hq6T54oN+J3N0Prj5
-OEL8pahbSCOz6+MlsoCultQKnMJ4msZoGK43YjdeUXWoWGPAUe5AeH6orxqg4bB4nVCMe+ez/I4j
-sNtlAHCEAQgAFG5Uhpq6zPk3EPbg3oQtnaSFN9OH4xXQwReQfhkhahKpdv0SAulPIV4XAgMBAAGj
-YTBfMA8GA1UdEwEB/wQFMAMBAf8wTAYDVR0gBEUwQzBBBgtghkgBhvt7hwcBCzAyMDAGCCsGAQUF
-BwIBFiRodHRwOi8vd3d3LndlbGxzZmFyZ28uY29tL2NlcnRwb2xpY3kwDQYJKoZIhvcNAQEFBQAD
-ggEBANIn3ZwKdyu7IvICtUpKkfnRLb7kuxpo7w6kAOnu5+/u9vnldKTC2FJYxHT7zmu1Oyl5GFrv
-m+0fazbuSCUlFLZWohDo7qd/0D+j0MNdJu4HzMPBJCGHHt8qElNvQRbn7a6U+oxy+hNH8Dx+rn0R
-OhPs7fpvcmR7nX1/Jv16+yWt6j4pf0zjAFcysLPp7VMX2YuyFA4w6OXVE8Zkr8QA1dhYJPz1j+zx
-x32l2w8n0cbyQIjmH/ZhqPRCyLk306m+LFZ4wnKbWV01QIroTmMatukgalHizqSQ33ZwmVxwQ023
-tqcZZE6St8WRPH9IFmV7Fv3L/PvZ1dZPIWU7Sn9Ho/s=
------END CERTIFICATE-----
-
-Swisscom Root CA 1
-==================
------BEGIN CERTIFICATE-----
-MIIF2TCCA8GgAwIBAgIQXAuFXAvnWUHfV8w/f52oNjANBgkqhkiG9w0BAQUFADBkMQswCQYDVQQG
-EwJjaDERMA8GA1UEChMIU3dpc3Njb20xJTAjBgNVBAsTHERpZ2l0YWwgQ2VydGlmaWNhdGUgU2Vy
-dmljZXMxGzAZBgNVBAMTElN3aXNzY29tIFJvb3QgQ0EgMTAeFw0wNTA4MTgxMjA2MjBaFw0yNTA4
-MTgyMjA2MjBaMGQxCzAJBgNVBAYTAmNoMREwDwYDVQQKEwhTd2lzc2NvbTElMCMGA1UECxMcRGln
-aXRhbCBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczEbMBkGA1UEAxMSU3dpc3Njb20gUm9vdCBDQSAxMIIC
-IjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA0LmwqAzZuz8h+BvVM5OAFmUgdbI9m2BtRsiM
-MW8Xw/qabFbtPMWRV8PNq5ZJkCoZSx6jbVfd8StiKHVFXqrWW/oLJdihFvkcxC7mlSpnzNApbjyF
-NDhhSbEAn9Y6cV9Nbc5fuankiX9qUvrKm/LcqfmdmUc/TilftKaNXXsLmREDA/7n29uj/x2lzZAe
-AR81sH8A25Bvxn570e56eqeqDFdvpG3FEzuwpdntMhy0XmeLVNxzh+XTF3xmUHJd1BpYwdnP2IkC
-b6dJtDZd0KTeByy2dbcokdaXvij1mB7qWybJvbCXc9qukSbraMH5ORXWZ0sKbU/Lz7DkQnGMU3nn
-7uHbHaBuHYwadzVcFh4rUx80i9Fs/PJnB3r1re3WmquhsUvhzDdf/X/NTa64H5xD+SpYVUNFvJbN
-cA78yeNmuk6NO4HLFWR7uZToXTNShXEuT46iBhFRyePLoW4xCGQMwtI89Tbo19AOeCMgkckkKmUp
-WyL3Ic6DXqTz3kvTaI9GdVyDCW4pa8RwjPWd1yAv/0bSKzjCL3UcPX7ape8eYIVpQtPM+GP+HkM5
-haa2Y0EQs3MevNP6yn0WR+Kn1dCjigoIlmJWbjTb2QK5MHXjBNLnj8KwEUAKrNVxAmKLMb7dxiNY
-MUJDLXT5xp6mig/p/r+D5kNXJLrvRjSq1xIBOO0CAwEAAaOBhjCBgzAOBgNVHQ8BAf8EBAMCAYYw
-HQYDVR0hBBYwFDASBgdghXQBUwABBgdghXQBUwABMBIGA1UdEwEB/wQIMAYBAf8CAQcwHwYDVR0j
-BBgwFoAUAyUv3m+CATpcLNwroWm1Z9SM0/0wHQYDVR0OBBYEFAMlL95vggE6XCzcK6FptWfUjNP9
-MA0GCSqGSIb3DQEBBQUAA4ICAQA1EMvspgQNDQ/NwNurqPKIlwzfky9NfEBWMXrrpA9gzXrzvsMn
-jgM+pN0S734edAY8PzHyHHuRMSG08NBsl9Tpl7IkVh5WwzW9iAUPWxAaZOHHgjD5Mq2eUCzneAXQ
-MbFamIp1TpBcahQq4FJHgmDmHtqBsfsUC1rxn9KVuj7QG9YVHaO+htXbD8BJZLsuUBlL0iT43R4H
-VtA4oJVwIHaM190e3p9xxCPvgxNcoyQVTSlAPGrEqdi3pkSlDfTgnXceQHAm/NrZNuR55LU/vJtl
-vrsRls/bxig5OgjOR1tTWsWZ/l2p3e9M1MalrQLmjAcSHm8D0W+go/MpvRLHUKKwf4ipmXeascCl
-OS5cfGniLLDqN2qk4Vrh9VDlg++luyqI54zb/W1elxmofmZ1a3Hqv7HHb6D0jqTsNFFbjCYDcKF3
-1QESVwA12yPeDooomf2xEG9L/zgtYE4snOtnta1J7ksfrK/7DZBaZmBwXarNeNQk7shBoJMBkpxq
-nvy5JMWzFYJ+vq6VK+uxwNrjAWALXmmshFZhvnEX/h0TD/7Gh0Xp/jKgGg0TpJRVcaUWi7rKibCy
-x/yP2FS1k2Kdzs9Z+z0YzirLNRWCXf9UIltxUvu3yf5gmwBBZPCqKuy2QkPOiWaByIufOVQDJdMW
-NY6E0F/6MBr1mmz0DlP5OlvRHA==
------END CERTIFICATE-----
-
-DigiCert Assured ID Root CA
-===========================
------BEGIN CERTIFICATE-----
-MIIDtzCCAp+gAwIBAgIQDOfg5RfYRv6P5WD8G/AwOTANBgkqhkiG9w0BAQUFADBlMQswCQYDVQQG
-EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSQw
-IgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0EwHhcNMDYxMTEwMDAwMDAwWhcNMzEx
-MTEwMDAwMDAwWjBlMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQL
-ExB3d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0Ew
-ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCtDhXO5EOAXLGH87dg+XESpa7cJpSIqvTO
-9SA5KFhgDPiA2qkVlTJhPLWxKISKityfCgyDF3qPkKyK53lTXDGEKvYPmDI2dsze3Tyoou9q+yHy
-UmHfnyDXH+Kx2f4YZNISW1/5WBg1vEfNoTb5a3/UsDg+wRvDjDPZ2C8Y/igPs6eD1sNuRMBhNZYW
-/lmci3Zt1/GiSw0r/wty2p5g0I6QNcZ4VYcgoc/lbQrISXwxmDNsIumH0DJaoroTghHtORedmTpy
-oeb6pNnVFzF1roV9Iq4/AUaG9ih5yLHa5FcXxH4cDrC0kqZWs72yl+2qp/C3xag/lRbQ/6GW6whf
-GHdPAgMBAAGjYzBhMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRF
-66Kv9JLLgjEtUYunpyGd823IDzAfBgNVHSMEGDAWgBRF66Kv9JLLgjEtUYunpyGd823IDzANBgkq
-hkiG9w0BAQUFAAOCAQEAog683+Lt8ONyc3pklL/3cmbYMuRCdWKuh+vy1dneVrOfzM4UKLkNl2Bc
-EkxY5NM9g0lFWJc1aRqoR+pWxnmrEthngYTffwk8lOa4JiwgvT2zKIn3X/8i4peEH+ll74fg38Fn
-SbNd67IJKusm7Xi+fT8r87cmNW1fiQG2SVufAQWbqz0lwcy2f8Lxb4bG+mRo64EtlOtCt/qMHt1i
-8b5QZ7dsvfPxH2sMNgcWfzd8qVttevESRmCD1ycEvkvOl77DZypoEd+A5wwzZr8TDRRu838fYxAe
-+o0bJW1sj6W3YQGx0qMmoRBxna3iw/nDmVG3KwcIzi7mULKn+gpFL6Lw8g==
------END CERTIFICATE-----
-
-DigiCert Global Root CA
-=======================
------BEGIN CERTIFICATE-----
-MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBhMQswCQYDVQQG
-EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSAw
-HgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBDQTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAw
-MDAwMDBaMGExCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3
-dy5kaWdpY2VydC5jb20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkq
-hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsBCSDMAZOn
-TjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97nh6Vfe63SKMI2tavegw5
-BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt43C/dxC//AH2hdmoRBBYMql1GNXRor5H
-4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7PT19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y
-7vrTC0LUq7dBMtoM1O/4gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQAB
-o2MwYTAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbRTLtm
-8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUwDQYJKoZIhvcNAQEF
-BQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/EsrhMAtudXH/vTBH1jLuG2cenTnmCmr
-EbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIt
-tep3Sp+dWOIrWcBAI+0tKIJFPnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886
-UAb3LujEV0lsYSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk
-CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=
------END CERTIFICATE-----
-
-DigiCert High Assurance EV Root CA
-==================================
------BEGIN CERTIFICATE-----
-MIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBsMQswCQYDVQQG
-EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSsw
-KQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5jZSBFViBSb290IENBMB4XDTA2MTExMDAwMDAw
-MFoXDTMxMTExMDAwMDAwMFowbDELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZ
-MBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFu
-Y2UgRVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm+9S75S0t
-Mqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTWPNt0OKRKzE0lgvdKpVMS
-OO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEMxChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3
-MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFBIk5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQ
-NAQTXKFx01p8VdteZOE3hzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUe
-h10aUAsgEsxBu24LUTi4S8sCAwEAAaNjMGEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQFMAMB
-Af8wHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMB8GA1UdIwQYMBaAFLE+w2kD+L9HAdSY
-JhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3NecnzyIZgYIVyHbIUf4KmeqvxgydkAQ
-V8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6zeM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFp
-myPInngiK3BD41VHMWEZ71jFhS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkK
-mNEVX58Svnw2Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe
-vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep+OkuE6N36B9K
------END CERTIFICATE-----
-
-Certplus Class 2 Primary CA
-===========================
------BEGIN CERTIFICATE-----
-MIIDkjCCAnqgAwIBAgIRAIW9S/PY2uNp9pTXX8OlRCMwDQYJKoZIhvcNAQEFBQAwPTELMAkGA1UE
-BhMCRlIxETAPBgNVBAoTCENlcnRwbHVzMRswGQYDVQQDExJDbGFzcyAyIFByaW1hcnkgQ0EwHhcN
-OTkwNzA3MTcwNTAwWhcNMTkwNzA2MjM1OTU5WjA9MQswCQYDVQQGEwJGUjERMA8GA1UEChMIQ2Vy
-dHBsdXMxGzAZBgNVBAMTEkNsYXNzIDIgUHJpbWFyeSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEP
-ADCCAQoCggEBANxQltAS+DXSCHh6tlJw/W/uz7kRy1134ezpfgSN1sxvc0NXYKwzCkTsA18cgCSR
-5aiRVhKC9+Ar9NuuYS6JEI1rbLqzAr3VNsVINyPi8Fo3UjMXEuLRYE2+L0ER4/YXJQyLkcAbmXuZ
-Vg2v7tK8R1fjeUl7NIknJITesezpWE7+Tt9avkGtrAjFGA7v0lPubNCdEgETjdyAYveVqUSISnFO
-YFWe2yMZeVYHDD9jC1yw4r5+FfyUM1hBOHTE4Y+L3yasH7WLO7dDWWuwJKZtkIvEcupdM5i3y95e
-e++U8Rs+yskhwcWYAqqi9lt3m/V+llU0HGdpwPFC40es/CgcZlUCAwEAAaOBjDCBiTAPBgNVHRME
-CDAGAQH/AgEKMAsGA1UdDwQEAwIBBjAdBgNVHQ4EFgQU43Mt38sOKAze3bOkynm4jrvoMIkwEQYJ
-YIZIAYb4QgEBBAQDAgEGMDcGA1UdHwQwMC4wLKAqoCiGJmh0dHA6Ly93d3cuY2VydHBsdXMuY29t
-L0NSTC9jbGFzczIuY3JsMA0GCSqGSIb3DQEBBQUAA4IBAQCnVM+IRBnL39R/AN9WM2K191EBkOvD
-P9GIROkkXe/nFL0gt5o8AP5tn9uQ3Nf0YtaLcF3n5QRIqWh8yfFC82x/xXp8HVGIutIKPidd3i1R
-TtMTZGnkLuPT55sJmabglZvOGtd/vjzOUrMRFcEPF80Du5wlFbqidon8BvEY0JNLDnyCt6X09l/+
-7UCmnYR0ObncHoUW2ikbhiMAybuJfm6AiB4vFLQDJKgybwOaRywwvlbGp0ICcBvqQNi6BQNwB6SW
-//1IMwrh3KWBkJtN3X3n57LNXMhqlfil9o3EXXgIvnsG1knPGTZQIy4I5p4FTUcY1Rbpsda2ENW7
-l7+ijrRU
------END CERTIFICATE-----
-
-DST Root CA X3
-==============
------BEGIN CERTIFICATE-----
-MIIDSjCCAjKgAwIBAgIQRK+wgNajJ7qJMDmGLvhAazANBgkqhkiG9w0BAQUFADA/MSQwIgYDVQQK
-ExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMTDkRTVCBSb290IENBIFgzMB4X
-DTAwMDkzMDIxMTIxOVoXDTIxMDkzMDE0MDExNVowPzEkMCIGA1UEChMbRGlnaXRhbCBTaWduYXR1
-cmUgVHJ1c3QgQ28uMRcwFQYDVQQDEw5EU1QgUm9vdCBDQSBYMzCCASIwDQYJKoZIhvcNAQEBBQAD
-ggEPADCCAQoCggEBAN+v6ZdQCINXtMxiZfaQguzH0yxrMMpb7NnDfcdAwRgUi+DoM3ZJKuM/IUmT
-rE4Orz5Iy2Xu/NMhD2XSKtkyj4zl93ewEnu1lcCJo6m67XMuegwGMoOifooUMM0RoOEqOLl5CjH9
-UL2AZd+3UWODyOKIYepLYYHsUmu5ouJLGiifSKOeDNoJjj4XLh7dIN9bxiqKqy69cK3FCxolkHRy
-xXtqqzTWMIn/5WgTe1QLyNau7Fqckh49ZLOMxt+/yUFw7BZy1SbsOFU5Q9D8/RhcQPGX69Wam40d
-utolucbY38EVAjqr2m7xPi71XAicPNaDaeQQmxkqtilX4+U9m5/wAl0CAwEAAaNCMEAwDwYDVR0T
-AQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFMSnsaR7LHH62+FLkHX/xBVghYkQ
-MA0GCSqGSIb3DQEBBQUAA4IBAQCjGiybFwBcqR7uKGY3Or+Dxz9LwwmglSBd49lZRNI+DT69ikug
-dB/OEIKcdBodfpga3csTS7MgROSR6cz8faXbauX+5v3gTt23ADq1cEmv8uXrAvHRAosZy5Q6XkjE
-GB5YGV8eAlrwDPGxrancWYaLbumR9YbK+rlmM6pZW87ipxZzR8srzJmwN0jP41ZL9c8PDHIyh8bw
-RLtTcm1D9SZImlJnt1ir/md2cXjbDaJWFBM5JDGFoqgCWjBH4d1QB7wCCZAA62RjYJsWvIjJEubS
-fZGL+T0yjWW06XyxV3bqxbYoOb8VZRzI9neWagqNdwvYkQsEjgfbKbYK7p2CNTUQ
------END CERTIFICATE-----
-
-DST ACES CA X6
-==============
------BEGIN CERTIFICATE-----
-MIIECTCCAvGgAwIBAgIQDV6ZCtadt3js2AdWO4YV2TANBgkqhkiG9w0BAQUFADBbMQswCQYDVQQG
-EwJVUzEgMB4GA1UEChMXRGlnaXRhbCBTaWduYXR1cmUgVHJ1c3QxETAPBgNVBAsTCERTVCBBQ0VT
-MRcwFQYDVQQDEw5EU1QgQUNFUyBDQSBYNjAeFw0wMzExMjAyMTE5NThaFw0xNzExMjAyMTE5NTha
-MFsxCzAJBgNVBAYTAlVTMSAwHgYDVQQKExdEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdDERMA8GA1UE
-CxMIRFNUIEFDRVMxFzAVBgNVBAMTDkRTVCBBQ0VTIENBIFg2MIIBIjANBgkqhkiG9w0BAQEFAAOC
-AQ8AMIIBCgKCAQEAuT31LMmU3HWKlV1j6IR3dma5WZFcRt2SPp/5DgO0PWGSvSMmtWPuktKe1jzI
-DZBfZIGxqAgNTNj50wUoUrQBJcWVHAx+PhCEdc/BGZFjz+iokYi5Q1K7gLFViYsx+tC3dr5BPTCa
-pCIlF3PoHuLTrCq9Wzgh1SpL11V94zpVvddtawJXa+ZHfAjIgrrep4c9oW24MFbCswKBXy314pow
-GCi4ZtPLAZZv6opFVdbgnf9nKxcCpk4aahELfrd755jWjHZvwTvbUJN+5dCOHze4vbrGn2zpfDPy
-MjwmR/onJALJfh1biEITajV8fTXpLmaRcpPVMibEdPVTo7NdmvYJywIDAQABo4HIMIHFMA8GA1Ud
-EwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgHGMB8GA1UdEQQYMBaBFHBraS1vcHNAdHJ1c3Rkc3Qu
-Y29tMGIGA1UdIARbMFkwVwYKYIZIAWUDAgEBATBJMEcGCCsGAQUFBwIBFjtodHRwOi8vd3d3LnRy
-dXN0ZHN0LmNvbS9jZXJ0aWZpY2F0ZXMvcG9saWN5L0FDRVMtaW5kZXguaHRtbDAdBgNVHQ4EFgQU
-CXIGThhDD+XWzMNqizF7eI+og7gwDQYJKoZIhvcNAQEFBQADggEBAKPYjtay284F5zLNAdMEA+V2
-5FYrnJmQ6AgwbN99Pe7lv7UkQIRJ4dEorsTCOlMwiPH1d25Ryvr/ma8kXxug/fKshMrfqfBfBC6t
-Fr8hlxCBPeP/h40y3JTlR4peahPJlJU90u7INJXQgNStMgiAVDzgvVJT11J8smk/f3rPanTK+gQq
-nExaBqXpIK1FZg9p8d2/6eMyi/rgwYZNcjwu2JN4Cir42NInPRmJX1p7ijvMDNpRrscL9yuwNwXs
-vFcj4jjSm2jzVhKIT0J8uDHEtdvkyCE06UgRNe76x5JXxZ805Mf29w4LTJxoeHtxMcfrHuBnQfO3
-oKfN5XozNmr6mis=
------END CERTIFICATE-----
-
-TURKTRUST Certificate Services Provider Root 1
-==============================================
------BEGIN CERTIFICATE-----
-MIID+zCCAuOgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBtzE/MD0GA1UEAww2VMOcUktUUlVTVCBF
-bGVrdHJvbmlrIFNlcnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sxc8SxMQswCQYDVQQGDAJUUjEP
-MA0GA1UEBwwGQU5LQVJBMVYwVAYDVQQKDE0oYykgMjAwNSBUw5xSS1RSVVNUIEJpbGdpIMSwbGV0
-acWfaW0gdmUgQmlsacWfaW0gR8O8dmVubGnEn2kgSGl6bWV0bGVyaSBBLsWeLjAeFw0wNTA1MTMx
-MDI3MTdaFw0xNTAzMjIxMDI3MTdaMIG3MT8wPQYDVQQDDDZUw5xSS1RSVVNUIEVsZWt0cm9uaWsg
-U2VydGlmaWthIEhpem1ldCBTYcSfbGF5xLFjxLFzxLExCzAJBgNVBAYMAlRSMQ8wDQYDVQQHDAZB
-TktBUkExVjBUBgNVBAoMTShjKSAyMDA1IFTDnFJLVFJVU1QgQmlsZ2kgxLBsZXRpxZ9pbSB2ZSBC
-aWxpxZ9pbSBHw7x2ZW5sacSfaSBIaXptZXRsZXJpIEEuxZ4uMIIBIjANBgkqhkiG9w0BAQEFAAOC
-AQ8AMIIBCgKCAQEAylIF1mMD2Bxf3dJ7XfIMYGFbazt0K3gNfUW9InTojAPBxhEqPZW8qZSwu5GX
-yGl8hMW0kWxsE2qkVa2kheiVfrMArwDCBRj1cJ02i67L5BuBf5OI+2pVu32Fks66WJ/bMsW9Xe8i
-Si9BB35JYbOG7E6mQW6EvAPs9TscyB/C7qju6hJKjRTP8wrgUDn5CDX4EVmt5yLqS8oUBt5CurKZ
-8y1UiBAG6uEaPj1nH/vO+3yC6BFdSsG5FOpU2WabfIl9BJpiyelSPJ6c79L1JuTm5Rh8i27fbMx4
-W09ysstcP4wFjdFMjK2Sx+F4f2VsSQZQLJ4ywtdKxnWKWU51b0dewQIDAQABoxAwDjAMBgNVHRME
-BTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQAV9VX/N5aAWSGk/KEVTCD21F/aAyT8z5Aa9CEKmu46
-sWrv7/hg0Uw2ZkUd82YCdAR7kjCo3gp2D++Vbr3JN+YaDayJSFvMgzbC9UZcWYJWtNX+I7TYVBxE
-q8Sn5RTOPEFhfEPmzcSBCYsk+1Ql1haolgxnB2+zUEfjHCQo3SqYpGH+2+oSN7wBGjSFvW5P55Fy
-B0SFHljKVETd96y5y4khctuPwGkplyqjrhgjlxxBKot8KsF8kOipKMDTkcatKIdAaLX/7KfS0zgY
-nNN9aV3wxqUeJBujR/xpB2jn5Jq07Q+hh4cCzofSSE7hvP/L8XKSRGQDJereW26fyfJOrN3H
------END CERTIFICATE-----
-
-TURKTRUST Certificate Services Provider Root 2
-==============================================
------BEGIN CERTIFICATE-----
-MIIEPDCCAySgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBvjE/MD0GA1UEAww2VMOcUktUUlVTVCBF
-bGVrdHJvbmlrIFNlcnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sxc8SxMQswCQYDVQQGEwJUUjEP
-MA0GA1UEBwwGQW5rYXJhMV0wWwYDVQQKDFRUw5xSS1RSVVNUIEJpbGdpIMSwbGV0acWfaW0gdmUg
-QmlsacWfaW0gR8O8dmVubGnEn2kgSGl6bWV0bGVyaSBBLsWeLiAoYykgS2FzxLFtIDIwMDUwHhcN
-MDUxMTA3MTAwNzU3WhcNMTUwOTE2MTAwNzU3WjCBvjE/MD0GA1UEAww2VMOcUktUUlVTVCBFbGVr
-dHJvbmlrIFNlcnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sxc8SxMQswCQYDVQQGEwJUUjEPMA0G
-A1UEBwwGQW5rYXJhMV0wWwYDVQQKDFRUw5xSS1RSVVNUIEJpbGdpIMSwbGV0acWfaW0gdmUgQmls
-acWfaW0gR8O8dmVubGnEn2kgSGl6bWV0bGVyaSBBLsWeLiAoYykgS2FzxLFtIDIwMDUwggEiMA0G
-CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCpNn7DkUNMwxmYCMjHWHtPFoylzkkBH3MOrHUTpvqe
-LCDe2JAOCtFp0if7qnefJ1Il4std2NiDUBd9irWCPwSOtNXwSadktx4uXyCcUHVPr+G1QRT0mJKI
-x+XlZEdhR3n9wFHxwZnn3M5q+6+1ATDcRhzviuyV79z/rxAc653YsKpqhRgNF8k+v/Gb0AmJQv2g
-QrSdiVFVKc8bcLyEVK3BEx+Y9C52YItdP5qtygy/p1Zbj3e41Z55SZI/4PGXJHpsmxcPbe9TmJEr
-5A++WXkHeLuXlfSfadRYhwqp48y2WBmfJiGxxFmNskF1wK1pzpwACPI2/z7woQ8arBT9pmAPAgMB
-AAGjQzBBMB0GA1UdDgQWBBTZN7NOBf3Zz58SFq62iS/rJTqIHDAPBgNVHQ8BAf8EBQMDBwYAMA8G
-A1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAHJglrfJ3NgpXiOFX7KzLXb7iNcX/ntt
-Rbj2hWyfIvwqECLsqrkw9qtY1jkQMZkpAL2JZkH7dN6RwRgLn7Vhy506vvWolKMiVW4XSf/SKfE4
-Jl3vpao6+XF75tpYHdN0wgH6PmlYX63LaL4ULptswLbcoCb6dxriJNoaN+BnrdFzgw2lGh1uEpJ+
-hGIAF728JRhX8tepb1mIvDS3LoV4nZbcFMMsilKbloxSZj2GFotHuFEJjOp9zYhys2AzsfAKRO8P
-9Qk3iCQOLGsgOqL6EfJANZxEaGM7rDNvY7wsu/LSy3Z9fYjYHcgFHW68lKlmjHdxx/qR+i9Rnuk5
-UrbnBEI=
------END CERTIFICATE-----
-
-SwissSign Gold CA - G2
-======================
------BEGIN CERTIFICATE-----
-MIIFujCCA6KgAwIBAgIJALtAHEP1Xk+wMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNVBAYTAkNIMRUw
-EwYDVQQKEwxTd2lzc1NpZ24gQUcxHzAdBgNVBAMTFlN3aXNzU2lnbiBHb2xkIENBIC0gRzIwHhcN
-MDYxMDI1MDgzMDM1WhcNMzYxMDI1MDgzMDM1WjBFMQswCQYDVQQGEwJDSDEVMBMGA1UEChMMU3dp
-c3NTaWduIEFHMR8wHQYDVQQDExZTd2lzc1NpZ24gR29sZCBDQSAtIEcyMIICIjANBgkqhkiG9w0B
-AQEFAAOCAg8AMIICCgKCAgEAr+TufoskDhJuqVAtFkQ7kpJcyrhdhJJCEyq8ZVeCQD5XJM1QiyUq
-t2/876LQwB8CJEoTlo8jE+YoWACjR8cGp4QjK7u9lit/VcyLwVcfDmJlD909Vopz2q5+bbqBHH5C
-jCA12UNNhPqE21Is8w4ndwtrvxEvcnifLtg+5hg3Wipy+dpikJKVyh+c6bM8K8vzARO/Ws/BtQpg
-vd21mWRTuKCWs2/iJneRjOBiEAKfNA+k1ZIzUd6+jbqEemA8atufK+ze3gE/bk3lUIbLtK/tREDF
-ylqM2tIrfKjuvqblCqoOpd8FUrdVxyJdMmqXl2MT28nbeTZ7hTpKxVKJ+STnnXepgv9VHKVxaSvR
-AiTysybUa9oEVeXBCsdtMDeQKuSeFDNeFhdVxVu1yzSJkvGdJo+hB9TGsnhQ2wwMC3wLjEHXuend
-jIj3o02yMszYF9rNt85mndT9Xv+9lz4pded+p2JYryU0pUHHPbwNUMoDAw8IWh+Vc3hiv69yFGkO
-peUDDniOJihC8AcLYiAQZzlG+qkDzAQ4embvIIO1jEpWjpEA/I5cgt6IoMPiaG59je883WX0XaxR
-7ySArqpWl2/5rX3aYT+YdzylkbYcjCbaZaIJbcHiVOO5ykxMgI93e2CaHt+28kgeDrpOVG2Y4OGi
-GqJ3UM/EY5LsRxmd6+ZrzsECAwEAAaOBrDCBqTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUw
-AwEB/zAdBgNVHQ4EFgQUWyV7lqRlUX64OfPAeGZe6Drn8O4wHwYDVR0jBBgwFoAUWyV7lqRlUX64
-OfPAeGZe6Drn8O4wRgYDVR0gBD8wPTA7BglghXQBWQECAQEwLjAsBggrBgEFBQcCARYgaHR0cDov
-L3JlcG9zaXRvcnkuc3dpc3NzaWduLmNvbS8wDQYJKoZIhvcNAQEFBQADggIBACe645R88a7A3hfm
-5djV9VSwg/S7zV4Fe0+fdWavPOhWfvxyeDgD2StiGwC5+OlgzczOUYrHUDFu4Up+GC9pWbY9ZIEr
-44OE5iKHjn3g7gKZYbge9LgriBIWhMIxkziWMaa5O1M/wySTVltpkuzFwbs4AOPsF6m43Md8AYOf
-Mke6UiI0HTJ6CVanfCU2qT1L2sCCbwq7EsiHSycR+R4tx5M/nttfJmtS2S6K8RTGRI0Vqbe/vd6m
-Gu6uLftIdxf+u+yvGPUqUfA5hJeVbG4bwyvEdGB5JbAKJ9/fXtI5z0V9QkvfsywexcZdylU6oJxp
-mo/a77KwPJ+HbBIrZXAVUjEaJM9vMSNQH4xPjyPDdEFjHFWoFN0+4FFQz/EbMFYOkrCChdiDyyJk
-vC24JdVUorgG6q2SpCSgwYa1ShNqR88uC1aVVMvOmttqtKay20EIhid392qgQmwLOM7XdVAyksLf
-KzAiSNDVQTglXaTpXZ/GlHXQRf0wl0OPkKsKx4ZzYEppLd6leNcG2mqeSz53OiATIgHQv2ieY2Br
-NU0LbbqhPcCT4H8js1WtciVORvnSFu+wZMEBnunKoGqYDs/YYPIvSbjkQuE4NRb0yG5P94FW6Lqj
-viOvrv1vA+ACOzB2+httQc8Bsem4yWb02ybzOqR08kkkW8mw0FfB+j564ZfJ
------END CERTIFICATE-----
-
-SwissSign Silver CA - G2
-========================
------BEGIN CERTIFICATE-----
-MIIFvTCCA6WgAwIBAgIITxvUL1S7L0swDQYJKoZIhvcNAQEFBQAwRzELMAkGA1UEBhMCQ0gxFTAT
-BgNVBAoTDFN3aXNzU2lnbiBBRzEhMB8GA1UEAxMYU3dpc3NTaWduIFNpbHZlciBDQSAtIEcyMB4X
-DTA2MTAyNTA4MzI0NloXDTM2MTAyNTA4MzI0NlowRzELMAkGA1UEBhMCQ0gxFTATBgNVBAoTDFN3
-aXNzU2lnbiBBRzEhMB8GA1UEAxMYU3dpc3NTaWduIFNpbHZlciBDQSAtIEcyMIICIjANBgkqhkiG
-9w0BAQEFAAOCAg8AMIICCgKCAgEAxPGHf9N4Mfc4yfjDmUO8x/e8N+dOcbpLj6VzHVxumK4DV644
-N0MvFz0fyM5oEMF4rhkDKxD6LHmD9ui5aLlV8gREpzn5/ASLHvGiTSf5YXu6t+WiE7brYT7QbNHm
-+/pe7R20nqA1W6GSy/BJkv6FCgU+5tkL4k+73JU3/JHpMjUi0R86TieFnbAVlDLaYQ1HTWBCrpJH
-6INaUFjpiou5XaHc3ZlKHzZnu0jkg7Y360g6rw9njxcH6ATK72oxh9TAtvmUcXtnZLi2kUpCe2Uu
-MGoM9ZDulebyzYLs2aFK7PayS+VFheZteJMELpyCbTapxDFkH4aDCyr0NQp4yVXPQbBH6TCfmb5h
-qAaEuSh6XzjZG6k4sIN/c8HDO0gqgg8hm7jMqDXDhBuDsz6+pJVpATqJAHgE2cn0mRmrVn5bi4Y5
-FZGkECwJMoBgs5PAKrYYC51+jUnyEEp/+dVGLxmSo5mnJqy7jDzmDrxHB9xzUfFwZC8I+bRHHTBs
-ROopN4WSaGa8gzj+ezku01DwH/teYLappvonQfGbGHLy9YR0SslnxFSuSGTfjNFusB3hB48IHpmc
-celM2KX3RxIfdNFRnobzwqIjQAtz20um53MGjMGg6cFZrEb65i/4z3GcRm25xBWNOHkDRUjvxF3X
-CO6HOSKGsg0PWEP3calILv3q1h8CAwEAAaOBrDCBqTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/
-BAUwAwEB/zAdBgNVHQ4EFgQUF6DNweRBtjpbO8tFnb0cwpj6hlgwHwYDVR0jBBgwFoAUF6DNweRB
-tjpbO8tFnb0cwpj6hlgwRgYDVR0gBD8wPTA7BglghXQBWQEDAQEwLjAsBggrBgEFBQcCARYgaHR0
-cDovL3JlcG9zaXRvcnkuc3dpc3NzaWduLmNvbS8wDQYJKoZIhvcNAQEFBQADggIBAHPGgeAn0i0P
-4JUw4ppBf1AsX19iYamGamkYDHRJ1l2E6kFSGG9YrVBWIGrGvShpWJHckRE1qTodvBqlYJ7YH39F
-kWnZfrt4csEGDyrOj4VwYaygzQu4OSlWhDJOhrs9xCrZ1x9y7v5RoSJBsXECYxqCsGKrXlcSH9/L
-3XWgwF15kIwb4FDm3jH+mHtwX6WQ2K34ArZv02DdQEsixT2tOnqfGhpHkXkzuoLcMmkDlm4fS/Bx
-/uNncqCxv1yL5PqZIseEuRuNI5c/7SXgz2W79WEE790eslpBIlqhn10s6FvJbakMDHiqYMZWjwFa
-DGi8aRl5xB9+lwW/xekkUV7U1UtT7dkjWjYDZaPBA61BMPNGG4WQr2W11bHkFlt4dR2Xem1ZqSqP
-e97Dh4kQmUlzeMg9vVE1dCrV8X5pGyq7O70luJpaPXJhkGaH7gzWTdQRdAtq/gsD/KNVV4n+Ssuu
-WxcFyPKNIzFTONItaj+CuY0IavdeQXRuwxF+B6wpYJE/OMpXEA29MC/HpeZBoNquBYeaoKRlbEwJ
-DIm6uNO5wJOKMPqN5ZprFQFOZ6raYlY+hAhm0sQ2fac+EPyI4NSA5QC9qvNOBqN6avlicuMJT+ub
-DgEj8Z+7fNzcbBGXJbLytGMU0gYqZ4yD9c7qB9iaah7s5Aq7KkzrCWA5zspi2C5u
------END CERTIFICATE-----
-
-GeoTrust Primary Certification Authority
-========================================
------BEGIN CERTIFICATE-----
-MIIDfDCCAmSgAwIBAgIQGKy1av1pthU6Y2yv2vrEoTANBgkqhkiG9w0BAQUFADBYMQswCQYDVQQG
-EwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjExMC8GA1UEAxMoR2VvVHJ1c3QgUHJpbWFyeSBD
-ZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNjExMjcwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMFgx
-CzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTEwLwYDVQQDEyhHZW9UcnVzdCBQ
-cmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
-CgKCAQEAvrgVe//UfH1nrYNke8hCUy3f9oQIIGHWAVlqnEQRr+92/ZV+zmEwu3qDXwK9AWbK7hWN
-b6EwnL2hhZ6UOvNWiAAxz9juapYC2e0DjPt1befquFUWBRaa9OBesYjAZIVcFU2Ix7e64HXprQU9
-nceJSOC7KMgD4TCTZF5SwFlwIjVXiIrxlQqD17wxcwE07e9GceBrAqg1cmuXm2bgyxx5X9gaBGge
-RwLmnWDiNpcB3841kt++Z8dtd1k7j53WkBWUvEI0EME5+bEnPn7WinXFsq+W06Lem+SYvn3h6YGt
-tm/81w7a4DSwDRp35+MImO9Y+pyEtzavwt+s0vQQBnBxNQIDAQABo0IwQDAPBgNVHRMBAf8EBTAD
-AQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQULNVQQZcVi/CPNmFbSvtr2ZnJM5IwDQYJKoZI
-hvcNAQEFBQADggEBAFpwfyzdtzRP9YZRqSa+S7iq8XEN3GHHoOo0Hnp3DwQ16CePbJC/kRYkRj5K
-Ts4rFtULUh38H2eiAkUxT87z+gOneZ1TatnaYzr4gNfTmeGl4b7UVXGYNTq+k+qurUKykG/g/CFN
-NWMziUnWm07Kx+dOCQD32sfvmWKZd7aVIl6KoKv0uHiYyjgZmclynnjNS6yvGaBzEi38wkG6gZHa
-Floxt/m0cYASSJlyc1pZU8FjUjPtp8nSOQJw+uCxQmYpqptR7TBUIhRf2asdweSU8Pj1K/fqynhG
-1riR/aYNKxoUAT6A8EKglQdebc3MS6RFjasS6LPeWuWgfOgPIh1a6Vk=
------END CERTIFICATE-----
-
-thawte Primary Root CA
-======================
------BEGIN CERTIFICATE-----
-MIIEIDCCAwigAwIBAgIQNE7VVyDV7exJ9C/ON9srbTANBgkqhkiG9w0BAQUFADCBqTELMAkGA1UE
-BhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2
-aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMvKGMpIDIwMDYgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhv
-cml6ZWQgdXNlIG9ubHkxHzAdBgNVBAMTFnRoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EwHhcNMDYxMTE3
-MDAwMDAwWhcNMzYwNzE2MjM1OTU5WjCBqTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwg
-SW5jLjEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMv
-KGMpIDIwMDYgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxHzAdBgNVBAMT
-FnRoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCs
-oPD7gFnUnMekz52hWXMJEEUMDSxuaPFsW0hoSVk3/AszGcJ3f8wQLZU0HObrTQmnHNK4yZc2AreJ
-1CRfBsDMRJSUjQJib+ta3RGNKJpchJAQeg29dGYvajig4tVUROsdB58Hum/u6f1OCyn1PoSgAfGc
-q/gcfomk6KHYcWUNo1F77rzSImANuVud37r8UVsLr5iy6S7pBOhih94ryNdOwUxkHt3Ph1i6Sk/K
-aAcdHJ1KxtUvkcx8cXIcxcBn6zL9yZJclNqFwJu/U30rCfSMnZEfl2pSy94JNqR32HuHUETVPm4p
-afs5SSYeCaWAe0At6+gnhcn+Yf1+5nyXHdWdAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYD
-VR0PAQH/BAQDAgEGMB0GA1UdDgQWBBR7W0XPr87Lev0xkhpqtvNG61dIUDANBgkqhkiG9w0BAQUF
-AAOCAQEAeRHAS7ORtvzw6WfUDW5FvlXok9LOAz/t2iWwHVfLHjp2oEzsUHboZHIMpKnxuIvW1oeE
-uzLlQRHAd9mzYJ3rG9XRbkREqaYB7FViHXe4XI5ISXycO1cRrK1zN44veFyQaEfZYGDm/Ac9IiAX
-xPcW6cTYcvnIc3zfFi8VqT79aie2oetaupgf1eNNZAqdE8hhuvU5HIe6uL17In/2/qxAeeWsEG89
-jxt5dovEN7MhGITlNgDrYyCZuen+MwS7QcjBAvlEYyCegc5C09Y/LHbTY5xZ3Y+m4Q6gLkH3LpVH
-z7z9M/P2C2F+fpErgUfCJzDupxBdN49cOSvkBPB7jVaMaA==
------END CERTIFICATE-----
-
-VeriSign Class 3 Public Primary Certification Authority - G5
-============================================================
------BEGIN CERTIFICATE-----
-MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCByjELMAkGA1UE
-BhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBO
-ZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVk
-IHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRp
-ZmljYXRpb24gQXV0aG9yaXR5IC0gRzUwHhcNMDYxMTA4MDAwMDAwWhcNMzYwNzE2MjM1OTU5WjCB
-yjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2ln
-biBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2lnbiwgSW5jLiAtIEZvciBh
-dXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmlt
-YXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
-ggEKAoIBAQCvJAgIKXo1nmAMqudLO07cfLw8RRy7K+D+KQL5VwijZIUVJ/XxrcgxiV0i6CqqpkKz
-j/i5Vbext0uz/o9+B1fs70PbZmIVYc9gDaTY3vjgw2IIPVQT60nKWVSFJuUrjxuf6/WhkcIzSdhD
-Y2pSS9KP6HBRTdGJaXvHcPaz3BJ023tdS1bTlr8Vd6Gw9KIl8q8ckmcY5fQGBO+QueQA5N06tRn/
-Arr0PO7gi+s3i+z016zy9vA9r911kTMZHRxAy3QkGSGT2RT+rCpSx4/VBEnkjWNHiDxpg8v+R70r
-fk/Fla4OndTRQ8Bnc+MUCH7lP59zuDMKz10/NIeWiu5T6CUVAgMBAAGjgbIwga8wDwYDVR0TAQH/
-BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2Uv
-Z2lmMCEwHzAHBgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDovL2xvZ28udmVy
-aXNpZ24uY29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFH/TZafC3ey78DAJ80M5+gKvMzEzMA0GCSqG
-SIb3DQEBBQUAA4IBAQCTJEowX2LP2BqYLz3q3JktvXf2pXkiOOzEp6B4Eq1iDkVwZMXnl2YtmAl+
-X6/WzChl8gGqCBpH3vn5fJJaCGkgDdk+bW48DW7Y5gaRQBi5+MHt39tBquCWIMnNZBU4gcmU7qKE
-KQsTb47bDN0lAtukixlE0kF6BWlKWE9gyn6CagsCqiUXObXbf+eEZSqVir2G3l6BFoMtEMze/aiC
-Km0oHw0LxOXnGiYZ4fQRbxC1lfznQgUy286dUV4otp6F01vvpX1FQHKOtw5rDgb7MzVIcbidJ4vE
-ZV8NhnacRHr2lVz2XTIIM6RUthg/aFzyQkqFOFSDX9HoLPKsEdao7WNq
------END CERTIFICATE-----
-
-SecureTrust CA
-==============
------BEGIN CERTIFICATE-----
-MIIDuDCCAqCgAwIBAgIQDPCOXAgWpa1Cf/DrJxhZ0DANBgkqhkiG9w0BAQUFADBIMQswCQYDVQQG
-EwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24xFzAVBgNVBAMTDlNlY3VyZVRy
-dXN0IENBMB4XDTA2MTEwNzE5MzExOFoXDTI5MTIzMTE5NDA1NVowSDELMAkGA1UEBhMCVVMxIDAe
-BgNVBAoTF1NlY3VyZVRydXN0IENvcnBvcmF0aW9uMRcwFQYDVQQDEw5TZWN1cmVUcnVzdCBDQTCC
-ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKukgeWVzfX2FI7CT8rU4niVWJxB4Q2ZQCQX
-OZEzZum+4YOvYlyJ0fwkW2Gz4BERQRwdbvC4u/jep4G6pkjGnx29vo6pQT64lO0pGtSO0gMdA+9t
-DWccV9cGrcrI9f4Or2YlSASWC12juhbDCE/RRvgUXPLIXgGZbf2IzIaowW8xQmxSPmjL8xk037uH
-GFaAJsTQ3MBv396gwpEWoGQRS0S8Hvbn+mPeZqx2pHGj7DaUaHp3pLHnDi+BeuK1cobvomuL8A/b
-01k/unK8RCSc43Oz969XL0Imnal0ugBS8kvNU3xHCzaFDmapCJcWNFfBZveA4+1wVMeT4C4oFVmH
-ursCAwEAAaOBnTCBmjATBgkrBgEEAYI3FAIEBh4EAEMAQTALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/
-BAUwAwEB/zAdBgNVHQ4EFgQUQjK2FvoE/f5dS3rD/fdMQB1aQ68wNAYDVR0fBC0wKzApoCegJYYj
-aHR0cDovL2NybC5zZWN1cmV0cnVzdC5jb20vU1RDQS5jcmwwEAYJKwYBBAGCNxUBBAMCAQAwDQYJ
-KoZIhvcNAQEFBQADggEBADDtT0rhWDpSclu1pqNlGKa7UTt36Z3q059c4EVlew3KW+JwULKUBRSu
-SceNQQcSc5R+DCMh/bwQf2AQWnL1mA6s7Ll/3XpvXdMc9P+IBWlCqQVxyLesJugutIxq/3HcuLHf
-mbx8IVQr5Fiiu1cprp6poxkmD5kuCLDv/WnPmRoJjeOnnyvJNjR7JLN4TJUXpAYmHrZkUjZfYGfZ
-nMUFdAvnZyPSCPyI6a6Lf+Ew9Dd+/cYy2i2eRDAwbO4H3tI0/NL/QPZL9GZGBlSm8jIKYyYwa5vR
-3ItHuuG51WLQoqD0ZwV4KWMabwTW+MZMo5qxN7SN5ShLHZ4swrhovO0C7jE=
------END CERTIFICATE-----
-
-Secure Global CA
-================
------BEGIN CERTIFICATE-----
-MIIDvDCCAqSgAwIBAgIQB1YipOjUiolN9BPI8PjqpTANBgkqhkiG9w0BAQUFADBKMQswCQYDVQQG
-EwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24xGTAXBgNVBAMTEFNlY3VyZSBH
-bG9iYWwgQ0EwHhcNMDYxMTA3MTk0MjI4WhcNMjkxMjMxMTk1MjA2WjBKMQswCQYDVQQGEwJVUzEg
-MB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24xGTAXBgNVBAMTEFNlY3VyZSBHbG9iYWwg
-Q0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvNS7YrGxVaQZx5RNoJLNP2MwhR/jx
-YDiJiQPpvepeRlMJ3Fz1Wuj3RSoC6zFh1ykzTM7HfAo3fg+6MpjhHZevj8fcyTiW89sa/FHtaMbQ
-bqR8JNGuQsiWUGMu4P51/pinX0kuleM5M2SOHqRfkNJnPLLZ/kG5VacJjnIFHovdRIWCQtBJwB1g
-8NEXLJXr9qXBkqPFwqcIYA1gBBCWeZ4WNOaptvolRTnIHmX5k/Wq8VLcmZg9pYYaDDUz+kulBAYV
-HDGA76oYa8J719rO+TMg1fW9ajMtgQT7sFzUnKPiXB3jqUJ1XnvUd+85VLrJChgbEplJL4hL/VBi
-0XPnj3pDAgMBAAGjgZ0wgZowEwYJKwYBBAGCNxQCBAYeBABDAEEwCwYDVR0PBAQDAgGGMA8GA1Ud
-EwEB/wQFMAMBAf8wHQYDVR0OBBYEFK9EBMJBfkiD2045AuzshHrmzsmkMDQGA1UdHwQtMCswKaAn
-oCWGI2h0dHA6Ly9jcmwuc2VjdXJldHJ1c3QuY29tL1NHQ0EuY3JsMBAGCSsGAQQBgjcVAQQDAgEA
-MA0GCSqGSIb3DQEBBQUAA4IBAQBjGghAfaReUw132HquHw0LURYD7xh8yOOvaliTFGCRsoTciE6+
-OYo68+aCiV0BN7OrJKQVDpI1WkpEXk5X+nXOH0jOZvQ8QCaSmGwb7iRGDBezUqXbpZGRzzfTb+cn
-CDpOGR86p1hcF895P4vkp9MmI50mD1hp/Ed+stCNi5O/KU9DaXR2Z0vPB4zmAve14bRDtUstFJ/5
-3CYNv6ZHdAbYiNE6KTCEztI5gGIbqMdXSbxqVVFnFUq+NQfk1XWYN3kwFNspnWzFacxHVaIw98xc
-f8LDmBxrThaA63p4ZUWiABqvDA1VZDRIuJK58bRQKfJPIx/abKwfROHdI3hRW8cW
------END CERTIFICATE-----
-
-COMODO Certification Authority
-==============================
------BEGIN CERTIFICATE-----
-MIIEHTCCAwWgAwIBAgIQToEtioJl4AsC7j41AkblPTANBgkqhkiG9w0BAQUFADCBgTELMAkGA1UE
-BhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgG
-A1UEChMRQ09NT0RPIENBIExpbWl0ZWQxJzAlBgNVBAMTHkNPTU9ETyBDZXJ0aWZpY2F0aW9uIEF1
-dGhvcml0eTAeFw0wNjEyMDEwMDAwMDBaFw0yOTEyMzEyMzU5NTlaMIGBMQswCQYDVQQGEwJHQjEb
-MBkGA1UECBMSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHEwdTYWxmb3JkMRowGAYDVQQKExFD
-T01PRE8gQ0EgTGltaXRlZDEnMCUGA1UEAxMeQ09NT0RPIENlcnRpZmljYXRpb24gQXV0aG9yaXR5
-MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0ECLi3LjkRv3UcEbVASY06m/weaKXTuH
-+7uIzg3jLz8GlvCiKVCZrts7oVewdFFxze1CkU1B/qnI2GqGd0S7WWaXUF601CxwRM/aN5VCaTww
-xHGzUvAhTaHYujl8HJ6jJJ3ygxaYqhZ8Q5sVW7euNJH+1GImGEaaP+vB+fGQV+useg2L23IwambV
-4EajcNxo2f8ESIl33rXp+2dtQem8Ob0y2WIC8bGoPW43nOIv4tOiJovGuFVDiOEjPqXSJDlqR6sA
-1KGzqSX+DT+nHbrTUcELpNqsOO9VUCQFZUaTNE8tja3G1CEZ0o7KBWFxB3NH5YoZEr0ETc5OnKVI
-rLsm9wIDAQABo4GOMIGLMB0GA1UdDgQWBBQLWOWLxkwVN6RAqTCpIb5HNlpW/zAOBgNVHQ8BAf8E
-BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zBJBgNVHR8EQjBAMD6gPKA6hjhodHRwOi8vY3JsLmNvbW9k
-b2NhLmNvbS9DT01PRE9DZXJ0aWZpY2F0aW9uQXV0aG9yaXR5LmNybDANBgkqhkiG9w0BAQUFAAOC
-AQEAPpiem/Yb6dc5t3iuHXIYSdOH5EOC6z/JqvWote9VfCFSZfnVDeFs9D6Mk3ORLgLETgdxb8CP
-OGEIqB6BCsAvIC9Bi5HcSEW88cbeunZrM8gALTFGTO3nnc+IlP8zwFboJIYmuNg4ON8qa90SzMc/
-RxdMosIGlgnW2/4/PEZB31jiVg88O8EckzXZOFKs7sjsLjBOlDW0JB9LeGna8gI4zJVSk/BwJVmc
-IGfE7vmLV2H0knZ9P4SNVbfo5azV8fUZVqZa+5Acr5Pr5RzUZ5ddBA6+C4OmF4O5MBKgxTMVBbkN
-+8cFduPYSo38NBejxiEovjBFMR7HeL5YYTisO+IBZQ==
------END CERTIFICATE-----
-
-Network Solutions Certificate Authority
-=======================================
------BEGIN CERTIFICATE-----
-MIID5jCCAs6gAwIBAgIQV8szb8JcFuZHFhfjkDFo4DANBgkqhkiG9w0BAQUFADBiMQswCQYDVQQG
-EwJVUzEhMB8GA1UEChMYTmV0d29yayBTb2x1dGlvbnMgTC5MLkMuMTAwLgYDVQQDEydOZXR3b3Jr
-IFNvbHV0aW9ucyBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwHhcNMDYxMjAxMDAwMDAwWhcNMjkxMjMx
-MjM1OTU5WjBiMQswCQYDVQQGEwJVUzEhMB8GA1UEChMYTmV0d29yayBTb2x1dGlvbnMgTC5MLkMu
-MTAwLgYDVQQDEydOZXR3b3JrIFNvbHV0aW9ucyBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwggEiMA0G
-CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDkvH6SMG3G2I4rC7xGzuAnlt7e+foS0zwzc7MEL7xx
-jOWftiJgPl9dzgn/ggwbmlFQGiaJ3dVhXRncEg8tCqJDXRfQNJIg6nPPOCwGJgl6cvf6UDL4wpPT
-aaIjzkGxzOTVHzbRijr4jGPiFFlp7Q3Tf2vouAPlT2rlmGNpSAW+Lv8ztumXWWn4Zxmuk2GWRBXT
-crA/vGp97Eh/jcOrqnErU2lBUzS1sLnFBgrEsEX1QV1uiUV7PTsmjHTC5dLRfbIR1PtYMiKagMnc
-/Qzpf14Dl847ABSHJ3A4qY5usyd2mFHgBeMhqxrVhSI8KbWaFsWAqPS7azCPL0YCorEMIuDTAgMB
-AAGjgZcwgZQwHQYDVR0OBBYEFCEwyfsA106Y2oeqKtCnLrFAMadMMA4GA1UdDwEB/wQEAwIBBjAP
-BgNVHRMBAf8EBTADAQH/MFIGA1UdHwRLMEkwR6BFoEOGQWh0dHA6Ly9jcmwubmV0c29sc3NsLmNv
-bS9OZXR3b3JrU29sdXRpb25zQ2VydGlmaWNhdGVBdXRob3JpdHkuY3JsMA0GCSqGSIb3DQEBBQUA
-A4IBAQC7rkvnt1frf6ott3NHhWrB5KUd5Oc86fRZZXe1eltajSU24HqXLjjAV2CDmAaDn7l2em5Q
-4LqILPxFzBiwmZVRDuwduIj/h1AcgsLj4DKAv6ALR8jDMe+ZZzKATxcheQxpXN5eNK4CtSbqUN9/
-GGUsyfJj4akH/nxxH2szJGoeBfcFaMBqEssuXmHLrijTfsK0ZpEmXzwuJF/LWA/rKOyvEZbz3Htv
-wKeI8lN3s2Berq4o2jUsbzRF0ybh3uxbTydrFny9RAQYgrOJeRcQcT16ohZO9QHNpGxlaKFJdlxD
-ydi8NmdspZS11My5vWo1ViHe2MPr+8ukYEywVaCge1ey
------END CERTIFICATE-----
-
-WellsSecure Public Root Certificate Authority
-=============================================
------BEGIN CERTIFICATE-----
-MIIEvTCCA6WgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBhTELMAkGA1UEBhMCVVMxIDAeBgNVBAoM
-F1dlbGxzIEZhcmdvIFdlbGxzU2VjdXJlMRwwGgYDVQQLDBNXZWxscyBGYXJnbyBCYW5rIE5BMTYw
-NAYDVQQDDC1XZWxsc1NlY3VyZSBQdWJsaWMgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwHhcN
-MDcxMjEzMTcwNzU0WhcNMjIxMjE0MDAwNzU0WjCBhTELMAkGA1UEBhMCVVMxIDAeBgNVBAoMF1dl
-bGxzIEZhcmdvIFdlbGxzU2VjdXJlMRwwGgYDVQQLDBNXZWxscyBGYXJnbyBCYW5rIE5BMTYwNAYD
-VQQDDC1XZWxsc1NlY3VyZSBQdWJsaWMgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwggEiMA0G
-CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDub7S9eeKPCCGeOARBJe+rWxxTkqxtnt3CxC5FlAM1
-iGd0V+PfjLindo8796jE2yljDpFoNoqXjopxaAkH5OjUDk/41itMpBb570OYj7OeUt9tkTmPOL13
-i0Nj67eT/DBMHAGTthP796EfvyXhdDcsHqRePGj4S78NuR4uNuip5Kf4D8uCdXw1LSLWwr8L87T8
-bJVhHlfXBIEyg1J55oNjz7fLY4sR4r1e6/aN7ZVyKLSsEmLpSjPmgzKuBXWVvYSV2ypcm44uDLiB
-K0HmOFafSZtsdvqKXfcBeYF8wYNABf5x/Qw/zE5gCQ5lRxAvAcAFP4/4s0HvWkJ+We/SlwxlAgMB
-AAGjggE0MIIBMDAPBgNVHRMBAf8EBTADAQH/MDkGA1UdHwQyMDAwLqAsoCqGKGh0dHA6Ly9jcmwu
-cGtpLndlbGxzZmFyZ28uY29tL3dzcHJjYS5jcmwwDgYDVR0PAQH/BAQDAgHGMB0GA1UdDgQWBBQm
-lRkQ2eihl5H/3BnZtQQ+0nMKajCBsgYDVR0jBIGqMIGngBQmlRkQ2eihl5H/3BnZtQQ+0nMKaqGB
-i6SBiDCBhTELMAkGA1UEBhMCVVMxIDAeBgNVBAoMF1dlbGxzIEZhcmdvIFdlbGxzU2VjdXJlMRww
-GgYDVQQLDBNXZWxscyBGYXJnbyBCYW5rIE5BMTYwNAYDVQQDDC1XZWxsc1NlY3VyZSBQdWJsaWMg
-Um9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHmCAQEwDQYJKoZIhvcNAQEFBQADggEBALkVsUSRzCPI
-K0134/iaeycNzXK7mQDKfGYZUMbVmO2rvwNa5U3lHshPcZeG1eMd/ZDJPHV3V3p9+N701NX3leZ0
-bh08rnyd2wIDBSxxSyU+B+NemvVmFymIGjifz6pBA4SXa5M4esowRBskRDPQ5NHcKDj0E0M1NSlj
-qHyita04pO2t/caaH/+Xc/77szWnk4bGdpEA5qxRFsQnMlzbc9qlk1eOPm01JghZ1edE13YgY+es
-E2fDbbFwRnzVlhE9iW9dqKHrjQrawx0zbKPqZxmamX9LPYNRKh3KL4YMon4QLSvUFpULB6ouFJJJ
-tylv2G0xffX8oRAHh84vWdw+WNs=
------END CERTIFICATE-----
-
-COMODO ECC Certification Authority
-==================================
------BEGIN CERTIFICATE-----
-MIICiTCCAg+gAwIBAgIQH0evqmIAcFBUTAGem2OZKjAKBggqhkjOPQQDAzCBhTELMAkGA1UEBhMC
-R0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UE
-ChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlvbiBB
-dXRob3JpdHkwHhcNMDgwMzA2MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0Ix
-GzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMR
-Q09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlvbiBBdXRo
-b3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQDR3svdcmCFYX7deSRFtSrYpn1PlILBs5BAH+X
-4QokPB0BBO490o0JlwzgdeT6+3eKKvUDYEs2ixYjFq0JcfRK9ChQtP6IHG4/bC8vCVlbpVsLM5ni
-wz2J+Wos77LTBumjQjBAMB0GA1UdDgQWBBR1cacZSBm8nZ3qQUfflMRId5nTeTAOBgNVHQ8BAf8E
-BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjEA7wNbeqy3eApyt4jf/7VG
-FAkK+qDmfQjGGoe9GKhzvSbKYAydzpmfz1wPMOG+FDHqAjAU9JM8SaczepBGR7NjfRObTrdvGDeA
-U/7dIOA1mjbRxwG55tzd8/8dLDoWV9mSOdY=
------END CERTIFICATE-----
-
-IGC/A
-=====
------BEGIN CERTIFICATE-----
-MIIEAjCCAuqgAwIBAgIFORFFEJQwDQYJKoZIhvcNAQEFBQAwgYUxCzAJBgNVBAYTAkZSMQ8wDQYD
-VQQIEwZGcmFuY2UxDjAMBgNVBAcTBVBhcmlzMRAwDgYDVQQKEwdQTS9TR0ROMQ4wDAYDVQQLEwVE
-Q1NTSTEOMAwGA1UEAxMFSUdDL0ExIzAhBgkqhkiG9w0BCQEWFGlnY2FAc2dkbi5wbS5nb3V2LmZy
-MB4XDTAyMTIxMzE0MjkyM1oXDTIwMTAxNzE0MjkyMlowgYUxCzAJBgNVBAYTAkZSMQ8wDQYDVQQI
-EwZGcmFuY2UxDjAMBgNVBAcTBVBhcmlzMRAwDgYDVQQKEwdQTS9TR0ROMQ4wDAYDVQQLEwVEQ1NT
-STEOMAwGA1UEAxMFSUdDL0ExIzAhBgkqhkiG9w0BCQEWFGlnY2FAc2dkbi5wbS5nb3V2LmZyMIIB
-IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsh/R0GLFMzvABIaIs9z4iPf930Pfeo2aSVz2
-TqrMHLmh6yeJ8kbpO0px1R2OLc/mratjUMdUC24SyZA2xtgv2pGqaMVy/hcKshd+ebUyiHDKcMCW
-So7kVc0dJ5S/znIq7Fz5cyD+vfcuiWe4u0dzEvfRNWk68gq5rv9GQkaiv6GFGvm/5P9JhfejcIYy
-HF2fYPepraX/z9E0+X1bF8bc1g4oa8Ld8fUzaJ1O/Id8NhLWo4DoQw1VYZTqZDdH6nfK0LJYBcNd
-frGoRpAxVs5wKpayMLh35nnAvSk7/ZR3TL0gzUEl4C7HG7vupARB0l2tEmqKm0f7yd1GQOGdPDPQ
-tQIDAQABo3cwdTAPBgNVHRMBAf8EBTADAQH/MAsGA1UdDwQEAwIBRjAVBgNVHSAEDjAMMAoGCCqB
-egF5AQEBMB0GA1UdDgQWBBSjBS8YYFDCiQrdKyFP/45OqDAxNjAfBgNVHSMEGDAWgBSjBS8YYFDC
-iQrdKyFP/45OqDAxNjANBgkqhkiG9w0BAQUFAAOCAQEABdwm2Pp3FURo/C9mOnTgXeQp/wYHE4RK
-q89toB9RlPhJy3Q2FLwV3duJL92PoF189RLrn544pEfMs5bZvpwlqwN+Mw+VgQ39FuCIvjfwbF3Q
-MZsyK10XZZOYYLxuj7GoPB7ZHPOpJkL5ZB3C55L29B5aqhlSXa/oovdgoPaN8In1buAKBQGVyYsg
-Crpa/JosPL3Dt8ldeCUFP1YUmwza+zpI/pdpXsoQhvdOlgQITeywvl3cO45Pwf2aNjSaTFR+FwNI
-lQgRHAdvhQh+XU3Endv7rs6y0bO4g2wdsrN58dhwmX7wEwLOXt1R0982gaEbeC9xs/FZTEYYKKuF
-0mBWWg==
------END CERTIFICATE-----
-
-Security Communication EV RootCA1
-=================================
------BEGIN CERTIFICATE-----
-MIIDfTCCAmWgAwIBAgIBADANBgkqhkiG9w0BAQUFADBgMQswCQYDVQQGEwJKUDElMCMGA1UEChMc
-U0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEqMCgGA1UECxMhU2VjdXJpdHkgQ29tbXVuaWNh
-dGlvbiBFViBSb290Q0ExMB4XDTA3MDYwNjAyMTIzMloXDTM3MDYwNjAyMTIzMlowYDELMAkGA1UE
-BhMCSlAxJTAjBgNVBAoTHFNFQ09NIFRydXN0IFN5c3RlbXMgQ08uLExURC4xKjAoBgNVBAsTIVNl
-Y3VyaXR5IENvbW11bmljYXRpb24gRVYgUm9vdENBMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
-AQoCggEBALx/7FebJOD+nLpCeamIivqA4PUHKUPqjgo0No0c+qe1OXj/l3X3L+SqawSERMqm4miO
-/VVQYg+kcQ7OBzgtQoVQrTyWb4vVog7P3kmJPdZkLjjlHmy1V4qe70gOzXppFodEtZDkBp2uoQSX
-WHnvIEqCa4wiv+wfD+mEce3xDuS4GBPMVjZd0ZoeUWs5bmB2iDQL87PRsJ3KYeJkHcFGB7hj3R4z
-ZbOOCVVSPbW9/wfrrWFVGCypaZhKqkDFMxRldAD5kd6vA0jFQFTcD4SQaCDFkpbcLuUCRarAX1T4
-bepJz11sS6/vmsJWXMY1VkJqMF/Cq/biPT+zyRGPMUzXn0kCAwEAAaNCMEAwHQYDVR0OBBYEFDVK
-9U2vP9eCOKyrcWUXdYydVZPmMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MA0GCSqG
-SIb3DQEBBQUAA4IBAQCoh+ns+EBnXcPBZsdAS5f8hxOQWsTvoMpfi7ent/HWtWS3irO4G8za+6xm
-iEHO6Pzk2x6Ipu0nUBsCMCRGef4Eh3CXQHPRwMFXGZpppSeZq51ihPZRwSzJIxXYKLerJRO1RuGG
-Av8mjMSIkh1W/hln8lXkgKNrnKt34VFxDSDbEJrbvXZ5B3eZKK2aXtqxT0QsNY6llsf9g/BYxnnW
-mHyojf6GPgcWkuF75x3sM3Z+Qi5KhfmRiWiEA4Glm5q+4zfFVKtWOxgtQaQM+ELbmaDgcm+7XeEW
-T1MKZPlO9L9OVL14bIjqv5wTJMJwaaJ/D8g8rQjJsJhAoyrniIPtd490
------END CERTIFICATE-----
-
-OISTE WISeKey Global Root GA CA
-===============================
------BEGIN CERTIFICATE-----
-MIID8TCCAtmgAwIBAgIQQT1yx/RrH4FDffHSKFTfmjANBgkqhkiG9w0BAQUFADCBijELMAkGA1UE
-BhMCQ0gxEDAOBgNVBAoTB1dJU2VLZXkxGzAZBgNVBAsTEkNvcHlyaWdodCAoYykgMjAwNTEiMCAG
-A1UECxMZT0lTVEUgRm91bmRhdGlvbiBFbmRvcnNlZDEoMCYGA1UEAxMfT0lTVEUgV0lTZUtleSBH
-bG9iYWwgUm9vdCBHQSBDQTAeFw0wNTEyMTExNjAzNDRaFw0zNzEyMTExNjA5NTFaMIGKMQswCQYD
-VQQGEwJDSDEQMA4GA1UEChMHV0lTZUtleTEbMBkGA1UECxMSQ29weXJpZ2h0IChjKSAyMDA1MSIw
-IAYDVQQLExlPSVNURSBGb3VuZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBXSVNlS2V5
-IEdsb2JhbCBSb290IEdBIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAy0+zAJs9
-Nt350UlqaxBJH+zYK7LG+DKBKUOVTJoZIyEVRd7jyBxRVVuuk+g3/ytr6dTqvirdqFEr12bDYVxg
-Asj1znJ7O7jyTmUIms2kahnBAbtzptf2w93NvKSLtZlhuAGio9RN1AU9ka34tAhxZK9w8RxrfvbD
-d50kc3vkDIzh2TbhmYsFmQvtRTEJysIA2/dyoJaqlYfQjse2YXMNdmaM3Bu0Y6Kff5MTMPGhJ9vZ
-/yxViJGg4E8HsChWjBgbl0SOid3gF27nKu+POQoxhILYQBRJLnpB5Kf+42TMwVlxSywhp1t94B3R
-LoGbw9ho972WG6xwsRYUC9tguSYBBQIDAQABo1EwTzALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/BAUw
-AwEB/zAdBgNVHQ4EFgQUswN+rja8sHnR3JQmthG+IbJphpQwEAYJKwYBBAGCNxUBBAMCAQAwDQYJ
-KoZIhvcNAQEFBQADggEBAEuh/wuHbrP5wUOxSPMowB0uyQlB+pQAHKSkq0lPjz0e701vvbyk9vIm
-MMkQyh2I+3QZH4VFvbBsUfk2ftv1TDI6QU9bR8/oCy22xBmddMVHxjtqD6wU2zz0c5ypBd8A3HR4
-+vg1YFkCExh8vPtNsCBtQ7tgMHpnM1zFmdH4LTlSc/uMqpclXHLZCB6rTjzjgTGfA6b7wP4piFXa
-hNVQA7bihKOmNqoROgHhGEvWRGizPflTdISzRpFGlgC3gCy24eMQ4tui5yiPAZZiFj4A4xylNoEY
-okxSdsARo27mHbrjWr42U8U+dY+GaSlYU7Wcu2+fXMUY7N0v4ZjJ/L7fCg0=
------END CERTIFICATE-----
-
-Microsec e-Szigno Root CA
-=========================
------BEGIN CERTIFICATE-----
-MIIHqDCCBpCgAwIBAgIRAMy4579OKRr9otxmpRwsDxEwDQYJKoZIhvcNAQEFBQAwcjELMAkGA1UE
-BhMCSFUxETAPBgNVBAcTCEJ1ZGFwZXN0MRYwFAYDVQQKEw1NaWNyb3NlYyBMdGQuMRQwEgYDVQQL
-EwtlLVN6aWdubyBDQTEiMCAGA1UEAxMZTWljcm9zZWMgZS1Temlnbm8gUm9vdCBDQTAeFw0wNTA0
-MDYxMjI4NDRaFw0xNzA0MDYxMjI4NDRaMHIxCzAJBgNVBAYTAkhVMREwDwYDVQQHEwhCdWRhcGVz
-dDEWMBQGA1UEChMNTWljcm9zZWMgTHRkLjEUMBIGA1UECxMLZS1Temlnbm8gQ0ExIjAgBgNVBAMT
-GU1pY3Jvc2VjIGUtU3ppZ25vIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB
-AQDtyADVgXvNOABHzNuEwSFpLHSQDCHZU4ftPkNEU6+r+ICbPHiN1I2uuO/TEdyB5s87lozWbxXG
-d36hL+BfkrYn13aaHUM86tnsL+4582pnS4uCzyL4ZVX+LMsvfUh6PXX5qqAnu3jCBspRwn5mS6/N
-oqdNAoI/gqyFxuEPkEeZlApxcpMqyabAvjxWTHOSJ/FrtfX9/DAFYJLG65Z+AZHCabEeHXtTRbjc
-QR/Ji3HWVBTji1R4P770Yjtb9aPs1ZJ04nQw7wHb4dSrmZsqa/i9phyGI0Jf7Enemotb9HI6QMVJ
-PqW+jqpx62z69Rrkav17fVVA71hu5tnVvCSrwe+3AgMBAAGjggQ3MIIEMzBnBggrBgEFBQcBAQRb
-MFkwKAYIKwYBBQUHMAGGHGh0dHBzOi8vcmNhLmUtc3ppZ25vLmh1L29jc3AwLQYIKwYBBQUHMAKG
-IWh0dHA6Ly93d3cuZS1zemlnbm8uaHUvUm9vdENBLmNydDAPBgNVHRMBAf8EBTADAQH/MIIBcwYD
-VR0gBIIBajCCAWYwggFiBgwrBgEEAYGoGAIBAQEwggFQMCgGCCsGAQUFBwIBFhxodHRwOi8vd3d3
-LmUtc3ppZ25vLmh1L1NaU1ovMIIBIgYIKwYBBQUHAgIwggEUHoIBEABBACAAdABhAG4A+gBzAO0A
-dAB2AOEAbgB5ACAA6QByAHQAZQBsAG0AZQB6AOkAcwDpAGgAZQB6ACAA6QBzACAAZQBsAGYAbwBn
-AGEAZADhAHMA4QBoAG8AegAgAGEAIABTAHoAbwBsAGcA4QBsAHQAYQB0APMAIABTAHoAbwBsAGcA
-4QBsAHQAYQB0AOEAcwBpACAAUwB6AGEAYgDhAGwAeQB6AGEAdABhACAAcwB6AGUAcgBpAG4AdAAg
-AGsAZQBsAGwAIABlAGwAagDhAHIAbgBpADoAIABoAHQAdABwADoALwAvAHcAdwB3AC4AZQAtAHMA
-egBpAGcAbgBvAC4AaAB1AC8AUwBaAFMAWgAvMIHIBgNVHR8EgcAwgb0wgbqggbeggbSGIWh0dHA6
-Ly93d3cuZS1zemlnbm8uaHUvUm9vdENBLmNybIaBjmxkYXA6Ly9sZGFwLmUtc3ppZ25vLmh1L0NO
-PU1pY3Jvc2VjJTIwZS1Temlnbm8lMjBSb290JTIwQ0EsT1U9ZS1Temlnbm8lMjBDQSxPPU1pY3Jv
-c2VjJTIwTHRkLixMPUJ1ZGFwZXN0LEM9SFU/Y2VydGlmaWNhdGVSZXZvY2F0aW9uTGlzdDtiaW5h
-cnkwDgYDVR0PAQH/BAQDAgEGMIGWBgNVHREEgY4wgYuBEGluZm9AZS1zemlnbm8uaHWkdzB1MSMw
-IQYDVQQDDBpNaWNyb3NlYyBlLVN6aWduw7MgUm9vdCBDQTEWMBQGA1UECwwNZS1TemlnbsOzIEhT
-WjEWMBQGA1UEChMNTWljcm9zZWMgS2Z0LjERMA8GA1UEBxMIQnVkYXBlc3QxCzAJBgNVBAYTAkhV
-MIGsBgNVHSMEgaQwgaGAFMegSXUWYYTbMUuE0vE3QJDvTtz3oXakdDByMQswCQYDVQQGEwJIVTER
-MA8GA1UEBxMIQnVkYXBlc3QxFjAUBgNVBAoTDU1pY3Jvc2VjIEx0ZC4xFDASBgNVBAsTC2UtU3pp
-Z25vIENBMSIwIAYDVQQDExlNaWNyb3NlYyBlLVN6aWdubyBSb290IENBghEAzLjnv04pGv2i3Gal
-HCwPETAdBgNVHQ4EFgQUx6BJdRZhhNsxS4TS8TdAkO9O3PcwDQYJKoZIhvcNAQEFBQADggEBANMT
-nGZjWS7KXHAM/IO8VbH0jgdsZifOwTsgqRy7RlRw7lrMoHfqaEQn6/Ip3Xep1fvj1KcExJW4C+FE
-aGAHQzAxQmHl7tnlJNUb3+FKG6qfx1/4ehHqE5MAyopYse7tDk2016g2JnzgOsHVV4Lxdbb9iV/a
-86g4nzUGCM4ilb7N1fy+W955a9x6qWVmvrElWl/tftOsRm1M9DKHtCAE4Gx4sHfRhUZLphK3dehK
-yVZs15KrnfVJONJPU+NVkBHbmJbGSfI+9J8b4PeI3CVimUTYc78/MPMMNz7UwiiAc7EBt51alhQB
-S6kRnSlqLtBdgcDPsiBDxwPgN05dCtxZICU=
------END CERTIFICATE-----
-
-Certigna
-========
------BEGIN CERTIFICATE-----
-MIIDqDCCApCgAwIBAgIJAP7c4wEPyUj/MA0GCSqGSIb3DQEBBQUAMDQxCzAJBgNVBAYTAkZSMRIw
-EAYDVQQKDAlEaGlteW90aXMxETAPBgNVBAMMCENlcnRpZ25hMB4XDTA3MDYyOTE1MTMwNVoXDTI3
-MDYyOTE1MTMwNVowNDELMAkGA1UEBhMCRlIxEjAQBgNVBAoMCURoaW15b3RpczERMA8GA1UEAwwI
-Q2VydGlnbmEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDIaPHJ1tazNHUmgh7stL7q
-XOEm7RFHYeGifBZ4QCHkYJ5ayGPhxLGWkv8YbWkj4Sti993iNi+RB7lIzw7sebYs5zRLcAglozyH
-GxnygQcPOJAZ0xH+hrTy0V4eHpbNgGzOOzGTtvKg0KmVEn2lmsxryIRWijOp5yIVUxbwzBfsV1/p
-ogqYCd7jX5xv3EjjhQsVWqa6n6xI4wmy9/Qy3l40vhx4XUJbzg4ij02Q130yGLMLLGq/jj8UEYkg
-DncUtT2UCIf3JR7VsmAA7G8qKCVuKj4YYxclPz5EIBb2JsglrgVKtOdjLPOMFlN+XPsRGgjBRmKf
-Irjxwo1p3Po6WAbfAgMBAAGjgbwwgbkwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUGu3+QTmQ
-tCRZvgHyUtVF9lo53BEwZAYDVR0jBF0wW4AUGu3+QTmQtCRZvgHyUtVF9lo53BGhOKQ2MDQxCzAJ
-BgNVBAYTAkZSMRIwEAYDVQQKDAlEaGlteW90aXMxETAPBgNVBAMMCENlcnRpZ25hggkA/tzjAQ/J
-SP8wDgYDVR0PAQH/BAQDAgEGMBEGCWCGSAGG+EIBAQQEAwIABzANBgkqhkiG9w0BAQUFAAOCAQEA
-hQMeknH2Qq/ho2Ge6/PAD/Kl1NqV5ta+aDY9fm4fTIrv0Q8hbV6lUmPOEvjvKtpv6zf+EwLHyzs+
-ImvaYS5/1HI93TDhHkxAGYwP15zRgzB7mFncfca5DClMoTOi62c6ZYTTluLtdkVwj7Ur3vkj1klu
-PBS1xp81HlDQwY9qcEQCYsuuHWhBp6pX6FOqB9IG9tUUBguRA3UsbHK1YZWaDYu5Def131TN3ubY
-1gkIl2PlwS6wt0QmwCbAr1UwnjvVNioZBPRcHv/PLLf/0P2HQBHVESO7SMAhqaQoLf0V+LBOK/Qw
-WyH8EZE0vkHve52Xdf+XlcCWWC/qu0bXu+TZLg==
------END CERTIFICATE-----
-
-AC Ra\xC3\xADz Certic\xC3\xA1mara S.A.
-======================================
------BEGIN CERTIFICATE-----
-MIIGZjCCBE6gAwIBAgIPB35Sk3vgFeNX8GmMy+wMMA0GCSqGSIb3DQEBBQUAMHsxCzAJBgNVBAYT
-AkNPMUcwRQYDVQQKDD5Tb2NpZWRhZCBDYW1lcmFsIGRlIENlcnRpZmljYWNpw7NuIERpZ2l0YWwg
-LSBDZXJ0aWPDoW1hcmEgUy5BLjEjMCEGA1UEAwwaQUMgUmHDrXogQ2VydGljw6FtYXJhIFMuQS4w
-HhcNMDYxMTI3MjA0NjI5WhcNMzAwNDAyMjE0MjAyWjB7MQswCQYDVQQGEwJDTzFHMEUGA1UECgw+
-U29jaWVkYWQgQ2FtZXJhbCBkZSBDZXJ0aWZpY2FjacOzbiBEaWdpdGFsIC0gQ2VydGljw6FtYXJh
-IFMuQS4xIzAhBgNVBAMMGkFDIFJhw616IENlcnRpY8OhbWFyYSBTLkEuMIICIjANBgkqhkiG9w0B
-AQEFAAOCAg8AMIICCgKCAgEAq2uJo1PMSCMI+8PPUZYILrgIem08kBeGqentLhM0R7LQcNzJPNCN
-yu5LF6vQhbCnIwTLqKL85XXbQMpiiY9QngE9JlsYhBzLfDe3fezTf3MZsGqy2IiKLUV0qPezuMDU
-2s0iiXRNWhU5cxh0T7XrmafBHoi0wpOQY5fzp6cSsgkiBzPZkc0OnB8OIMfuuzONj8LSWKdf/WU3
-4ojC2I+GdV75LaeHM/J4Ny+LvB2GNzmxlPLYvEqcgxhaBvzz1NS6jBUJJfD5to0EfhcSM2tXSExP
-2yYe68yQ54v5aHxwD6Mq0Do43zeX4lvegGHTgNiRg0JaTASJaBE8rF9ogEHMYELODVoqDA+bMMCm
-8Ibbq0nXl21Ii/kDwFJnmxL3wvIumGVC2daa49AZMQyth9VXAnow6IYm+48jilSH5L887uvDdUhf
-HjlvgWJsxS3EF1QZtzeNnDeRyPYL1epjb4OsOMLzP96a++EjYfDIJss2yKHzMI+ko6Kh3VOz3vCa
-Mh+DkXkwwakfU5tTohVTP92dsxA7SH2JD/ztA/X7JWR1DhcZDY8AFmd5ekD8LVkH2ZD6mq093ICK
-5lw1omdMEWux+IBkAC1vImHFrEsm5VoQgpukg3s0956JkSCXjrdCx2bD0Omk1vUgjcTDlaxECp1b
-czwmPS9KvqfJpxAe+59QafMCAwEAAaOB5jCB4zAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQE
-AwIBBjAdBgNVHQ4EFgQU0QnQ6dfOeXRU+Tows/RtLAMDG2gwgaAGA1UdIASBmDCBlTCBkgYEVR0g
-ADCBiTArBggrBgEFBQcCARYfaHR0cDovL3d3dy5jZXJ0aWNhbWFyYS5jb20vZHBjLzBaBggrBgEF
-BQcCAjBOGkxMaW1pdGFjaW9uZXMgZGUgZ2FyYW507WFzIGRlIGVzdGUgY2VydGlmaWNhZG8gc2Ug
-cHVlZGVuIGVuY29udHJhciBlbiBsYSBEUEMuMA0GCSqGSIb3DQEBBQUAA4ICAQBclLW4RZFNjmEf
-AygPU3zmpFmps4p6xbD/CHwso3EcIRNnoZUSQDWDg4902zNc8El2CoFS3UnUmjIz75uny3XlesuX
-EpBcunvFm9+7OSPI/5jOCk0iAUgHforA1SBClETvv3eiiWdIG0ADBaGJ7M9i4z0ldma/Jre7Ir5v
-/zlXdLp6yQGVwZVR6Kss+LGGIOk/yzVb0hfpKv6DExdA7ohiZVvVO2Dpezy4ydV/NgIlqmjCMRW3
-MGXrfx1IebHPOeJCgBbT9ZMj/EyXyVo3bHwi2ErN0o42gzmRkBDI8ck1fj+404HGIGQatlDCIaR4
-3NAvO2STdPCWkPHv+wlaNECW8DYSwaN0jJN+Qd53i+yG2dIPPy3RzECiiWZIHiCznCNZc6lEc7wk
-eZBWN7PGKX6jD/EpOe9+XCgycDWs2rjIdWb8m0w5R44bb5tNAlQiM+9hup4phO9OSzNHdpdqy35f
-/RWmnkJDW2ZaiogN9xa5P1FlK2Zqi9E4UqLWRhH6/JocdJ6PlwsCT2TG9WjTSy3/pDceiz+/RL5h
-RqGEPQgnTIEgd4kI6mdAXmwIUV80WoyWaM3X94nCHNMyAK9Sy9NgWyo6R35rMDOhYil/SrnhLecU
-Iw4OGEfhefwVVdCx/CVxY3UzHCMrr1zZ7Ud3YA47Dx7SwNxkBYn8eNZcLCZDqQ==
------END CERTIFICATE-----
-
-TC TrustCenter Class 2 CA II
-============================
------BEGIN CERTIFICATE-----
-MIIEqjCCA5KgAwIBAgIOLmoAAQACH9dSISwRXDswDQYJKoZIhvcNAQEFBQAwdjELMAkGA1UEBhMC
-REUxHDAaBgNVBAoTE1RDIFRydXN0Q2VudGVyIEdtYkgxIjAgBgNVBAsTGVRDIFRydXN0Q2VudGVy
-IENsYXNzIDIgQ0ExJTAjBgNVBAMTHFRDIFRydXN0Q2VudGVyIENsYXNzIDIgQ0EgSUkwHhcNMDYw
-MTEyMTQzODQzWhcNMjUxMjMxMjI1OTU5WjB2MQswCQYDVQQGEwJERTEcMBoGA1UEChMTVEMgVHJ1
-c3RDZW50ZXIgR21iSDEiMCAGA1UECxMZVEMgVHJ1c3RDZW50ZXIgQ2xhc3MgMiBDQTElMCMGA1UE
-AxMcVEMgVHJ1c3RDZW50ZXIgQ2xhc3MgMiBDQSBJSTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
-AQoCggEBAKuAh5uO8MN8h9foJIIRszzdQ2Lu+MNF2ujhoF/RKrLqk2jftMjWQ+nEdVl//OEd+DFw
-IxuInie5e/060smp6RQvkL4DUsFJzfb95AhmC1eKokKguNV/aVyQMrKXDcpK3EY+AlWJU+MaWss2
-xgdW94zPEfRMuzBwBJWl9jmM/XOBCH2JXjIeIqkiRUuwZi4wzJ9l/fzLganx4Duvo4bRierERXlQ
-Xa7pIXSSTYtZgo+U4+lK8edJsBTj9WLL1XK9H7nSn6DNqPoByNkN39r8R52zyFTfSUrxIan+GE7u
-SNQZu+995OKdy1u2bv/jzVrndIIFuoAlOMvkaZ6vQaoahPUCAwEAAaOCATQwggEwMA8GA1UdEwEB
-/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTjq1RMgKHbVkO3kUrL84J6E1wIqzCB
-7QYDVR0fBIHlMIHiMIHfoIHcoIHZhjVodHRwOi8vd3d3LnRydXN0Y2VudGVyLmRlL2NybC92Mi90
-Y19jbGFzc18yX2NhX0lJLmNybIaBn2xkYXA6Ly93d3cudHJ1c3RjZW50ZXIuZGUvQ049VEMlMjBU
-cnVzdENlbnRlciUyMENsYXNzJTIwMiUyMENBJTIwSUksTz1UQyUyMFRydXN0Q2VudGVyJTIwR21i
-SCxPVT1yb290Y2VydHMsREM9dHJ1c3RjZW50ZXIsREM9ZGU/Y2VydGlmaWNhdGVSZXZvY2F0aW9u
-TGlzdD9iYXNlPzANBgkqhkiG9w0BAQUFAAOCAQEAjNfffu4bgBCzg/XbEeprS6iSGNn3Bzn1LL4G
-dXpoUxUc6krtXvwjshOg0wn/9vYua0Fxec3ibf2uWWuFHbhOIprtZjluS5TmVfwLG4t3wVMTZonZ
-KNaL80VKY7f9ewthXbhtvsPcW3nS7Yblok2+XnR8au0WOB9/WIFaGusyiC2y8zl3gK9etmF1Kdsj
-TYjKUCjLhdLTEKJZbtOTVAB6okaVhgWcqRmY5TFyDADiZ9lA4CQze28suVyrZZ0srHbqNZn1l7kP
-JOzHdiEoZa5X6AeIdUpWoNIFOqTmjZKILPPy4cHGYdtBxceb9w4aUUXCYWvcZCcXjFq32nQozZfk
-vQ==
------END CERTIFICATE-----
-
-TC TrustCenter Class 3 CA II
-============================
------BEGIN CERTIFICATE-----
-MIIEqjCCA5KgAwIBAgIOSkcAAQAC5aBd1j8AUb8wDQYJKoZIhvcNAQEFBQAwdjELMAkGA1UEBhMC
-REUxHDAaBgNVBAoTE1RDIFRydXN0Q2VudGVyIEdtYkgxIjAgBgNVBAsTGVRDIFRydXN0Q2VudGVy
-IENsYXNzIDMgQ0ExJTAjBgNVBAMTHFRDIFRydXN0Q2VudGVyIENsYXNzIDMgQ0EgSUkwHhcNMDYw
-MTEyMTQ0MTU3WhcNMjUxMjMxMjI1OTU5WjB2MQswCQYDVQQGEwJERTEcMBoGA1UEChMTVEMgVHJ1
-c3RDZW50ZXIgR21iSDEiMCAGA1UECxMZVEMgVHJ1c3RDZW50ZXIgQ2xhc3MgMyBDQTElMCMGA1UE
-AxMcVEMgVHJ1c3RDZW50ZXIgQ2xhc3MgMyBDQSBJSTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
-AQoCggEBALTgu1G7OVyLBMVMeRwjhjEQY0NVJz/GRcekPewJDRoeIMJWHt4bNwcwIi9v8Qbxq63W
-yKthoy9DxLCyLfzDlml7forkzMA5EpBCYMnMNWju2l+QVl/NHE1bWEnrDgFPZPosPIlY2C8u4rBo
-6SI7dYnWRBpl8huXJh0obazovVkdKyT21oQDZogkAHhg8fir/gKya/si+zXmFtGt9i4S5Po1auUZ
-uV3bOx4a+9P/FRQI2AlqukWdFHlgfa9Aigdzs5OW03Q0jTo3Kd5c7PXuLjHCINy+8U9/I1LZW+Jk
-2ZyqBwi1Rb3R0DHBq1SfqdLDYmAD8bs5SpJKPQq5ncWg/jcCAwEAAaOCATQwggEwMA8GA1UdEwEB
-/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTUovyfs8PYA9NXXAek0CSnwPIA1DCB
-7QYDVR0fBIHlMIHiMIHfoIHcoIHZhjVodHRwOi8vd3d3LnRydXN0Y2VudGVyLmRlL2NybC92Mi90
-Y19jbGFzc18zX2NhX0lJLmNybIaBn2xkYXA6Ly93d3cudHJ1c3RjZW50ZXIuZGUvQ049VEMlMjBU
-cnVzdENlbnRlciUyMENsYXNzJTIwMyUyMENBJTIwSUksTz1UQyUyMFRydXN0Q2VudGVyJTIwR21i
-SCxPVT1yb290Y2VydHMsREM9dHJ1c3RjZW50ZXIsREM9ZGU/Y2VydGlmaWNhdGVSZXZvY2F0aW9u
-TGlzdD9iYXNlPzANBgkqhkiG9w0BAQUFAAOCAQEANmDkcPcGIEPZIxpC8vijsrlNirTzwppVMXzE
-O2eatN9NDoqTSheLG43KieHPOh6sHfGcMrSOWXaiQYUlN6AT0PV8TtXqluJucsG7Kv5sbviRmEb8
-yRtXW+rIGjs/sFGYPAfaLFkB2otE6OF0/ado3VS6g0bsyEa1+K+XwDsJHI/OcpY9M1ZwvJbL2NV9
-IJqDnxrcOfHFcqMRA/07QlIp2+gB95tejNaNhk4Z+rwcvsUhpYeeeC422wlxo3I0+GzjBgnyXlal
-092Y+tTmBvTwtiBjS+opvaqCZh77gaqnN60TGOaSw4HBM7uIHqHn4rS9MWwOUT1v+5ZWgOI2F9Hc
-5A==
------END CERTIFICATE-----
-
-TC TrustCenter Universal CA I
-=============================
------BEGIN CERTIFICATE-----
-MIID3TCCAsWgAwIBAgIOHaIAAQAC7LdggHiNtgYwDQYJKoZIhvcNAQEFBQAweTELMAkGA1UEBhMC
-REUxHDAaBgNVBAoTE1RDIFRydXN0Q2VudGVyIEdtYkgxJDAiBgNVBAsTG1RDIFRydXN0Q2VudGVy
-IFVuaXZlcnNhbCBDQTEmMCQGA1UEAxMdVEMgVHJ1c3RDZW50ZXIgVW5pdmVyc2FsIENBIEkwHhcN
-MDYwMzIyMTU1NDI4WhcNMjUxMjMxMjI1OTU5WjB5MQswCQYDVQQGEwJERTEcMBoGA1UEChMTVEMg
-VHJ1c3RDZW50ZXIgR21iSDEkMCIGA1UECxMbVEMgVHJ1c3RDZW50ZXIgVW5pdmVyc2FsIENBMSYw
-JAYDVQQDEx1UQyBUcnVzdENlbnRlciBVbml2ZXJzYWwgQ0EgSTCCASIwDQYJKoZIhvcNAQEBBQAD
-ggEPADCCAQoCggEBAKR3I5ZEr5D0MacQ9CaHnPM42Q9e3s9B6DGtxnSRJJZ4Hgmgm5qVSkr1YnwC
-qMqs+1oEdjneX/H5s7/zA1hV0qq34wQi0fiU2iIIAI3TfCZdzHd55yx4Oagmcw6iXSVphU9VDprv
-xrlE4Vc93x9UIuVvZaozhDrzznq+VZeujRIPFDPiUHDDSYcTvFHe15gSWu86gzOSBnWLknwSaHtw
-ag+1m7Z3W0hZneTvWq3zwZ7U10VOylY0Ibw+F1tvdwxIAUMpsN0/lm7mlaoMwCC2/T42J5zjXM9O
-gdwZu5GQfezmlwQek8wiSdeXhrYTCjxDI3d+8NzmzSQfO4ObNDqDNOMCAwEAAaNjMGEwHwYDVR0j
-BBgwFoAUkqR1LKSevoFE63n8isWVpesQdXMwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC
-AYYwHQYDVR0OBBYEFJKkdSyknr6BROt5/IrFlaXrEHVzMA0GCSqGSIb3DQEBBQUAA4IBAQAo0uCG
-1eb4e/CX3CJrO5UUVg8RMKWaTzqwOuAGy2X17caXJ/4l8lfmXpWMPmRgFVp/Lw0BxbFg/UU1z/Cy
-vwbZ71q+s2IhtNerNXxTPqYn8aEt2hojnczd7Dwtnic0XQ/CNnm8yUpiLe1r2X1BQ3y2qsrtYbE3
-ghUJGooWMNjsydZHcnhLEEYUjl8Or+zHL6sQ17bxbuyGssLoDZJz3KL0Dzq/YSMQiZxIQG5wALPT
-ujdEWBF6AmqI8Dc08BnprNRlc/ZpjGSUOnmFKbAWKwyCPwacx/0QK54PLLae4xW/2TYcuiUaUj0a
-7CIMHOCkoj3w6DnPgcB77V0fb8XQC9eY
------END CERTIFICATE-----
-
-Deutsche Telekom Root CA 2
-==========================
------BEGIN CERTIFICATE-----
-MIIDnzCCAoegAwIBAgIBJjANBgkqhkiG9w0BAQUFADBxMQswCQYDVQQGEwJERTEcMBoGA1UEChMT
-RGV1dHNjaGUgVGVsZWtvbSBBRzEfMB0GA1UECxMWVC1UZWxlU2VjIFRydXN0IENlbnRlcjEjMCEG
-A1UEAxMaRGV1dHNjaGUgVGVsZWtvbSBSb290IENBIDIwHhcNOTkwNzA5MTIxMTAwWhcNMTkwNzA5
-MjM1OTAwWjBxMQswCQYDVQQGEwJERTEcMBoGA1UEChMTRGV1dHNjaGUgVGVsZWtvbSBBRzEfMB0G
-A1UECxMWVC1UZWxlU2VjIFRydXN0IENlbnRlcjEjMCEGA1UEAxMaRGV1dHNjaGUgVGVsZWtvbSBS
-b290IENBIDIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCrC6M14IspFLEUha88EOQ5
-bzVdSq7d6mGNlUn0b2SjGmBmpKlAIoTZ1KXleJMOaAGtuU1cOs7TuKhCQN/Po7qCWWqSG6wcmtoI
-KyUn+WkjR/Hg6yx6m/UTAtB+NHzCnjwAWav12gz1MjwrrFDa1sPeg5TKqAyZMg4ISFZbavva4VhY
-AUlfckE8FQYBjl2tqriTtM2e66foai1SNNs671x1Udrb8zH57nGYMsRUFUQM+ZtV7a3fGAigo4aK
-Se5TBY8ZTNXeWHmb0mocQqvF1afPaA+W5OFhmHZhyJF81j4A4pFQh+GdCuatl9Idxjp9y7zaAzTV
-jlsB9WoHtxa2bkp/AgMBAAGjQjBAMB0GA1UdDgQWBBQxw3kbuvVT1xfgiXotF2wKsyudMzAPBgNV
-HRMECDAGAQH/AgEFMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQUFAAOCAQEAlGRZrTlk5ynr
-E/5aw4sTV8gEJPB0d8Bg42f76Ymmg7+Wgnxu1MM9756AbrsptJh6sTtU6zkXR34ajgv8HzFZMQSy
-zhfzLMdiNlXiItiJVbSYSKpk+tYcNthEeFpaIzpXl/V6ME+un2pMSyuOoAPjPuCp1NJ70rOo4nI8
-rZ7/gFnkm0W09juwzTkZmDLl6iFhkOQxIY40sfcvNUqFENrnijchvllj4PKFiDFT1FQUhXB59C4G
-dyd1Lx+4ivn+xbrYNuSD7Odlt79jWvNGr4GUN9RBjNYj1h7P9WgbRGOiWrqnNVmh5XAFmw4jV5mU
-Cm26OWMohpLzGITY+9HPBVZkVw==
------END CERTIFICATE-----
-
-ComSign Secured CA
-==================
------BEGIN CERTIFICATE-----
-MIIDqzCCApOgAwIBAgIRAMcoRwmzuGxFjB36JPU2TukwDQYJKoZIhvcNAQEFBQAwPDEbMBkGA1UE
-AxMSQ29tU2lnbiBTZWN1cmVkIENBMRAwDgYDVQQKEwdDb21TaWduMQswCQYDVQQGEwJJTDAeFw0w
-NDAzMjQxMTM3MjBaFw0yOTAzMTYxNTA0NTZaMDwxGzAZBgNVBAMTEkNvbVNpZ24gU2VjdXJlZCBD
-QTEQMA4GA1UEChMHQ29tU2lnbjELMAkGA1UEBhMCSUwwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
-ggEKAoIBAQDGtWhfHZQVw6QIVS3joFd67+l0Kru5fFdJGhFeTymHDEjWaueP1H5XJLkGieQcPOqs
-49ohgHMhCu95mGwfCP+hUH3ymBvJVG8+pSjsIQQPRbsHPaHA+iqYHU4Gk/v1iDurX8sWv+bznkqH
-7Rnqwp9D5PGBpX8QTz7RSmKtUxvLg/8HZaWSLWapW7ha9B20IZFKF3ueMv5WJDmyVIRD9YTC2LxB
-kMyd1mja6YJQqTtoz7VdApRgFrFD2UNd3V2Hbuq7s8lr9gOUCXDeFhF6K+h2j0kQmHe5Y1yLM5d1
-9guMsqtb3nQgJT/j8xH5h2iGNXHDHYwt6+UarA9z1YJZQIDTAgMBAAGjgacwgaQwDAYDVR0TBAUw
-AwEB/zBEBgNVHR8EPTA7MDmgN6A1hjNodHRwOi8vZmVkaXIuY29tc2lnbi5jby5pbC9jcmwvQ29t
-U2lnblNlY3VyZWRDQS5jcmwwDgYDVR0PAQH/BAQDAgGGMB8GA1UdIwQYMBaAFMFL7XC29z58ADsA
-j8c+DkWfHl3sMB0GA1UdDgQWBBTBS+1wtvc+fAA7AI/HPg5Fnx5d7DANBgkqhkiG9w0BAQUFAAOC
-AQEAFs/ukhNQq3sUnjO2QiBq1BW9Cav8cujvR3qQrFHBZE7piL1DRYHjZiM/EoZNGeQFsOY3wo3a
-BijJD4mkU6l1P7CW+6tMM1X5eCZGbxs2mPtCdsGCuY7e+0X5YxtiOzkGynd6qDwJz2w2PQ8KRUtp
-FhpFfTMDZflScZAmlaxMDPWLkz/MdXSFmLr/YnpNH4n+rr2UAJm/EaXc4HnFFgt9AmEd6oX5AhVP
-51qJThRv4zdLhfXBPGHg/QVBspJ/wx2g0K5SZGBrGMYmnNj1ZOQ2GmKfig8+/21OGVZOIJFsnzQz
-OjRXUDpvgV4GxvU+fE6OK85lBi5d0ipTdF7Tbieejw==
------END CERTIFICATE-----
-
-Cybertrust Global Root
-======================
------BEGIN CERTIFICATE-----
-MIIDoTCCAomgAwIBAgILBAAAAAABD4WqLUgwDQYJKoZIhvcNAQEFBQAwOzEYMBYGA1UEChMPQ3li
-ZXJ0cnVzdCwgSW5jMR8wHQYDVQQDExZDeWJlcnRydXN0IEdsb2JhbCBSb290MB4XDTA2MTIxNTA4
-MDAwMFoXDTIxMTIxNTA4MDAwMFowOzEYMBYGA1UEChMPQ3liZXJ0cnVzdCwgSW5jMR8wHQYDVQQD
-ExZDeWJlcnRydXN0IEdsb2JhbCBSb290MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
-+Mi8vRRQZhP/8NN57CPytxrHjoXxEnOmGaoQ25yiZXRadz5RfVb23CO21O1fWLE3TdVJDm71aofW
-0ozSJ8bi/zafmGWgE07GKmSb1ZASzxQG9Dvj1Ci+6A74q05IlG2OlTEQXO2iLb3VOm2yHLtgwEZL
-AfVJrn5GitB0jaEMAs7u/OePuGtm839EAL9mJRQr3RAwHQeWP032a7iPt3sMpTjr3kfb1V05/Iin
-89cqdPHoWqI7n1C6poxFNcJQZZXcY4Lv3b93TZxiyWNzFtApD0mpSPCzqrdsxacwOUBdrsTiXSZT
-8M4cIwhhqJQZugRiQOwfOHB3EgZxpzAYXSUnpQIDAQABo4GlMIGiMA4GA1UdDwEB/wQEAwIBBjAP
-BgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBS2CHsNesysIEyGVjJez6tuhS1wVzA/BgNVHR8EODA2
-MDSgMqAwhi5odHRwOi8vd3d3Mi5wdWJsaWMtdHJ1c3QuY29tL2NybC9jdC9jdHJvb3QuY3JsMB8G
-A1UdIwQYMBaAFLYIew16zKwgTIZWMl7Pq26FLXBXMA0GCSqGSIb3DQEBBQUAA4IBAQBW7wojoFRO
-lZfJ+InaRcHUowAl9B8Tq7ejhVhpwjCt2BWKLePJzYFa+HMjWqd8BfP9IjsO0QbE2zZMcwSO5bAi
-5MXzLqXZI+O4Tkogp24CJJ8iYGd7ix1yCcUxXOl5n4BHPa2hCwcUPUf/A2kaDAtE52Mlp3+yybh2
-hO0j9n0Hq0V+09+zv+mKts2oomcrUtW3ZfA5TGOgkXmTUg9U3YO7n9GPp1Nzw8v/MOx8BLjYRB+T
-X3EJIrduPuocA06dGiBh+4E37F78CkWr1+cXVdCg6mCbpvbjjFspwgZgFJ0tl0ypkxWdYcQBX0jW
-WL1WMRJOEcgh4LMRkWXbtKaIOM5V
------END CERTIFICATE-----
-
-ePKI Root Certification Authority
-=================================
------BEGIN CERTIFICATE-----
-MIIFsDCCA5igAwIBAgIQFci9ZUdcr7iXAF7kBtK8nTANBgkqhkiG9w0BAQUFADBeMQswCQYDVQQG
-EwJUVzEjMCEGA1UECgwaQ2h1bmdod2EgVGVsZWNvbSBDby4sIEx0ZC4xKjAoBgNVBAsMIWVQS0kg
-Um9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNDEyMjAwMjMxMjdaFw0zNDEyMjAwMjMx
-MjdaMF4xCzAJBgNVBAYTAlRXMSMwIQYDVQQKDBpDaHVuZ2h3YSBUZWxlY29tIENvLiwgTHRkLjEq
-MCgGA1UECwwhZVBLSSBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIICIjANBgkqhkiG9w0B
-AQEFAAOCAg8AMIICCgKCAgEA4SUP7o3biDN1Z82tH306Tm2d0y8U82N0ywEhajfqhFAHSyZbCUNs
-IZ5qyNUD9WBpj8zwIuQf5/dqIjG3LBXy4P4AakP/h2XGtRrBp0xtInAhijHyl3SJCRImHJ7K2RKi
-lTza6We/CKBk49ZCt0Xvl/T29de1ShUCWH2YWEtgvM3XDZoTM1PRYfl61dd4s5oz9wCGzh1NlDiv
-qOx4UXCKXBCDUSH3ET00hl7lSM2XgYI1TBnsZfZrxQWh7kcT1rMhJ5QQCtkkO7q+RBNGMD+XPNjX
-12ruOzjjK9SXDrkb5wdJfzcq+Xd4z1TtW0ado4AOkUPB1ltfFLqfpo0kR0BZv3I4sjZsN/+Z0V0O
-WQqraffAsgRFelQArr5T9rXn4fg8ozHSqf4hUmTFpmfwdQcGlBSBVcYn5AGPF8Fqcde+S/uUWH1+
-ETOxQvdibBjWzwloPn9s9h6PYq2lY9sJpx8iQkEeb5mKPtf5P0B6ebClAZLSnT0IFaUQAS2zMnao
-lQ2zepr7BxB4EW/hj8e6DyUadCrlHJhBmd8hh+iVBmoKs2pHdmX2Os+PYhcZewoozRrSgx4hxyy/
-vv9haLdnG7t4TY3OZ+XkwY63I2binZB1NJipNiuKmpS5nezMirH4JYlcWrYvjB9teSSnUmjDhDXi
-Zo1jDiVN1Rmy5nk3pyKdVDECAwEAAaNqMGgwHQYDVR0OBBYEFB4M97Zn8uGSJglFwFU5Lnc/Qkqi
-MAwGA1UdEwQFMAMBAf8wOQYEZyoHAAQxMC8wLQIBADAJBgUrDgMCGgUAMAcGBWcqAwAABBRFsMLH
-ClZ87lt4DJX5GFPBphzYEDANBgkqhkiG9w0BAQUFAAOCAgEACbODU1kBPpVJufGBuvl2ICO1J2B0
-1GqZNF5sAFPZn/KmsSQHRGoqxqWOeBLoR9lYGxMqXnmbnwoqZ6YlPwZpVnPDimZI+ymBV3QGypzq
-KOg4ZyYr8dW1P2WT+DZdjo2NQCCHGervJ8A9tDkPJXtoUHRVnAxZfVo9QZQlUgjgRywVMRnVvwdV
-xrsStZf0X4OFunHB2WyBEXYKCrC/gpf36j36+uwtqSiUO1bd0lEursC9CBWMd1I0ltabrNMdjmEP
-NXubrjlpC2JgQCA2j6/7Nu4tCEoduL+bXPjqpRugc6bY+G7gMwRfaKonh+3ZwZCc7b3jajWvY9+r
-GNm65ulK6lCKD2GTHuItGeIwlDWSXQ62B68ZgI9HkFFLLk3dheLSClIKF5r8GrBQAuUBo2M3IUxE
-xJtRmREOc5wGj1QupyheRDmHVi03vYVElOEMSyycw5KFNGHLD7ibSkNS/jQ6fbjpKdx2qcgw+BRx
-gMYeNkh0IkFch4LoGHGLQYlE535YW6i4jRPpp2zDR+2zGp1iro2C6pSe3VkQw63d4k3jMdXH7Ojy
-sP6SHhYKGvzZ8/gntsm+HbRsZJB/9OTEW9c3rkIO3aQab3yIVMUWbuF6aC74Or8NpDyJO3inTmOD
-BCEIZ43ygknQW/2xzQ+DhNQ+IIX3Sj0rnP0qCglN6oH4EZw=
------END CERTIFICATE-----
-
-T\xc3\x9c\x42\xC4\xB0TAK UEKAE K\xC3\xB6k Sertifika Hizmet Sa\xC4\x9Flay\xc4\xb1\x63\xc4\xb1s\xc4\xb1 - S\xC3\xBCr\xC3\xBCm 3
-=============================================================================================================================
------BEGIN CERTIFICATE-----
-MIIFFzCCA/+gAwIBAgIBETANBgkqhkiG9w0BAQUFADCCASsxCzAJBgNVBAYTAlRSMRgwFgYDVQQH
-DA9HZWJ6ZSAtIEtvY2FlbGkxRzBFBgNVBAoMPlTDvHJraXllIEJpbGltc2VsIHZlIFRla25vbG9q
-aWsgQXJhxZ90xLFybWEgS3VydW11IC0gVMOcQsSwVEFLMUgwRgYDVQQLDD9VbHVzYWwgRWxla3Ry
-b25payB2ZSBLcmlwdG9sb2ppIEFyYcWfdMSxcm1hIEVuc3RpdMO8c8O8IC0gVUVLQUUxIzAhBgNV
-BAsMGkthbXUgU2VydGlmaWthc3lvbiBNZXJrZXppMUowSAYDVQQDDEFUw5xCxLBUQUsgVUVLQUUg
-S8O2ayBTZXJ0aWZpa2EgSGl6bWV0IFNhxJ9sYXnEsWPEsXPEsSAtIFPDvHLDvG0gMzAeFw0wNzA4
-MjQxMTM3MDdaFw0xNzA4MjExMTM3MDdaMIIBKzELMAkGA1UEBhMCVFIxGDAWBgNVBAcMD0dlYnpl
-IC0gS29jYWVsaTFHMEUGA1UECgw+VMO8cmtpeWUgQmlsaW1zZWwgdmUgVGVrbm9sb2ppayBBcmHF
-n3TEsXJtYSBLdXJ1bXUgLSBUw5xCxLBUQUsxSDBGBgNVBAsMP1VsdXNhbCBFbGVrdHJvbmlrIHZl
-IEtyaXB0b2xvamkgQXJhxZ90xLFybWEgRW5zdGl0w7xzw7wgLSBVRUtBRTEjMCEGA1UECwwaS2Ft
-dSBTZXJ0aWZpa2FzeW9uIE1lcmtlemkxSjBIBgNVBAMMQVTDnELEsFRBSyBVRUtBRSBLw7ZrIFNl
-cnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sxc8SxIC0gU8O8csO8bSAzMIIBIjANBgkqhkiG9w0B
-AQEFAAOCAQ8AMIIBCgKCAQEAim1L/xCIOsP2fpTo6iBkcK4hgb46ezzb8R1Sf1n68yJMlaCQvEhO
-Eav7t7WNeoMojCZG2E6VQIdhn8WebYGHV2yKO7Rm6sxA/OOqbLLLAdsyv9Lrhc+hDVXDWzhXcLh1
-xnnRFDDtG1hba+818qEhTsXOfJlfbLm4IpNQp81McGq+agV/E5wrHur+R84EpW+sky58K5+eeROR
-6Oqeyjh1jmKwlZMq5d/pXpduIF9fhHpEORlAHLpVK/swsoHvhOPc7Jg4OQOFCKlUAwUp8MmPi+oL
-hmUZEdPpCSPeaJMDyTYcIW7OjGbxmTDY17PDHfiBLqi9ggtm/oLL4eAagsNAgQIDAQABo0IwQDAd
-BgNVHQ4EFgQUvYiHyY/2pAoLquvF/pEjnatKijIwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQF
-MAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAB18+kmPNOm3JpIWmgV050vQbTlswyb2zrgxvMTfvCr4
-N5EY3ATIZJkrGG2AA1nJrvhY0D7twyOfaTyGOBye79oneNGEN3GKPEs5z35FBtYt2IpNeBLWrcLT
-y9LQQfMmNkqblWwM7uXRQydmwYj3erMgbOqwaSvHIOgMA8RBBZniP+Rr+KCGgceExh/VS4ESshYh
-LBOhgLJeDEoTniDYYkCrkOpkSi+sDQESeUWoL4cZaMjihccwsnX5OD+ywJO0a+IDRM5noN+J1q2M
-dqMTw5RhK2vZbMEHCiIHhWyFJEapvj+LeISCfiQMnf2BN+MlqO02TpUsyZyQ2uypQjyttgI=
------END CERTIFICATE-----
-
-Buypass Class 2 CA 1
-====================
------BEGIN CERTIFICATE-----
-MIIDUzCCAjugAwIBAgIBATANBgkqhkiG9w0BAQUFADBLMQswCQYDVQQGEwJOTzEdMBsGA1UECgwU
-QnV5cGFzcyBBUy05ODMxNjMzMjcxHTAbBgNVBAMMFEJ1eXBhc3MgQ2xhc3MgMiBDQSAxMB4XDTA2
-MTAxMzEwMjUwOVoXDTE2MTAxMzEwMjUwOVowSzELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1eXBh
-c3MgQVMtOTgzMTYzMzI3MR0wGwYDVQQDDBRCdXlwYXNzIENsYXNzIDIgQ0EgMTCCASIwDQYJKoZI
-hvcNAQEBBQADggEPADCCAQoCggEBAIs8B0XY9t/mx8q6jUPFR42wWsE425KEHK8T1A9vNkYgxC7M
-cXA0ojTTNy7Y3Tp3L8DrKehc0rWpkTSHIln+zNvnma+WwajHQN2lFYxuyHyXA8vmIPLXl18xoS83
-0r7uvqmtqEyeIWZDO6i88wmjONVZJMHCR3axiFyCO7srpgTXjAePzdVBHfCuuCkslFJgNJQ72uA4
-0Z0zPhX0kzLFANq1KWYOOngPIVJfAuWSeyXTkh4vFZ2B5J2O6O+JzhRMVB0cgRJNcKi+EAUXfh/R
-uFdV7c27UsKwHnjCTTZoy1YmwVLBvXb3WNVyfh9EdrsAiR0WnVE1703CVu9r4Iw7DekCAwEAAaNC
-MEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUP42aWYv8e3uco684sDntkHGA1sgwDgYDVR0P
-AQH/BAQDAgEGMA0GCSqGSIb3DQEBBQUAA4IBAQAVGn4TirnoB6NLJzKyQJHyIdFkhb5jatLPgcIV
-1Xp+DCmsNx4cfHZSldq1fyOhKXdlyTKdqC5Wq2B2zha0jX94wNWZUYN/Xtm+DKhQ7SLHrQVMdvvt
-7h5HZPb3J31cKA9FxVxiXqaakZG3Uxcu3K1gnZZkOb1naLKuBctN518fV4bVIJwo+28TOPX2EZL2
-fZleHwzoq0QkKXJAPTZSr4xYkHPB7GEseaHsh7U/2k3ZIQAw3pDaDtMaSKk+hQsUi4y8QZ5q9w5w
-wDX3OaJdZtB7WZ+oRxKaJyOkLY4ng5IgodcVf/EuGO70SH8vf/GhGLWhC5SgYiAynB321O+/TIho
------END CERTIFICATE-----
-
-Buypass Class 3 CA 1
-====================
------BEGIN CERTIFICATE-----
-MIIDUzCCAjugAwIBAgIBAjANBgkqhkiG9w0BAQUFADBLMQswCQYDVQQGEwJOTzEdMBsGA1UECgwU
-QnV5cGFzcyBBUy05ODMxNjMzMjcxHTAbBgNVBAMMFEJ1eXBhc3MgQ2xhc3MgMyBDQSAxMB4XDTA1
-MDUwOTE0MTMwM1oXDTE1MDUwOTE0MTMwM1owSzELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1eXBh
-c3MgQVMtOTgzMTYzMzI3MR0wGwYDVQQDDBRCdXlwYXNzIENsYXNzIDMgQ0EgMTCCASIwDQYJKoZI
-hvcNAQEBBQADggEPADCCAQoCggEBAKSO13TZKWTeXx+HgJHqTjnmGcZEC4DVC69TB4sSveZn8AKx
-ifZgisRbsELRwCGoy+Gb72RRtqfPFfV0gGgEkKBYouZ0plNTVUhjP5JW3SROjvi6K//zNIqeKNc0
-n6wv1g/xpC+9UrJJhW05NfBEMJNGJPO251P7vGGvqaMU+8IXF4Rs4HyI+MkcVyzwPX6UvCWThOia
-AJpFBUJXgPROztmuOfbIUxAMZTpHe2DC1vqRycZxbL2RhzyRhkmr8w+gbCZ2Xhysm3HljbybIR6c
-1jh+JIAVMYKWsUnTYjdbiAwKYjT+p0h+mbEwi5A3lRyoH6UsjfRVyNvdWQrCrXig9IsCAwEAAaNC
-MEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUOBTmyPCppAP0Tj4io1vy1uCtQHQwDgYDVR0P
-AQH/BAQDAgEGMA0GCSqGSIb3DQEBBQUAA4IBAQABZ6OMySU9E2NdFm/soT4JXJEVKirZgCFPBdy7
-pYmrEzMqnji3jG8CcmPHc3ceCQa6Oyh7pEfJYWsICCD8igWKH7y6xsL+z27sEzNxZy5p+qksP2bA
-EllNC1QCkoS72xLvg3BweMhT+t/Gxv/ciC8HwEmdMldg0/L2mSlf56oBzKwzqBwKu5HEA6BvtjT5
-htOzdlSY9EqBs1OdTUDs5XcTRa9bqh/YL0yCe/4qxFi7T/ye/QNlGioOw6UgFpRreaaiErS7GqQj
-el/wroQk5PMr+4okoyeYZdowdXb8GZHo2+ubPzK/QJcHJrrM85SFSnonk8+QQtS4Wxam58tAA915
------END CERTIFICATE-----
-
-EBG Elektronik Sertifika Hizmet Sa\xC4\x9Flay\xc4\xb1\x63\xc4\xb1s\xc4\xb1
-==========================================================================
------BEGIN CERTIFICATE-----
-MIIF5zCCA8+gAwIBAgIITK9zQhyOdAIwDQYJKoZIhvcNAQEFBQAwgYAxODA2BgNVBAMML0VCRyBF
-bGVrdHJvbmlrIFNlcnRpZmlrYSBIaXptZXQgU2HEn2xhecSxY8Sxc8SxMTcwNQYDVQQKDC5FQkcg
-QmlsacWfaW0gVGVrbm9sb2ppbGVyaSB2ZSBIaXptZXRsZXJpIEEuxZ4uMQswCQYDVQQGEwJUUjAe
-Fw0wNjA4MTcwMDIxMDlaFw0xNjA4MTQwMDMxMDlaMIGAMTgwNgYDVQQDDC9FQkcgRWxla3Ryb25p
-ayBTZXJ0aWZpa2EgSGl6bWV0IFNhxJ9sYXnEsWPEsXPEsTE3MDUGA1UECgwuRUJHIEJpbGnFn2lt
-IFRla25vbG9qaWxlcmkgdmUgSGl6bWV0bGVyaSBBLsWeLjELMAkGA1UEBhMCVFIwggIiMA0GCSqG
-SIb3DQEBAQUAA4ICDwAwggIKAoICAQDuoIRh0DpqZhAy2DE4f6en5f2h4fuXd7hxlugTlkaDT7by
-X3JWbhNgpQGR4lvFzVcfd2NR/y8927k/qqk153nQ9dAktiHq6yOU/im/+4mRDGSaBUorzAzu8T2b
-gmmkTPiab+ci2hC6X5L8GCcKqKpE+i4stPtGmggDg3KriORqcsnlZR9uKg+ds+g75AxuetpX/dfr
-eYteIAbTdgtsApWjluTLdlHRKJ2hGvxEok3MenaoDT2/F08iiFD9rrbskFBKW5+VQarKD7JK/oCZ
-TqNGFav4c0JqwmZ2sQomFd2TkuzbqV9UIlKRcF0T6kjsbgNs2d1s/OsNA/+mgxKb8amTD8UmTDGy
-Y5lhcucqZJnSuOl14nypqZoaqsNW2xCaPINStnuWt6yHd6i58mcLlEOzrz5z+kI2sSXFCjEmN1Zn
-uqMLfdb3ic1nobc6HmZP9qBVFCVMLDMNpkGMvQQxahByCp0OLna9XvNRiYuoP1Vzv9s6xiQFlpJI
-qkuNKgPlV5EQ9GooFW5Hd4RcUXSfGenmHmMWOeMRFeNYGkS9y8RsZteEBt8w9DeiQyJ50hBs37vm
-ExH8nYQKE3vwO9D8owrXieqWfo1IhR5kX9tUoqzVegJ5a9KK8GfaZXINFHDk6Y54jzJ0fFfy1tb0
-Nokb+Clsi7n2l9GkLqq+CxnCRelwXQIDAJ3Zo2MwYTAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB
-/wQEAwIBBjAdBgNVHQ4EFgQU587GT/wWZ5b6SqMHwQSny2re2kcwHwYDVR0jBBgwFoAU587GT/wW
-Z5b6SqMHwQSny2re2kcwDQYJKoZIhvcNAQEFBQADggIBAJuYml2+8ygjdsZs93/mQJ7ANtyVDR2t
-FcU22NU57/IeIl6zgrRdu0waypIN30ckHrMk2pGI6YNw3ZPX6bqz3xZaPt7gyPvT/Wwp+BVGoGgm
-zJNSroIBk5DKd8pNSe/iWtkqvTDOTLKBtjDOWU/aWR1qeqRFsIImgYZ29fUQALjuswnoT4cCB64k
-XPBfrAowzIpAoHMEwfuJJPaaHFy3PApnNgUIMbOv2AFoKuB4j3TeuFGkjGwgPaL7s9QJ/XvCgKqT
-bCmYIai7FvOpEl90tYeY8pUm3zTvilORiF0alKM/fCL414i6poyWqD1SNGKfAB5UVUJnxk1Gj7sU
-RT0KlhaOEKGXmdXTMIXM3rRyt7yKPBgpaP3ccQfuJDlq+u2lrDgv+R4QDgZxGhBM/nV+/x5XOULK
-1+EVoVZVWRvRo68R2E7DpSvvkL/A7IITW43WciyTTo9qKd+FPNMN4KIYEsxVL0e3p5sC/kH2iExt
-2qkBR4NkJ2IQgtYSe14DHzSpyZH+r11thie3I6p1GMog57AP14kOpmciY/SDQSsGS7tY1dHXt7kQ
-Y9iJSrSq3RZj9W6+YKH47ejWkE8axsWgKdOnIaj1Wjz3x0miIZpKlVIglnKaZsv30oZDfCK+lvm9
-AahH3eU7QPl1K5srRmSGjR70j/sHd9DqSaIcjVIUpgqT
------END CERTIFICATE-----
-
-certSIGN ROOT CA
-================
------BEGIN CERTIFICATE-----
-MIIDODCCAiCgAwIBAgIGIAYFFnACMA0GCSqGSIb3DQEBBQUAMDsxCzAJBgNVBAYTAlJPMREwDwYD
-VQQKEwhjZXJ0U0lHTjEZMBcGA1UECxMQY2VydFNJR04gUk9PVCBDQTAeFw0wNjA3MDQxNzIwMDRa
-Fw0zMTA3MDQxNzIwMDRaMDsxCzAJBgNVBAYTAlJPMREwDwYDVQQKEwhjZXJ0U0lHTjEZMBcGA1UE
-CxMQY2VydFNJR04gUk9PVCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALczuX7I
-JUqOtdu0KBuqV5Do0SLTZLrTk+jUrIZhQGpgV2hUhE28alQCBf/fm5oqrl0Hj0rDKH/v+yv6efHH
-rfAQUySQi2bJqIirr1qjAOm+ukbuW3N7LBeCgV5iLKECZbO9xSsAfsT8AzNXDe3i+s5dRdY4zTW2
-ssHQnIFKquSyAVwdj1+ZxLGt24gh65AIgoDzMKND5pCCrlUoSe1b16kQOA7+j0xbm0bqQfWwCHTD
-0IgztnzXdN/chNFDDnU5oSVAKOp4yw4sLjmdjItuFhwvJoIQ4uNllAoEwF73XVv4EOLQunpL+943
-AAAaWyjj0pxzPjKHmKHJUS/X3qwzs08CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8B
-Af8EBAMCAcYwHQYDVR0OBBYEFOCMm9slSbPxfIbWskKHC9BroNnkMA0GCSqGSIb3DQEBBQUAA4IB
-AQA+0hyJLjX8+HXd5n9liPRyTMks1zJO890ZeUe9jjtbkw9QSSQTaxQGcu8J06Gh40CEyecYMnQ8
-SG4Pn0vU9x7Tk4ZkVJdjclDVVc/6IJMCopvDI5NOFlV2oHB5bc0hH88vLbwZ44gx+FkagQnIl6Z0
-x2DEW8xXjrJ1/RsCCdtZb3KTafcxQdaIOL+Hsr0Wefmq5L6IJd1hJyMctTEHBDa0GpC9oHRxUIlt
-vBTjD4au8as+x6AJzKNI0eDbZOeStc+vckNwi/nDhDwTqn6Sm1dTk/pwwpEOMfmbZ13pljheX7Nz
-TogVZ96edhBiIL5VaZVDADlN9u6wWk5JRFRYX0KD
------END CERTIFICATE-----
-
-CNNIC ROOT
-==========
------BEGIN CERTIFICATE-----
-MIIDVTCCAj2gAwIBAgIESTMAATANBgkqhkiG9w0BAQUFADAyMQswCQYDVQQGEwJDTjEOMAwGA1UE
-ChMFQ05OSUMxEzARBgNVBAMTCkNOTklDIFJPT1QwHhcNMDcwNDE2MDcwOTE0WhcNMjcwNDE2MDcw
-OTE0WjAyMQswCQYDVQQGEwJDTjEOMAwGA1UEChMFQ05OSUMxEzARBgNVBAMTCkNOTklDIFJPT1Qw
-ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDTNfc/c3et6FtzF8LRb+1VvG7q6KR5smzD
-o+/hn7E7SIX1mlwhIhAsxYLO2uOabjfhhyzcuQxauohV3/2q2x8x6gHx3zkBwRP9SFIhxFXf2tiz
-VHa6dLG3fdfA6PZZxU3Iva0fFNrfWEQlMhkqx35+jq44sDB7R3IJMfAw28Mbdim7aXZOV/kbZKKT
-VrdvmW7bCgScEeOAH8tjlBAKqeFkgjH5jCftppkA9nCTGPihNIaj3XrCGHn2emU1z5DrvTOTn1Or
-czvmmzQgLx3vqR1jGqCA2wMv+SYahtKNu6m+UjqHZ0gNv7Sg2Ca+I19zN38m5pIEo3/PIKe38zrK
-y5nLAgMBAAGjczBxMBEGCWCGSAGG+EIBAQQEAwIABzAfBgNVHSMEGDAWgBRl8jGtKvf33VKWCscC
-wQ7vptU7ETAPBgNVHRMBAf8EBTADAQH/MAsGA1UdDwQEAwIB/jAdBgNVHQ4EFgQUZfIxrSr3991S
-lgrHAsEO76bVOxEwDQYJKoZIhvcNAQEFBQADggEBAEs17szkrr/Dbq2flTtLP1se31cpolnKOOK5
-Gv+e5m4y3R6u6jW39ZORTtpC4cMXYFDy0VwmuYK36m3knITnA3kXr5g9lNvHugDnuL8BV8F3RTIM
-O/G0HAiw/VGgod2aHRM2mm23xzy54cXZF/qD1T0VoDy7HgviyJA/qIYM/PmLXoXLT1tLYhFHxUV8
-BS9BsZ4QaRuZluBVeftOhpm4lNqGOGqTo+fLbuXf6iFViZx9fX+Y9QCJ7uOEwFyWtcVG6kbghVW2
-G8kS1sHNzYDzAgE8yGnLRUhj2JTQ7IUOO04RZfSCjKY9ri4ilAnIXOo8gV0WKgOXFlUJ24pBgp5m
-mxE=
------END CERTIFICATE-----
-
-ApplicationCA - Japanese Government
-===================================
------BEGIN CERTIFICATE-----
-MIIDoDCCAoigAwIBAgIBMTANBgkqhkiG9w0BAQUFADBDMQswCQYDVQQGEwJKUDEcMBoGA1UEChMT
-SmFwYW5lc2UgR292ZXJubWVudDEWMBQGA1UECxMNQXBwbGljYXRpb25DQTAeFw0wNzEyMTIxNTAw
-MDBaFw0xNzEyMTIxNTAwMDBaMEMxCzAJBgNVBAYTAkpQMRwwGgYDVQQKExNKYXBhbmVzZSBHb3Zl
-cm5tZW50MRYwFAYDVQQLEw1BcHBsaWNhdGlvbkNBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
-CgKCAQEAp23gdE6Hj6UG3mii24aZS2QNcfAKBZuOquHMLtJqO8F6tJdhjYq+xpqcBrSGUeQ3DnR4
-fl+Kf5Sk10cI/VBaVuRorChzoHvpfxiSQE8tnfWuREhzNgaeZCw7NCPbXCbkcXmP1G55IrmTwcrN
-wVbtiGrXoDkhBFcsovW8R0FPXjQilbUfKW1eSvNNcr5BViCH/OlQR9cwFO5cjFW6WY2H/CPek9AE
-jP3vbb3QesmlOmpyM8ZKDQUXKi17safY1vC+9D/qDihtQWEjdnjDuGWk81quzMKq2edY3rZ+nYVu
-nyoKb58DKTCXKB28t89UKU5RMfkntigm/qJj5kEW8DOYRwIDAQABo4GeMIGbMB0GA1UdDgQWBBRU
-WssmP3HMlEYNllPqa0jQk/5CdTAOBgNVHQ8BAf8EBAMCAQYwWQYDVR0RBFIwUKROMEwxCzAJBgNV
-BAYTAkpQMRgwFgYDVQQKDA/ml6XmnKzlm73mlL/lupwxIzAhBgNVBAsMGuOCouODl+ODquOCseOD
-vOOCt+ODp+ODs0NBMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBADlqRHZ3ODrs
-o2dGD/mLBqj7apAxzn7s2tGJfHrrLgy9mTLnsCTWw//1sogJhyzjVOGjprIIC8CFqMjSnHH2HZ9g
-/DgzE+Ge3Atf2hZQKXsvcJEPmbo0NI2VdMV+eKlmXb3KIXdCEKxmJj3ekav9FfBv7WxfEPjzFvYD
-io+nEhEMy/0/ecGc/WLuo89UDNErXxc+4z6/wCs+CZv+iKZ+tJIX/COUgb1up8WMwusRRdv4QcmW
-dupwX3kSa+SjB1oF7ydJzyGfikwJcGapJsErEU4z0g781mzSDjJkaP+tBXhfAx2o45CsJOAPQKdL
-rosot4LKGAfmt1t06SAZf7IbiVQ=
------END CERTIFICATE-----
-
-GeoTrust Primary Certification Authority - G3
-=============================================
------BEGIN CERTIFICATE-----
-MIID/jCCAuagAwIBAgIQFaxulBmyeUtB9iepwxgPHzANBgkqhkiG9w0BAQsFADCBmDELMAkGA1UE
-BhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4xOTA3BgNVBAsTMChjKSAyMDA4IEdlb1RydXN0
-IEluYy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25seTE2MDQGA1UEAxMtR2VvVHJ1c3QgUHJpbWFy
-eSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEczMB4XDTA4MDQwMjAwMDAwMFoXDTM3MTIwMTIz
-NTk1OVowgZgxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTkwNwYDVQQLEzAo
-YykgMjAwOCBHZW9UcnVzdCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxNjA0BgNVBAMT
-LUdlb1RydXN0IFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHMzCCASIwDQYJKoZI
-hvcNAQEBBQADggEPADCCAQoCggEBANziXmJYHTNXOTIz+uvLh4yn1ErdBojqZI4xmKU4kB6Yzy5j
-K/BGvESyiaHAKAxJcCGVn2TAppMSAmUmhsalifD614SgcK9PGpc/BkTVyetyEH3kMSj7HGHmKAdE
-c5IiaacDiGydY8hS2pgn5whMcD60yRLBxWeDXTPzAxHsatBT4tG6NmCUgLthY2xbF37fQJQeqw3C
-IShwiP/WJmxsYAQlTlV+fe+/lEjetx3dcI0FX4ilm/LC7urRQEFtYjgdVgbFA0dRIBn8exALDmKu
-dlW/X3e+PkkBUz2YJQN2JFodtNuJ6nnltrM7P7pMKEF/BqxqjsHQ9gUdfeZChuOl1UcCAwEAAaNC
-MEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFMR5yo6hTgMdHNxr
-2zFblD4/MH8tMA0GCSqGSIb3DQEBCwUAA4IBAQAtxRPPVoB7eni9n64smefv2t+UXglpp+duaIy9
-cr5HqQ6XErhK8WTTOd8lNNTBzU6B8A8ExCSzNJbGpqow32hhc9f5joWJ7w5elShKKiePEI4ufIbE
-Ap7aDHdlDkQNkv39sxY2+hENHYwOB4lqKVb3cvTdFZx3NWZXqxNT2I7BQMXXExZacse3aQHEerGD
-AWh9jUGhlBjBJVz88P6DAod8DQ3PLghcSkANPuyBYeYk28rgDi0Hsj5W3I31QYUHSJsMC8tJP33s
-t/3LjWeJGqvtux6jAAgIFyqCXDFdRootD4abdNlF+9RAsXqqaC2Gspki4cErx5z481+oghLrGREt
------END CERTIFICATE-----
-
-thawte Primary Root CA - G2
-===========================
------BEGIN CERTIFICATE-----
-MIICiDCCAg2gAwIBAgIQNfwmXNmET8k9Jj1Xm67XVjAKBggqhkjOPQQDAzCBhDELMAkGA1UEBhMC
-VVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjE4MDYGA1UECxMvKGMpIDIwMDcgdGhhd3RlLCBJbmMu
-IC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxJDAiBgNVBAMTG3RoYXd0ZSBQcmltYXJ5IFJvb3Qg
-Q0EgLSBHMjAeFw0wNzExMDUwMDAwMDBaFw0zODAxMTgyMzU5NTlaMIGEMQswCQYDVQQGEwJVUzEV
-MBMGA1UEChMMdGhhd3RlLCBJbmMuMTgwNgYDVQQLEy8oYykgMjAwNyB0aGF3dGUsIEluYy4gLSBG
-b3IgYXV0aG9yaXplZCB1c2Ugb25seTEkMCIGA1UEAxMbdGhhd3RlIFByaW1hcnkgUm9vdCBDQSAt
-IEcyMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEotWcgnuVnfFSeIf+iha/BebfowJPDQfGAFG6DAJS
-LSKkQjnE/o/qycG+1E3/n3qe4rF8mq2nhglzh9HnmuN6papu+7qzcMBniKI11KOasf2twu8x+qi5
-8/sIxpHR+ymVo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQU
-mtgAMADna3+FGO6Lts6KDPgR4bswCgYIKoZIzj0EAwMDaQAwZgIxAN344FdHW6fmCsO99YCKlzUN
-G4k8VIZ3KMqh9HneteY4sPBlcIx/AlTCv//YoT7ZzwIxAMSNlPzcU9LcnXgWHxUzI1NS41oxXZ3K
-rr0TKUQNJ1uo52icEvdYPy5yAlejj6EULg==
------END CERTIFICATE-----
-
-thawte Primary Root CA - G3
-===========================
------BEGIN CERTIFICATE-----
-MIIEKjCCAxKgAwIBAgIQYAGXt0an6rS0mtZLL/eQ+zANBgkqhkiG9w0BAQsFADCBrjELMAkGA1UE
-BhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2
-aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMvKGMpIDIwMDggdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhv
-cml6ZWQgdXNlIG9ubHkxJDAiBgNVBAMTG3RoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EgLSBHMzAeFw0w
-ODA0MDIwMDAwMDBaFw0zNzEyMDEyMzU5NTlaMIGuMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMdGhh
-d3RlLCBJbmMuMSgwJgYDVQQLEx9DZXJ0aWZpY2F0aW9uIFNlcnZpY2VzIERpdmlzaW9uMTgwNgYD
-VQQLEy8oYykgMjAwOCB0aGF3dGUsIEluYy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25seTEkMCIG
-A1UEAxMbdGhhd3RlIFByaW1hcnkgUm9vdCBDQSAtIEczMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A
-MIIBCgKCAQEAsr8nLPvb2FvdeHsbnndmgcs+vHyu86YnmjSjaDFxODNi5PNxZnmxqWWjpYvVj2At
-P0LMqmsywCPLLEHd5N/8YZzic7IilRFDGF/Eth9XbAoFWCLINkw6fKXRz4aviKdEAhN0cXMKQlkC
-+BsUa0Lfb1+6a4KinVvnSr0eAXLbS3ToO39/fR8EtCab4LRarEc9VbjXsCZSKAExQGbY2SS99irY
-7CFJXJv2eul/VTV+lmuNk5Mny5K76qxAwJ/C+IDPXfRa3M50hqY+bAtTyr2SzhkGcuYMXDhpxwTW
-vGzOW/b3aJzcJRVIiKHpqfiYnODz1TEoYRFsZ5aNOZnLwkUkOQIDAQABo0IwQDAPBgNVHRMBAf8E
-BTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUrWyqlGCc7eT/+j4KdCtjA/e2Wb8wDQYJ
-KoZIhvcNAQELBQADggEBABpA2JVlrAmSicY59BDlqQ5mU1143vokkbvnRFHfxhY0Cu9qRFHqKweK
-A3rD6z8KLFIWoCtDuSWQP3CpMyVtRRooOyfPqsMpQhvfO0zAMzRbQYi/aytlryjvsvXDqmbOe1bu
-t8jLZ8HJnBoYuMTDSQPxYA5QzUbF83d597YV4Djbxy8ooAw/dyZ02SUS2jHaGh7cKUGRIjxpp7sC
-8rZcJwOJ9Abqm+RyguOhCcHpABnTPtRwa7pxpqpYrvS76Wy274fMm7v/OeZWYdMKp8RcTGB7BXcm
-er/YB1IsYvdwY9k5vG8cwnncdimvzsUsZAReiDZuMdRAGmI0Nj81Aa6sY6A=
------END CERTIFICATE-----
-
-GeoTrust Primary Certification Authority - G2
-=============================================
------BEGIN CERTIFICATE-----
-MIICrjCCAjWgAwIBAgIQPLL0SAoA4v7rJDteYD7DazAKBggqhkjOPQQDAzCBmDELMAkGA1UEBhMC
-VVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4xOTA3BgNVBAsTMChjKSAyMDA3IEdlb1RydXN0IElu
-Yy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25seTE2MDQGA1UEAxMtR2VvVHJ1c3QgUHJpbWFyeSBD
-ZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEcyMB4XDTA3MTEwNTAwMDAwMFoXDTM4MDExODIzNTk1
-OVowgZgxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTkwNwYDVQQLEzAoYykg
-MjAwNyBHZW9UcnVzdCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxNjA0BgNVBAMTLUdl
-b1RydXN0IFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHMjB2MBAGByqGSM49AgEG
-BSuBBAAiA2IABBWx6P0DFUPlrOuHNxFi79KDNlJ9RVcLSo17VDs6bl8VAsBQps8lL33KSLjHUGMc
-KiEIfJo22Av+0SbFWDEwKCXzXV2juLaltJLtbCyf691DiaI8S0iRHVDsJt/WYC69IaNCMEAwDwYD
-VR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFBVfNVdRVfslsq0DafwBo/q+
-EVXVMAoGCCqGSM49BAMDA2cAMGQCMGSWWaboCd6LuvpaiIjwH5HTRqjySkwCY/tsXzjbLkGTqQ7m
-ndwxHLKgpxgceeHHNgIwOlavmnRs9vuD4DPTCF+hnMJbn0bWtsuRBmOiBuczrD6ogRLQy7rQkgu2
-npaqBA+K
------END CERTIFICATE-----
-
-VeriSign Universal Root Certification Authority
-===============================================
------BEGIN CERTIFICATE-----
-MIIEuTCCA6GgAwIBAgIQQBrEZCGzEyEDDrvkEhrFHTANBgkqhkiG9w0BAQsFADCBvTELMAkGA1UE
-BhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBO
-ZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwOCBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVk
-IHVzZSBvbmx5MTgwNgYDVQQDEy9WZXJpU2lnbiBVbml2ZXJzYWwgUm9vdCBDZXJ0aWZpY2F0aW9u
-IEF1dGhvcml0eTAeFw0wODA0MDIwMDAwMDBaFw0zNzEyMDEyMzU5NTlaMIG9MQswCQYDVQQGEwJV
-UzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdv
-cmsxOjA4BgNVBAsTMShjKSAyMDA4IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl
-IG9ubHkxODA2BgNVBAMTL1ZlcmlTaWduIFVuaXZlcnNhbCBSb290IENlcnRpZmljYXRpb24gQXV0
-aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx2E3XrEBNNti1xWb/1hajCMj
-1mCOkdeQmIN65lgZOIzF9uVkhbSicfvtvbnazU0AtMgtc6XHaXGVHzk8skQHnOgO+k1KxCHfKWGP
-MiJhgsWHH26MfF8WIFFE0XBPV+rjHOPMee5Y2A7Cs0WTwCznmhcrewA3ekEzeOEz4vMQGn+HLL72
-9fdC4uW/h2KJXwBL38Xd5HVEMkE6HnFuacsLdUYI0crSK5XQz/u5QGtkjFdN/BMReYTtXlT2NJ8I
-AfMQJQYXStrxHXpma5hgZqTZ79IugvHw7wnqRMkVauIDbjPTrJ9VAMf2CGqUuV/c4DPxhGD5WycR
-tPwW8rtWaoAljQIDAQABo4GyMIGvMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMG0G
-CCsGAQUFBwEMBGEwX6FdoFswWTBXMFUWCWltYWdlL2dpZjAhMB8wBwYFKw4DAhoEFI/l0xqGrI2O
-a8PPgGrUSBgsexkuMCUWI2h0dHA6Ly9sb2dvLnZlcmlzaWduLmNvbS92c2xvZ28uZ2lmMB0GA1Ud
-DgQWBBS2d/ppSEefUxLVwuoHMnYH0ZcHGTANBgkqhkiG9w0BAQsFAAOCAQEASvj4sAPmLGd75JR3
-Y8xuTPl9Dg3cyLk1uXBPY/ok+myDjEedO2Pzmvl2MpWRsXe8rJq+seQxIcaBlVZaDrHC1LGmWazx
-Y8u4TB1ZkErvkBYoH1quEPuBUDgMbMzxPcP1Y+Oz4yHJJDnp/RVmRvQbEdBNc6N9Rvk97ahfYtTx
-P/jgdFcrGJ2BtMQo2pSXpXDrrB2+BxHw1dvd5Yzw1TKwg+ZX4o+/vqGqvz0dtdQ46tewXDpPaj+P
-wGZsY6rp2aQW9IHRlRQOfc2VNNnSj3BzgXucfr2YYdhFh5iQxeuGMMY1v/D/w1WIg0vvBZIGcfK4
-mJO37M2CYfE45k+XmCpajQ==
------END CERTIFICATE-----
-
-VeriSign Class 3 Public Primary Certification Authority - G4
-============================================================
------BEGIN CERTIFICATE-----
-MIIDhDCCAwqgAwIBAgIQL4D+I4wOIg9IZxIokYesszAKBggqhkjOPQQDAzCByjELMAkGA1UEBhMC
-VVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBOZXR3
-b3JrMTowOAYDVQQLEzEoYykgMjAwNyBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVz
-ZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmlj
-YXRpb24gQXV0aG9yaXR5IC0gRzQwHhcNMDcxMTA1MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCByjEL
-MAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBU
-cnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNyBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRo
-b3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5
-IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzQwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAASnVnp8
-Utpkmw4tXNherJI9/gHmGUo9FANL+mAnINmDiWn6VMaaGF5VKmTeBvaNSjutEDxlPZCIBIngMGGz
-rl0Bp3vefLK+ymVhAIau2o970ImtTR1ZmkGxvEeA3J5iw/mjgbIwga8wDwYDVR0TAQH/BAUwAwEB
-/zAOBgNVHQ8BAf8EBAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2UvZ2lmMCEw
-HzAHBgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDovL2xvZ28udmVyaXNpZ24u
-Y29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFLMWkf3upm7ktS5Jj4d4gYDs5bG1MAoGCCqGSM49BAMD
-A2gAMGUCMGYhDBgmYFo4e1ZC4Kf8NoRRkSAsdk1DPcQdhCPQrNZ8NQbOzWm9kA3bbEhCHQ6qQgIx
-AJw9SDkjOVgaFRJZap7v1VmyHVIsmXHNxynfGyphe3HR3vPA5Q06Sqotp9iGKt0uEA==
------END CERTIFICATE-----
-
-NetLock Arany (Class Gold) Főtanúsítvány
-============================================
------BEGIN CERTIFICATE-----
-MIIEFTCCAv2gAwIBAgIGSUEs5AAQMA0GCSqGSIb3DQEBCwUAMIGnMQswCQYDVQQGEwJIVTERMA8G
-A1UEBwwIQnVkYXBlc3QxFTATBgNVBAoMDE5ldExvY2sgS2Z0LjE3MDUGA1UECwwuVGFuw7pzw610
-dsOhbnlraWFkw7NrIChDZXJ0aWZpY2F0aW9uIFNlcnZpY2VzKTE1MDMGA1UEAwwsTmV0TG9jayBB
-cmFueSAoQ2xhc3MgR29sZCkgRsWRdGFuw7pzw610dsOhbnkwHhcNMDgxMjExMTUwODIxWhcNMjgx
-MjA2MTUwODIxWjCBpzELMAkGA1UEBhMCSFUxETAPBgNVBAcMCEJ1ZGFwZXN0MRUwEwYDVQQKDAxO
-ZXRMb2NrIEtmdC4xNzA1BgNVBAsMLlRhbsO6c8OtdHbDoW55a2lhZMOzayAoQ2VydGlmaWNhdGlv
-biBTZXJ2aWNlcykxNTAzBgNVBAMMLE5ldExvY2sgQXJhbnkgKENsYXNzIEdvbGQpIEbFkXRhbsO6
-c8OtdHbDoW55MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxCRec75LbRTDofTjl5Bu
-0jBFHjzuZ9lk4BqKf8owyoPjIMHj9DrTlF8afFttvzBPhCf2nx9JvMaZCpDyD/V/Q4Q3Y1GLeqVw
-/HpYzY6b7cNGbIRwXdrzAZAj/E4wqX7hJ2Pn7WQ8oLjJM2P+FpD/sLj916jAwJRDC7bVWaaeVtAk
-H3B5r9s5VA1lddkVQZQBr17s9o3x/61k/iCa11zr/qYfCGSji3ZVrR47KGAuhyXoqq8fxmRGILdw
-fzzeSNuWU7c5d+Qa4scWhHaXWy+7GRWF+GmF9ZmnqfI0p6m2pgP8b4Y9VHx2BJtr+UBdADTHLpl1
-neWIA6pN+APSQnbAGwIDAKiLo0UwQzASBgNVHRMBAf8ECDAGAQH/AgEEMA4GA1UdDwEB/wQEAwIB
-BjAdBgNVHQ4EFgQUzPpnk/C2uNClwB7zU/2MU9+D15YwDQYJKoZIhvcNAQELBQADggEBAKt/7hwW
-qZw8UQCgwBEIBaeZ5m8BiFRhbvG5GK1Krf6BQCOUL/t1fC8oS2IkgYIL9WHxHG64YTjrgfpioTta
-YtOUZcTh5m2C+C8lcLIhJsFyUR+MLMOEkMNaj7rP9KdlpeuY0fsFskZ1FSNqb4VjMIDw1Z4fKRzC
-bLBQWV2QWzuoDTDPv31/zvGdg73JRm4gpvlhUbohL3u+pRVjodSVh/GeufOJ8z2FuLjbvrW5Kfna
-NwUASZQDhETnv0Mxz3WLJdH0pmT1kvarBes96aULNmLazAZfNou2XjG4Kvte9nHfRCaexOYNkbQu
-dZWAUWpLMKawYqGT8ZvYzsRjdT9ZR7E=
------END CERTIFICATE-----
-
-Staat der Nederlanden Root CA - G2
-==================================
------BEGIN CERTIFICATE-----
-MIIFyjCCA7KgAwIBAgIEAJiWjDANBgkqhkiG9w0BAQsFADBaMQswCQYDVQQGEwJOTDEeMBwGA1UE
-CgwVU3RhYXQgZGVyIE5lZGVybGFuZGVuMSswKQYDVQQDDCJTdGFhdCBkZXIgTmVkZXJsYW5kZW4g
-Um9vdCBDQSAtIEcyMB4XDTA4MDMyNjExMTgxN1oXDTIwMDMyNTExMDMxMFowWjELMAkGA1UEBhMC
-TkwxHjAcBgNVBAoMFVN0YWF0IGRlciBOZWRlcmxhbmRlbjErMCkGA1UEAwwiU3RhYXQgZGVyIE5l
-ZGVybGFuZGVuIFJvb3QgQ0EgLSBHMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMVZ
-5291qj5LnLW4rJ4L5PnZyqtdj7U5EILXr1HgO+EASGrP2uEGQxGZqhQlEq0i6ABtQ8SpuOUfiUtn
-vWFI7/3S4GCI5bkYYCjDdyutsDeqN95kWSpGV+RLufg3fNU254DBtvPUZ5uW6M7XxgpT0GtJlvOj
-CwV3SPcl5XCsMBQgJeN/dVrlSPhOewMHBPqCYYdu8DvEpMfQ9XQ+pV0aCPKbJdL2rAQmPlU6Yiil
-e7Iwr/g3wtG61jj99O9JMDeZJiFIhQGp5Rbn3JBV3w/oOM2ZNyFPXfUib2rFEhZgF1XyZWampzCR
-OME4HYYEhLoaJXhena/MUGDWE4dS7WMfbWV9whUYdMrhfmQpjHLYFhN9C0lK8SgbIHRrxT3dsKpI
-CT0ugpTNGmXZK4iambwYfp/ufWZ8Pr2UuIHOzZgweMFvZ9C+X+Bo7d7iscksWXiSqt8rYGPy5V65
-48r6f1CGPqI0GAwJaCgRHOThuVw+R7oyPxjMW4T182t0xHJ04eOLoEq9jWYv6q012iDTiIJh8BIi
-trzQ1aTsr1SIJSQ8p22xcik/Plemf1WvbibG/ufMQFxRRIEKeN5KzlW/HdXZt1bv8Hb/C3m1r737
-qWmRRpdogBQ2HbN/uymYNqUg+oJgYjOk7Na6B6duxc8UpufWkjTYgfX8HV2qXB72o007uPc5AgMB
-AAGjgZcwgZQwDwYDVR0TAQH/BAUwAwEB/zBSBgNVHSAESzBJMEcGBFUdIAAwPzA9BggrBgEFBQcC
-ARYxaHR0cDovL3d3dy5wa2lvdmVyaGVpZC5ubC9wb2xpY2llcy9yb290LXBvbGljeS1HMjAOBgNV
-HQ8BAf8EBAMCAQYwHQYDVR0OBBYEFJFoMocVHYnitfGsNig0jQt8YojrMA0GCSqGSIb3DQEBCwUA
-A4ICAQCoQUpnKpKBglBu4dfYszk78wIVCVBR7y29JHuIhjv5tLySCZa59sCrI2AGeYwRTlHSeYAz
-+51IvuxBQ4EffkdAHOV6CMqqi3WtFMTC6GY8ggen5ieCWxjmD27ZUD6KQhgpxrRW/FYQoAUXvQwj
-f/ST7ZwaUb7dRUG/kSS0H4zpX897IZmflZ85OkYcbPnNe5yQzSipx6lVu6xiNGI1E0sUOlWDuYaN
-kqbG9AclVMwWVxJKgnjIFNkXgiYtXSAfea7+1HAWFpWD2DU5/1JddRwWxRNVz0fMdWVSSt7wsKfk
-CpYL+63C4iWEst3kvX5ZbJvw8NjnyvLplzh+ib7M+zkXYT9y2zqR2GUBGR2tUKRXCnxLvJxxcypF
-URmFzI79R6d0lR2o0a9OF7FpJsKqeFdbxU2n5Z4FF5TKsl+gSRiNNOkmbEgeqmiSBeGCc1qb3Adb
-CG19ndeNIdn8FCCqwkXfP+cAslHkwvgFuXkajDTznlvkN1trSt8sV4pAWja63XVECDdCcAz+3F4h
-oKOKwJCcaNpQ5kUQR3i2TtJlycM33+FCY7BXN0Ute4qcvwXqZVUz9zkQxSgqIXobisQk+T8VyJoV
-IPVVYpbtbZNQvOSqeK3Zywplh6ZmwcSBo3c6WB4L7oOLnR7SUqTMHW+wmG2UMbX4cQrcufx9MmDm
-66+KAQ==
------END CERTIFICATE-----
-
-CA Disig
-========
------BEGIN CERTIFICATE-----
-MIIEDzCCAvegAwIBAgIBATANBgkqhkiG9w0BAQUFADBKMQswCQYDVQQGEwJTSzETMBEGA1UEBxMK
-QnJhdGlzbGF2YTETMBEGA1UEChMKRGlzaWcgYS5zLjERMA8GA1UEAxMIQ0EgRGlzaWcwHhcNMDYw
-MzIyMDEzOTM0WhcNMTYwMzIyMDEzOTM0WjBKMQswCQYDVQQGEwJTSzETMBEGA1UEBxMKQnJhdGlz
-bGF2YTETMBEGA1UEChMKRGlzaWcgYS5zLjERMA8GA1UEAxMIQ0EgRGlzaWcwggEiMA0GCSqGSIb3
-DQEBAQUAA4IBDwAwggEKAoIBAQCS9jHBfYj9mQGp2HvycXXxMcbzdWb6UShGhJd4NLxs/LxFWYgm
-GErENx+hSkS943EE9UQX4j/8SFhvXJ56CbpRNyIjZkMhsDxkovhqFQ4/61HhVKndBpnXmjxUizkD
-Pw/Fzsbrg3ICqB9x8y34dQjbYkzo+s7552oftms1grrijxaSfQUMbEYDXcDtab86wYqg6I7ZuUUo
-hwjstMoVvoLdtUSLLa2GDGhibYVW8qwUYzrG0ZmsNHhWS8+2rT+MitcE5eN4TPWGqvWP+j1scaMt
-ymfraHtuM6kMgiioTGohQBUgDCZbg8KpFhXAJIJdKxatymP2dACw30PEEGBWZ2NFAgMBAAGjgf8w
-gfwwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUjbJJaJ1yCCW5wCf1UJNWSEZx+Y8wDgYDVR0P
-AQH/BAQDAgEGMDYGA1UdEQQvMC2BE2Nhb3BlcmF0b3JAZGlzaWcuc2uGFmh0dHA6Ly93d3cuZGlz
-aWcuc2svY2EwZgYDVR0fBF8wXTAtoCugKYYnaHR0cDovL3d3dy5kaXNpZy5zay9jYS9jcmwvY2Ff
-ZGlzaWcuY3JsMCygKqAohiZodHRwOi8vY2EuZGlzaWcuc2svY2EvY3JsL2NhX2Rpc2lnLmNybDAa
-BgNVHSAEEzARMA8GDSuBHpGT5goAAAABAQEwDQYJKoZIhvcNAQEFBQADggEBAF00dGFMrzvY/59t
-WDYcPQuBDRIrRhCA/ec8J9B6yKm2fnQwM6M6int0wHl5QpNt/7EpFIKrIYwvF/k/Ji/1WcbvgAa3
-mkkp7M5+cTxqEEHA9tOasnxakZzArFvITV734VP/Q3f8nktnbNfzg9Gg4H8l37iYC5oyOGwwoPP/
-CBUz91BKez6jPiCp3C9WgArtQVCwyfTssuMmRAAOb54GvCKWU3BlxFAKRmukLyeBEicTXxChds6K
-ezfqwzlhA5WYOudsiCUI/HloDYd9Yvi0X/vF2Ey9WLw/Q1vUHgFNPGO+I++MzVpQuGhU+QqZMxEA
-4Z7CRneC9VkGjCFMhwnN5ag=
------END CERTIFICATE-----
-
-Juur-SK
-=======
------BEGIN CERTIFICATE-----
-MIIE5jCCA86gAwIBAgIEO45L/DANBgkqhkiG9w0BAQUFADBdMRgwFgYJKoZIhvcNAQkBFglwa2lA
-c2suZWUxCzAJBgNVBAYTAkVFMSIwIAYDVQQKExlBUyBTZXJ0aWZpdHNlZXJpbWlza2Vza3VzMRAw
-DgYDVQQDEwdKdXVyLVNLMB4XDTAxMDgzMDE0MjMwMVoXDTE2MDgyNjE0MjMwMVowXTEYMBYGCSqG
-SIb3DQEJARYJcGtpQHNrLmVlMQswCQYDVQQGEwJFRTEiMCAGA1UEChMZQVMgU2VydGlmaXRzZWVy
-aW1pc2tlc2t1czEQMA4GA1UEAxMHSnV1ci1TSzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
-ggEBAIFxNj4zB9bjMI0TfncyRsvPGbJgMUaXhvSYRqTCZUXP00B841oiqBB4M8yIsdOBSvZiF3tf
-TQou0M+LI+5PAk676w7KvRhj6IAcjeEcjT3g/1tf6mTll+g/mX8MCgkzABpTpyHhOEvWgxutr2TC
-+Rx6jGZITWYfGAriPrsfB2WThbkasLnE+w0R9vXW+RvHLCu3GFH+4Hv2qEivbDtPL+/40UceJlfw
-UR0zlv/vWT3aTdEVNMfqPxZIe5EcgEMPPbgFPtGzlc3Yyg/CQ2fbt5PgIoIuvvVoKIO5wTtpeyDa
-Tpxt4brNj3pssAki14sL2xzVWiZbDcDq5WDQn/413z8CAwEAAaOCAawwggGoMA8GA1UdEwEB/wQF
-MAMBAf8wggEWBgNVHSAEggENMIIBCTCCAQUGCisGAQQBzh8BAQEwgfYwgdAGCCsGAQUFBwICMIHD
-HoHAAFMAZQBlACAAcwBlAHIAdABpAGYAaQBrAGEAYQB0ACAAbwBuACAAdgDkAGwAagBhAHMAdABh
-AHQAdQBkACAAQQBTAC0AaQBzACAAUwBlAHIAdABpAGYAaQB0AHMAZQBlAHIAaQBtAGkAcwBrAGUA
-cwBrAHUAcwAgAGEAbABhAG0ALQBTAEsAIABzAGUAcgB0AGkAZgBpAGsAYQBhAHQAaQBkAGUAIABr
-AGkAbgBuAGkAdABhAG0AaQBzAGUAawBzMCEGCCsGAQUFBwIBFhVodHRwOi8vd3d3LnNrLmVlL2Nw
-cy8wKwYDVR0fBCQwIjAgoB6gHIYaaHR0cDovL3d3dy5zay5lZS9qdXVyL2NybC8wHQYDVR0OBBYE
-FASqekej5ImvGs8KQKcYP2/v6X2+MB8GA1UdIwQYMBaAFASqekej5ImvGs8KQKcYP2/v6X2+MA4G
-A1UdDwEB/wQEAwIB5jANBgkqhkiG9w0BAQUFAAOCAQEAe8EYlFOiCfP+JmeaUOTDBS8rNXiRTHyo
-ERF5TElZrMj3hWVcRrs7EKACr81Ptcw2Kuxd/u+gkcm2k298gFTsxwhwDY77guwqYHhpNjbRxZyL
-abVAyJRld/JXIWY7zoVAtjNjGr95HvxcHdMdkxuLDF2FvZkwMhgJkVLpfKG6/2SSmuz+Ne6ML678
-IIbsSt4beDI3poHSna9aEhbKmVv8b20OxaAehsmR0FyYgl9jDIpaq9iVpszLita/ZEuOyoqysOkh
-Mp6qqIWYNIE5ITuoOlIyPfZrN4YGWhWY3PARZv40ILcD9EEQfTmEeZZyY7aWAuVrua0ZTbvGRNs2
-yyqcjg==
------END CERTIFICATE-----
-
-Hongkong Post Root CA 1
-=======================
------BEGIN CERTIFICATE-----
-MIIDMDCCAhigAwIBAgICA+gwDQYJKoZIhvcNAQEFBQAwRzELMAkGA1UEBhMCSEsxFjAUBgNVBAoT
-DUhvbmdrb25nIFBvc3QxIDAeBgNVBAMTF0hvbmdrb25nIFBvc3QgUm9vdCBDQSAxMB4XDTAzMDUx
-NTA1MTMxNFoXDTIzMDUxNTA0NTIyOVowRzELMAkGA1UEBhMCSEsxFjAUBgNVBAoTDUhvbmdrb25n
-IFBvc3QxIDAeBgNVBAMTF0hvbmdrb25nIFBvc3QgUm9vdCBDQSAxMIIBIjANBgkqhkiG9w0BAQEF
-AAOCAQ8AMIIBCgKCAQEArP84tulmAknjorThkPlAj3n54r15/gK97iSSHSL22oVyaf7XPwnU3ZG1
-ApzQjVrhVcNQhrkpJsLj2aDxaQMoIIBFIi1WpztUlVYiWR8o3x8gPW2iNr4joLFutbEnPzlTCeqr
-auh0ssJlXI6/fMN4hM2eFvz1Lk8gKgifd/PFHsSaUmYeSF7jEAaPIpjhZY4bXSNmO7ilMlHIhqqh
-qZ5/dpTCpmy3QfDVyAY45tQM4vM7TG1QjMSDJ8EThFk9nnV0ttgCXjqQesBCNnLsak3c78QA3xMY
-V18meMjWCnl3v/evt3a5pQuEF10Q6m/hq5URX208o1xNg1vysxmKgIsLhwIDAQABoyYwJDASBgNV
-HRMBAf8ECDAGAQH/AgEDMA4GA1UdDwEB/wQEAwIBxjANBgkqhkiG9w0BAQUFAAOCAQEADkbVPK7i
-h9legYsCmEEIjEy82tvuJxuC52pF7BaLT4Wg87JwvVqWuspube5Gi27nKi6Wsxkz67SfqLI37pio
-l7Yutmcn1KZJ/RyTZXaeQi/cImyaT/JaFTmxcdcrUehtHJjA2Sr0oYJ71clBoiMBdDhViw+5Lmei
-IAQ32pwL0xch4I+XeTRvhEgCIDMb5jREn5Fw9IBehEPCKdJsEhTkYY2sEJCehFC78JZvRZ+K88ps
-T/oROhUVRsPNH4NbLUES7VBnQRM9IauUiqpOfMGx+6fWtScvl6tu4B3i0RwsH0Ti/L6RoZz71ilT
-c4afU9hDDl3WY4JxHYB0yvbiAmvZWg==
------END CERTIFICATE-----
-
-SecureSign RootCA11
-===================
------BEGIN CERTIFICATE-----
-MIIDbTCCAlWgAwIBAgIBATANBgkqhkiG9w0BAQUFADBYMQswCQYDVQQGEwJKUDErMCkGA1UEChMi
-SmFwYW4gQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcywgSW5jLjEcMBoGA1UEAxMTU2VjdXJlU2lnbiBS
-b290Q0ExMTAeFw0wOTA0MDgwNDU2NDdaFw0yOTA0MDgwNDU2NDdaMFgxCzAJBgNVBAYTAkpQMSsw
-KQYDVQQKEyJKYXBhbiBDZXJ0aWZpY2F0aW9uIFNlcnZpY2VzLCBJbmMuMRwwGgYDVQQDExNTZWN1
-cmVTaWduIFJvb3RDQTExMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA/XeqpRyQBTvL
-TJszi1oURaTnkBbR31fSIRCkF/3frNYfp+TbfPfs37gD2pRY/V1yfIw/XwFndBWW4wI8h9uuywGO
-wvNmxoVF9ALGOrVisq/6nL+k5tSAMJjzDbaTj6nU2DbysPyKyiyhFTOVMdrAG/LuYpmGYz+/3ZMq
-g6h2uRMft85OQoWPIucuGvKVCbIFtUROd6EgvanyTgp9UK31BQ1FT0Zx/Sg+U/sE2C3XZR1KG/rP
-O7AxmjVuyIsG0wCR8pQIZUyxNAYAeoni8McDWc/V1uinMrPmmECGxc0nEovMe863ETxiYAcjPitA
-bpSACW22s293bzUIUPsCh8U+iQIDAQABo0IwQDAdBgNVHQ4EFgQUW/hNT7KlhtQ60vFjmqC+CfZX
-t94wDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAKCh
-OBZmLqdWHyGcBvod7bkixTgm2E5P7KN/ed5GIaGHd48HCJqypMWvDzKYC3xmKbabfSVSSUOrTC4r
-bnpwrxYO4wJs+0LmGJ1F2FXI6Dvd5+H0LgscNFxsWEr7jIhQX5Ucv+2rIrVls4W6ng+4reV6G4pQ
-Oh29Dbx7VFALuUKvVaAYga1lme++5Jy/xIWrQbJUb9wlze144o4MjQlJ3WN7WmmWAiGovVJZ6X01
-y8hSyn+B/tlr0/cR7SXf+Of5pPpyl4RTDaXQMhhRdlkUbA/r7F+AjHVDg8OFmP9Mni0N5HeDk061
-lgeLKBObjBmNQSdJQO7e5iNEOdyhIta6A/I=
------END CERTIFICATE-----
-
-ACEDICOM Root
-=============
------BEGIN CERTIFICATE-----
-MIIFtTCCA52gAwIBAgIIYY3HhjsBggUwDQYJKoZIhvcNAQEFBQAwRDEWMBQGA1UEAwwNQUNFRElD
-T00gUm9vdDEMMAoGA1UECwwDUEtJMQ8wDQYDVQQKDAZFRElDT00xCzAJBgNVBAYTAkVTMB4XDTA4
-MDQxODE2MjQyMloXDTI4MDQxMzE2MjQyMlowRDEWMBQGA1UEAwwNQUNFRElDT00gUm9vdDEMMAoG
-A1UECwwDUEtJMQ8wDQYDVQQKDAZFRElDT00xCzAJBgNVBAYTAkVTMIICIjANBgkqhkiG9w0BAQEF
-AAOCAg8AMIICCgKCAgEA/5KV4WgGdrQsyFhIyv2AVClVYyT/kGWbEHV7w2rbYgIB8hiGtXxaOLHk
-WLn709gtn70yN78sFW2+tfQh0hOR2QetAQXW8713zl9CgQr5auODAKgrLlUTY4HKRxx7XBZXehuD
-YAQ6PmXDzQHe3qTWDLqO3tkE7hdWIpuPY/1NFgu3e3eM+SW10W2ZEi5PGrjm6gSSrj0RuVFCPYew
-MYWveVqc/udOXpJPQ/yrOq2lEiZmueIM15jO1FillUAKt0SdE3QrwqXrIhWYENiLxQSfHY9g5QYb
-m8+5eaA9oiM/Qj9r+hwDezCNzmzAv+YbX79nuIQZ1RXve8uQNjFiybwCq0Zfm/4aaJQ0PZCOrfbk
-HQl/Sog4P75n/TSW9R28MHTLOO7VbKvU/PQAtwBbhTIWdjPp2KOZnQUAqhbm84F9b32qhm2tFXTT
-xKJxqvQUfecyuB+81fFOvW8XAjnXDpVCOscAPukmYxHqC9FK/xidstd7LzrZlvvoHpKuE1XI2Sf2
-3EgbsCTBheN3nZqk8wwRHQ3ItBTutYJXCb8gWH8vIiPYcMt5bMlL8qkqyPyHK9caUPgn6C9D4zq9
-2Fdx/c6mUlv53U3t5fZvie27k5x2IXXwkkwp9y+cAS7+UEaeZAwUswdbxcJzbPEHXEUkFDWug/Fq
-TYl6+rPYLWbwNof1K1MCAwEAAaOBqjCBpzAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFKaz
-4SsrSbbXc6GqlPUB53NlTKxQMA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUprPhKytJttdzoaqU
-9QHnc2VMrFAwRAYDVR0gBD0wOzA5BgRVHSAAMDEwLwYIKwYBBQUHAgEWI2h0dHA6Ly9hY2VkaWNv
-bS5lZGljb21ncm91cC5jb20vZG9jMA0GCSqGSIb3DQEBBQUAA4ICAQDOLAtSUWImfQwng4/F9tqg
-aHtPkl7qpHMyEVNEskTLnewPeUKzEKbHDZ3Ltvo/Onzqv4hTGzz3gvoFNTPhNahXwOf9jU8/kzJP
-eGYDdwdY6ZXIfj7QeQCM8htRM5u8lOk6e25SLTKeI6RF+7YuE7CLGLHdztUdp0J/Vb77W7tH1Pwk
-zQSulgUV1qzOMPPKC8W64iLgpq0i5ALudBF/TP94HTXa5gI06xgSYXcGCRZj6hitoocf8seACQl1
-ThCojz2GuHURwCRiipZ7SkXp7FnFvmuD5uHorLUwHv4FB4D54SMNUI8FmP8sX+g7tq3PgbUhh8oI
-KiMnMCArz+2UW6yyetLHKKGKC5tNSixthT8Jcjxn4tncB7rrZXtaAWPWkFtPF2Y9fwsZo5NjEFIq
-nxQWWOLcpfShFosOkYuByptZ+thrkQdlVV9SH686+5DdaaVbnG0OLLb6zqylfDJKZ0DcMDQj3dcE
-I2bw/FWAp/tmGYI1Z2JwOV5vx+qQQEQIHriy1tvuWacNGHk0vFQYXlPKNFHtRQrmjseCNj6nOGOp
-MCwXEGCSn1WHElkQwg9naRHMTh5+Spqtr0CodaxWkHS4oJyleW/c6RrIaQXpuvoDs3zk4E7Czp3o
-tkYNbn5XOmeUwssfnHdKZ05phkOTOPu220+DkdRgfks+KzgHVZhepA==
------END CERTIFICATE-----
-
-Verisign Class 3 Public Primary Certification Authority
-=======================================================
------BEGIN CERTIFICATE-----
-MIICPDCCAaUCEDyRMcsf9tAbDpq40ES/Er4wDQYJKoZIhvcNAQEFBQAwXzELMAkGA1UEBhMCVVMx
-FzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFzcyAzIFB1YmxpYyBQcmltYXJ5
-IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTk2MDEyOTAwMDAwMFoXDTI4MDgwMjIzNTk1OVow
-XzELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMTcwNQYDVQQLEy5DbGFzcyAz
-IFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIGfMA0GCSqGSIb3DQEBAQUA
-A4GNADCBiQKBgQDJXFme8huKARS0EN8EQNvjV69qRUCPhAwL0TPZ2RHP7gJYHyX3KqhEBarsAx94
-f56TuZoAqiN91qyFomNFx3InzPRMxnVx0jnvT0Lwdd8KkMaOIG+YD/isI19wKTakyYbnsZogy1Ol
-hec9vn2a/iRFM9x2Fe0PonFkTGUugWhFpwIDAQABMA0GCSqGSIb3DQEBBQUAA4GBABByUqkFFBky
-CEHwxWsKzH4PIRnN5GfcX6kb5sroc50i2JhucwNhkcV8sEVAbkSdjbCxlnRhLQ2pRdKkkirWmnWX
-bj9T/UWZYB2oK0z5XqcJ2HUw19JlYD1n1khVdWk/kfVIC0dpImmClr7JyDiGSnoscxlIaU5rfGW/
-D/xwzoiQ
------END CERTIFICATE-----
-
-Microsec e-Szigno Root CA 2009
-==============================
------BEGIN CERTIFICATE-----
-MIIECjCCAvKgAwIBAgIJAMJ+QwRORz8ZMA0GCSqGSIb3DQEBCwUAMIGCMQswCQYDVQQGEwJIVTER
-MA8GA1UEBwwIQnVkYXBlc3QxFjAUBgNVBAoMDU1pY3Jvc2VjIEx0ZC4xJzAlBgNVBAMMHk1pY3Jv
-c2VjIGUtU3ppZ25vIFJvb3QgQ0EgMjAwOTEfMB0GCSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5o
-dTAeFw0wOTA2MTYxMTMwMThaFw0yOTEyMzAxMTMwMThaMIGCMQswCQYDVQQGEwJIVTERMA8GA1UE
-BwwIQnVkYXBlc3QxFjAUBgNVBAoMDU1pY3Jvc2VjIEx0ZC4xJzAlBgNVBAMMHk1pY3Jvc2VjIGUt
-U3ppZ25vIFJvb3QgQ0EgMjAwOTEfMB0GCSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5odTCCASIw
-DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOn4j/NjrdqG2KfgQvvPkd6mJviZpWNwrZuuyjNA
-fW2WbqEORO7hE52UQlKavXWFdCyoDh2Tthi3jCyoz/tccbna7P7ofo/kLx2yqHWH2Leh5TvPmUpG
-0IMZfcChEhyVbUr02MelTTMuhTlAdX4UfIASmFDHQWe4oIBhVKZsTh/gnQ4H6cm6M+f+wFUoLAKA
-pxn1ntxVUwOXewdI/5n7N4okxFnMUBBjjqqpGrCEGob5X7uxUG6k0QrM1XF+H6cbfPVTbiJfyyvm
-1HxdrtbCxkzlBQHZ7Vf8wSN5/PrIJIOV87VqUQHQd9bpEqH5GoP7ghu5sJf0dgYzQ0mg/wu1+rUC
-AwEAAaOBgDB+MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTLD8bf
-QkPMPcu1SCOhGnqmKrs0aDAfBgNVHSMEGDAWgBTLD8bfQkPMPcu1SCOhGnqmKrs0aDAbBgNVHREE
-FDASgRBpbmZvQGUtc3ppZ25vLmh1MA0GCSqGSIb3DQEBCwUAA4IBAQDJ0Q5eLtXMs3w+y/w9/w0o
-lZMEyL/azXm4Q5DwpL7v8u8hmLzU1F0G9u5C7DBsoKqpyvGvivo/C3NqPuouQH4frlRheesuCDfX
-I/OMn74dseGkddug4lQUsbocKaQY9hK6ohQU4zE1yED/t+AFdlfBHFny+L/k7SViXITwfn4fs775
-tyERzAMBVnCnEJIeGzSBHq2cGsMEPO0CYdYeBvNfOofyK/FFh+U9rNHHV4S9a67c2Pm2G2JwCz02
-yULyMtd6YebS2z3PyKnJm9zbWETXbzivf3jTo60adbocwTZ8jx5tHMN1Rq41Bab2XD0h7lbwyYIi
-LXpUq3DDfSJlgnCW
------END CERTIFICATE-----
-
-E-Guven Kok Elektronik Sertifika Hizmet Saglayicisi
-===================================================
------BEGIN CERTIFICATE-----
-MIIDtjCCAp6gAwIBAgIQRJmNPMADJ72cdpW56tustTANBgkqhkiG9w0BAQUFADB1MQswCQYDVQQG
-EwJUUjEoMCYGA1UEChMfRWxla3Ryb25payBCaWxnaSBHdXZlbmxpZ2kgQS5TLjE8MDoGA1UEAxMz
-ZS1HdXZlbiBLb2sgRWxla3Ryb25payBTZXJ0aWZpa2EgSGl6bWV0IFNhZ2xheWljaXNpMB4XDTA3
-MDEwNDExMzI0OFoXDTE3MDEwNDExMzI0OFowdTELMAkGA1UEBhMCVFIxKDAmBgNVBAoTH0VsZWt0
-cm9uaWsgQmlsZ2kgR3V2ZW5saWdpIEEuUy4xPDA6BgNVBAMTM2UtR3V2ZW4gS29rIEVsZWt0cm9u
-aWsgU2VydGlmaWthIEhpem1ldCBTYWdsYXlpY2lzaTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
-AQoCggEBAMMSIJ6wXgBljU5Gu4Bc6SwGl9XzcslwuedLZYDBS75+PNdUMZTe1RK6UxYC6lhj71vY
-8+0qGqpxSKPcEC1fX+tcS5yWCEIlKBHMilpiAVDV6wlTL/jDj/6z/P2douNffb7tC+Bg62nsM+3Y
-jfsSSYMAyYuXjDtzKjKzEve5TfL0TW3H5tYmNwjy2f1rXKPlSFxYvEK+A1qBuhw1DADT9SN+cTAI
-JjjcJRFHLfO6IxClv7wC90Nex/6wN1CZew+TzuZDLMN+DfIcQ2Zgy2ExR4ejT669VmxMvLz4Bcpk
-9Ok0oSy1c+HCPujIyTQlCFzz7abHlJ+tiEMl1+E5YP6sOVkCAwEAAaNCMEAwDgYDVR0PAQH/BAQD
-AgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFJ/uRLOU1fqRTy7ZVZoEVtstxNulMA0GCSqG
-SIb3DQEBBQUAA4IBAQB/X7lTW2M9dTLn+sR0GstG30ZpHFLPqk/CaOv/gKlR6D1id4k9CnU58W5d
-F4dvaAXBlGzZXd/aslnLpRCKysw5zZ/rTt5S/wzw9JKp8mxTq5vSR6AfdPebmvEvFZ96ZDAYBzwq
-D2fK/A+JYZ1lpTzlvBNbCNvj/+27BrtqBrF6T2XGgv0enIu1De5Iu7i9qgi0+6N8y5/NkHZchpZ4
-Vwpm+Vganf2XKWDeEaaQHBkc7gGWIjQ0LpH5t8Qn0Xvmv/uARFoW5evg1Ao4vOSR49XrXMGs3xtq
-fJ7lddK2l4fbzIcrQzqECK+rPNv3PGYxhrCdU3nt+CPeQuMtgvEP5fqX
------END CERTIFICATE-----
-
-GlobalSign Root CA - R3
-=======================
------BEGIN CERTIFICATE-----
-MIIDXzCCAkegAwIBAgILBAAAAAABIVhTCKIwDQYJKoZIhvcNAQELBQAwTDEgMB4GA1UECxMXR2xv
-YmFsU2lnbiBSb290IENBIC0gUjMxEzARBgNVBAoTCkdsb2JhbFNpZ24xEzARBgNVBAMTCkdsb2Jh
-bFNpZ24wHhcNMDkwMzE4MTAwMDAwWhcNMjkwMzE4MTAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxT
-aWduIFJvb3QgQ0EgLSBSMzETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2ln
-bjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMwldpB5BngiFvXAg7aEyiie/QV2EcWt
-iHL8RgJDx7KKnQRfJMsuS+FggkbhUqsMgUdwbN1k0ev1LKMPgj0MK66X17YUhhB5uzsTgHeMCOFJ
-0mpiLx9e+pZo34knlTifBtc+ycsmWQ1z3rDI6SYOgxXG71uL0gRgykmmKPZpO/bLyCiR5Z2KYVc3
-rHQU3HTgOu5yLy6c+9C7v/U9AOEGM+iCK65TpjoWc4zdQQ4gOsC0p6Hpsk+QLjJg6VfLuQSSaGjl
-OCZgdbKfd/+RFO+uIEn8rUAVSNECMWEZXriX7613t2Saer9fwRPvm2L7DWzgVGkWqQPabumDk3F2
-xmmFghcCAwEAAaNCMEAwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYE
-FI/wS3+oLkUkrk1Q+mOai97i3Ru8MA0GCSqGSIb3DQEBCwUAA4IBAQBLQNvAUKr+yAzv95ZURUm7
-lgAJQayzE4aGKAczymvmdLm6AC2upArT9fHxD4q/c2dKg8dEe3jgr25sbwMpjjM5RcOO5LlXbKr8
-EpbsU8Yt5CRsuZRj+9xTaGdWPoO4zzUhw8lo/s7awlOqzJCK6fBdRoyV3XpYKBovHd7NADdBj+1E
-bddTKJd+82cEHhXXipa0095MJ6RMG3NzdvQXmcIfeg7jLQitChws/zyrVQ4PkX4268NXSb7hLi18
-YIvDQVETI53O9zJrlAGomecsMx86OyXShkDOOyyGeMlhLxS67ttVb9+E7gUJTb0o2HLO02JQZR7r
-kpeDMdmztcpHWD9f
------END CERTIFICATE-----
-
-TC TrustCenter Universal CA III
-===============================
------BEGIN CERTIFICATE-----
-MIID4TCCAsmgAwIBAgIOYyUAAQACFI0zFQLkbPQwDQYJKoZIhvcNAQEFBQAwezELMAkGA1UEBhMC
-REUxHDAaBgNVBAoTE1RDIFRydXN0Q2VudGVyIEdtYkgxJDAiBgNVBAsTG1RDIFRydXN0Q2VudGVy
-IFVuaXZlcnNhbCBDQTEoMCYGA1UEAxMfVEMgVHJ1c3RDZW50ZXIgVW5pdmVyc2FsIENBIElJSTAe
-Fw0wOTA5MDkwODE1MjdaFw0yOTEyMzEyMzU5NTlaMHsxCzAJBgNVBAYTAkRFMRwwGgYDVQQKExNU
-QyBUcnVzdENlbnRlciBHbWJIMSQwIgYDVQQLExtUQyBUcnVzdENlbnRlciBVbml2ZXJzYWwgQ0Ex
-KDAmBgNVBAMTH1RDIFRydXN0Q2VudGVyIFVuaXZlcnNhbCBDQSBJSUkwggEiMA0GCSqGSIb3DQEB
-AQUAA4IBDwAwggEKAoIBAQDC2pxisLlxErALyBpXsq6DFJmzNEubkKLF5+cvAqBNLaT6hdqbJYUt
-QCggbergvbFIgyIpRJ9Og+41URNzdNW88jBmlFPAQDYvDIRlzg9uwliT6CwLOunBjvvya8o84pxO
-juT5fdMnnxvVZ3iHLX8LR7PH6MlIfK8vzArZQe+f/prhsq75U7Xl6UafYOPfjdN/+5Z+s7Vy+Eut
-CHnNaYlAJ/Uqwa1D7KRTyGG299J5KmcYdkhtWyUB0SbFt1dpIxVbYYqt8Bst2a9c8SaQaanVDED1
-M4BDj5yjdipFtK+/fz6HP3bFzSreIMUWWMv5G/UPyw0RUmS40nZid4PxWJ//AgMBAAGjYzBhMB8G
-A1UdIwQYMBaAFFbn4VslQ4Dg9ozhcbyO5YAvxEjiMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/
-BAQDAgEGMB0GA1UdDgQWBBRW5+FbJUOA4PaM4XG8juWAL8RI4jANBgkqhkiG9w0BAQUFAAOCAQEA
-g8ev6n9NCjw5sWi+e22JLumzCecYV42FmhfzdkJQEw/HkG8zrcVJYCtsSVgZ1OK+t7+rSbyUyKu+
-KGwWaODIl0YgoGhnYIg5IFHYaAERzqf2EQf27OysGh+yZm5WZ2B6dF7AbZc2rrUNXWZzwCUyRdhK
-BgePxLcHsU0GDeGl6/R1yrqc0L2z0zIkTO5+4nYES0lT2PLpVDP85XEfPRRclkvxOvIAu2y0+pZV
-CIgJwcyRGSmwIC3/yzikQOEXvnlhgP8HA4ZMTnsGnxGGjYnuJ8Tb4rwZjgvDwxPHLQNjO9Po5KIq
-woIIlBZU8O8fJ5AluA0OKBtHd0e9HKgl8ZS0Zg==
------END CERTIFICATE-----
-
-Autoridad de Certificacion Firmaprofesional CIF A62634068
-=========================================================
------BEGIN CERTIFICATE-----
-MIIGFDCCA/ygAwIBAgIIU+w77vuySF8wDQYJKoZIhvcNAQEFBQAwUTELMAkGA1UEBhMCRVMxQjBA
-BgNVBAMMOUF1dG9yaWRhZCBkZSBDZXJ0aWZpY2FjaW9uIEZpcm1hcHJvZmVzaW9uYWwgQ0lGIEE2
-MjYzNDA2ODAeFw0wOTA1MjAwODM4MTVaFw0zMDEyMzEwODM4MTVaMFExCzAJBgNVBAYTAkVTMUIw
-QAYDVQQDDDlBdXRvcmlkYWQgZGUgQ2VydGlmaWNhY2lvbiBGaXJtYXByb2Zlc2lvbmFsIENJRiBB
-NjI2MzQwNjgwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDKlmuO6vj78aI14H9M2uDD
-Utd9thDIAl6zQyrET2qyyhxdKJp4ERppWVevtSBC5IsP5t9bpgOSL/UR5GLXMnE42QQMcas9UX4P
-B99jBVzpv5RvwSmCwLTaUbDBPLutN0pcyvFLNg4kq7/DhHf9qFD0sefGL9ItWY16Ck6WaVICqjaY
-7Pz6FIMMNx/Jkjd/14Et5cS54D40/mf0PmbR0/RAz15iNA9wBj4gGFrO93IbJWyTdBSTo3OxDqqH
-ECNZXyAFGUftaI6SEspd/NYrspI8IM/hX68gvqB2f3bl7BqGYTM+53u0P6APjqK5am+5hyZvQWyI
-plD9amML9ZMWGxmPsu2bm8mQ9QEM3xk9Dz44I8kvjwzRAv4bVdZO0I08r0+k8/6vKtMFnXkIoctX
-MbScyJCyZ/QYFpM6/EfY0XiWMR+6KwxfXZmtY4laJCB22N/9q06mIqqdXuYnin1oKaPnirjaEbsX
-LZmdEyRG98Xi2J+Of8ePdG1asuhy9azuJBCtLxTa/y2aRnFHvkLfuwHb9H/TKI8xWVvTyQKmtFLK
-bpf7Q8UIJm+K9Lv9nyiqDdVF8xM6HdjAeI9BZzwelGSuewvF6NkBiDkal4ZkQdU7hwxu+g/GvUgU
-vzlN1J5Bto+WHWOWk9mVBngxaJ43BjuAiUVhOSPHG0SjFeUc+JIwuwIDAQABo4HvMIHsMBIGA1Ud
-EwEB/wQIMAYBAf8CAQEwDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBRlzeurNR4APn7VdMActHNH
-DhpkLzCBpgYDVR0gBIGeMIGbMIGYBgRVHSAAMIGPMC8GCCsGAQUFBwIBFiNodHRwOi8vd3d3LmZp
-cm1hcHJvZmVzaW9uYWwuY29tL2NwczBcBggrBgEFBQcCAjBQHk4AUABhAHMAZQBvACAAZABlACAA
-bABhACAAQgBvAG4AYQBuAG8AdgBhACAANAA3ACAAQgBhAHIAYwBlAGwAbwBuAGEAIAAwADgAMAAx
-ADcwDQYJKoZIhvcNAQEFBQADggIBABd9oPm03cXF661LJLWhAqvdpYhKsg9VSytXjDvlMd3+xDLx
-51tkljYyGOylMnfX40S2wBEqgLk9am58m9Ot/MPWo+ZkKXzR4Tgegiv/J2Wv+xYVxC5xhOW1//qk
-R71kMrv2JYSiJ0L1ILDCExARzRAVukKQKtJE4ZYm6zFIEv0q2skGz3QeqUvVhyj5eTSSPi5E6PaP
-T481PyWzOdxjKpBrIF/EUhJOlywqrJ2X3kjyo2bbwtKDlaZmp54lD+kLM5FlClrD2VQS3a/DTg4f
-Jl4N3LON7NWBcN7STyQF82xO9UxJZo3R/9ILJUFI/lGExkKvgATP0H5kSeTy36LssUzAKh3ntLFl
-osS88Zj0qnAHY7S42jtM+kAiMFsRpvAFDsYCA0irhpuF3dvd6qJ2gHN99ZwExEWN57kci57q13XR
-crHedUTnQn3iV2t93Jm8PYMo6oCTjcVMZcFwgbg4/EMxsvYDNEeyrPsiBsse3RdHHF9mudMaotoR
-saS8I8nkvof/uZS2+F0gStRf571oe2XyFR7SOqkt6dhrJKyXWERHrVkY8SFlcN7ONGCoQPHzPKTD
-KCOM/iczQ0CgFzzr6juwcqajuUpLXhZI9LK8yIySxZ2frHI2vDSANGupi5LAuBft7HZT9SQBjLMi
-6Et8Vcad+qMUu2WFbm5PEn4KPJ2V
------END CERTIFICATE-----
-
-Izenpe.com
-==========
------BEGIN CERTIFICATE-----
-MIIF8TCCA9mgAwIBAgIQALC3WhZIX7/hy/WL1xnmfTANBgkqhkiG9w0BAQsFADA4MQswCQYDVQQG
-EwJFUzEUMBIGA1UECgwLSVpFTlBFIFMuQS4xEzARBgNVBAMMCkl6ZW5wZS5jb20wHhcNMDcxMjEz
-MTMwODI4WhcNMzcxMjEzMDgyNzI1WjA4MQswCQYDVQQGEwJFUzEUMBIGA1UECgwLSVpFTlBFIFMu
-QS4xEzARBgNVBAMMCkl6ZW5wZS5jb20wggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDJ
-03rKDx6sp4boFmVqscIbRTJxldn+EFvMr+eleQGPicPK8lVx93e+d5TzcqQsRNiekpsUOqHnJJAK
-ClaOxdgmlOHZSOEtPtoKct2jmRXagaKH9HtuJneJWK3W6wyyQXpzbm3benhB6QiIEn6HLmYRY2xU
-+zydcsC8Lv/Ct90NduM61/e0aL6i9eOBbsFGb12N4E3GVFWJGjMxCrFXuaOKmMPsOzTFlUFpfnXC
-PCDFYbpRR6AgkJOhkEvzTnyFRVSa0QUmQbC1TR0zvsQDyCV8wXDbO/QJLVQnSKwv4cSsPsjLkkxT
-OTcj7NMB+eAJRE1NZMDhDVqHIrytG6P+JrUV86f8hBnp7KGItERphIPzidF0BqnMC9bC3ieFUCbK
-F7jJeodWLBoBHmy+E60QrLUk9TiRodZL2vG70t5HtfG8gfZZa88ZU+mNFctKy6lvROUbQc/hhqfK
-0GqfvEyNBjNaooXlkDWgYlwWTvDjovoDGrQscbNYLN57C9saD+veIR8GdwYDsMnvmfzAuU8Lhij+
-0rnq49qlw0dpEuDb8PYZi+17cNcC1u2HGCgsBCRMd+RIihrGO5rUD8r6ddIBQFqNeb+Lz0vPqhbB
-leStTIo+F5HUsWLlguWABKQDfo2/2n+iD5dPDNMN+9fR5XJ+HMh3/1uaD7euBUbl8agW7EekFwID
-AQABo4H2MIHzMIGwBgNVHREEgagwgaWBD2luZm9AaXplbnBlLmNvbaSBkTCBjjFHMEUGA1UECgw+
-SVpFTlBFIFMuQS4gLSBDSUYgQTAxMzM3MjYwLVJNZXJjLlZpdG9yaWEtR2FzdGVpeiBUMTA1NSBG
-NjIgUzgxQzBBBgNVBAkMOkF2ZGEgZGVsIE1lZGl0ZXJyYW5lbyBFdG9yYmlkZWEgMTQgLSAwMTAx
-MCBWaXRvcmlhLUdhc3RlaXowDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0O
-BBYEFB0cZQ6o8iV7tJHP5LGx5r1VdGwFMA0GCSqGSIb3DQEBCwUAA4ICAQB4pgwWSp9MiDrAyw6l
-Fn2fuUhfGI8NYjb2zRlrrKvV9pF9rnHzP7MOeIWblaQnIUdCSnxIOvVFfLMMjlF4rJUT3sb9fbga
-kEyrkgPH7UIBzg/YsfqikuFgba56awmqxinuaElnMIAkejEWOVt+8Rwu3WwJrfIxwYJOubv5vr8q
-hT/AQKM6WfxZSzwoJNu0FXWuDYi6LnPAvViH5ULy617uHjAimcs30cQhbIHsvm0m5hzkQiCeR7Cs
-g1lwLDXWrzY0tM07+DKo7+N4ifuNRSzanLh+QBxh5z6ikixL8s36mLYp//Pye6kfLqCTVyvehQP5
-aTfLnnhqBbTFMXiJ7HqnheG5ezzevh55hM6fcA5ZwjUukCox2eRFekGkLhObNA5me0mrZJfQRsN5
-nXJQY6aYWwa9SG3YOYNw6DXwBdGqvOPbyALqfP2C2sJbUjWumDqtujWTI6cfSN01RpiyEGjkpTHC
-ClguGYEQyVB1/OpaFs4R1+7vUIgtYf8/QnMFlEPVjjxOAToZpR9GTnfQXeWBIiGH/pR9hNiTrdZo
-Q0iy2+tzJOeRf1SktoA+naM8THLCV8Sg1Mw4J87VBp6iSNnpn86CcDaTmjvfliHjWbcM2pE38P1Z
-WrOZyGlsQyYBNWNgVYkDOnXYukrZVP/u3oDYLdE41V4tC5h9Pmzb/CaIxw==
------END CERTIFICATE-----
-
-Chambers of Commerce Root - 2008
-================================
------BEGIN CERTIFICATE-----
-MIIHTzCCBTegAwIBAgIJAKPaQn6ksa7aMA0GCSqGSIb3DQEBBQUAMIGuMQswCQYDVQQGEwJFVTFD
-MEEGA1UEBxM6TWFkcmlkIChzZWUgY3VycmVudCBhZGRyZXNzIGF0IHd3dy5jYW1lcmZpcm1hLmNv
-bS9hZGRyZXNzKTESMBAGA1UEBRMJQTgyNzQzMjg3MRswGQYDVQQKExJBQyBDYW1lcmZpcm1hIFMu
-QS4xKTAnBgNVBAMTIENoYW1iZXJzIG9mIENvbW1lcmNlIFJvb3QgLSAyMDA4MB4XDTA4MDgwMTEy
-Mjk1MFoXDTM4MDczMTEyMjk1MFowga4xCzAJBgNVBAYTAkVVMUMwQQYDVQQHEzpNYWRyaWQgKHNl
-ZSBjdXJyZW50IGFkZHJlc3MgYXQgd3d3LmNhbWVyZmlybWEuY29tL2FkZHJlc3MpMRIwEAYDVQQF
-EwlBODI3NDMyODcxGzAZBgNVBAoTEkFDIENhbWVyZmlybWEgUy5BLjEpMCcGA1UEAxMgQ2hhbWJl
-cnMgb2YgQ29tbWVyY2UgUm9vdCAtIDIwMDgwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoIC
-AQCvAMtwNyuAWko6bHiUfaN/Gh/2NdW928sNRHI+JrKQUrpjOyhYb6WzbZSm891kDFX29ufyIiKA
-XuFixrYp4YFs8r/lfTJqVKAyGVn+H4vXPWCGhSRv4xGzdz4gljUha7MI2XAuZPeEklPWDrCQiorj
-h40G072QDuKZoRuGDtqaCrsLYVAGUvGef3bsyw/QHg3PmTA9HMRFEFis1tPo1+XqxQEHd9ZR5gN/
-ikilTWh1uem8nk4ZcfUyS5xtYBkL+8ydddy/Js2Pk3g5eXNeJQ7KXOt3EgfLZEFHcpOrUMPrCXZk
-NNI5t3YRCQ12RcSprj1qr7V9ZS+UWBDsXHyvfuK2GNnQm05aSd+pZgvMPMZ4fKecHePOjlO+Bd5g
-D2vlGts/4+EhySnB8esHnFIbAURRPHsl18TlUlRdJQfKFiC4reRB7noI/plvg6aRArBsNlVq5331
-lubKgdaX8ZSD6e2wsWsSaR6s+12pxZjptFtYer49okQ6Y1nUCyXeG0+95QGezdIp1Z8XGQpvvwyQ
-0wlf2eOKNcx5Wk0ZN5K3xMGtr/R5JJqyAQuxr1yW84Ay+1w9mPGgP0revq+ULtlVmhduYJ1jbLhj
-ya6BXBg14JC7vjxPNyK5fuvPnnchpj04gftI2jE9K+OJ9dC1vX7gUMQSibMjmhAxhduub+84Mxh2
-EQIDAQABo4IBbDCCAWgwEgYDVR0TAQH/BAgwBgEB/wIBDDAdBgNVHQ4EFgQU+SSsD7K1+HnA+mCI
-G8TZTQKeFxkwgeMGA1UdIwSB2zCB2IAU+SSsD7K1+HnA+mCIG8TZTQKeFxmhgbSkgbEwga4xCzAJ
-BgNVBAYTAkVVMUMwQQYDVQQHEzpNYWRyaWQgKHNlZSBjdXJyZW50IGFkZHJlc3MgYXQgd3d3LmNh
-bWVyZmlybWEuY29tL2FkZHJlc3MpMRIwEAYDVQQFEwlBODI3NDMyODcxGzAZBgNVBAoTEkFDIENh
-bWVyZmlybWEgUy5BLjEpMCcGA1UEAxMgQ2hhbWJlcnMgb2YgQ29tbWVyY2UgUm9vdCAtIDIwMDiC
-CQCj2kJ+pLGu2jAOBgNVHQ8BAf8EBAMCAQYwPQYDVR0gBDYwNDAyBgRVHSAAMCowKAYIKwYBBQUH
-AgEWHGh0dHA6Ly9wb2xpY3kuY2FtZXJmaXJtYS5jb20wDQYJKoZIhvcNAQEFBQADggIBAJASryI1
-wqM58C7e6bXpeHxIvj99RZJe6dqxGfwWPJ+0W2aeaufDuV2I6A+tzyMP3iU6XsxPpcG1Lawk0lgH
-3qLPaYRgM+gQDROpI9CF5Y57pp49chNyM/WqfcZjHwj0/gF/JM8rLFQJ3uIrbZLGOU8W6jx+ekbU
-RWpGqOt1glanq6B8aBMz9p0w8G8nOSQjKpD9kCk18pPfNKXG9/jvjA9iSnyu0/VU+I22mlaHFoI6
-M6taIgj3grrqLuBHmrS1RaMFO9ncLkVAO+rcf+g769HsJtg1pDDFOqxXnrN2pSB7+R5KBWIBpih1
-YJeSDW4+TTdDDZIVnBgizVGZoCkaPF+KMjNbMMeJL0eYD6MDxvbxrN8y8NmBGuScvfaAFPDRLLmF
-9dijscilIeUcE5fuDr3fKanvNFNb0+RqE4QGtjICxFKuItLcsiFCGtpA8CnJ7AoMXOLQusxI0zcK
-zBIKinmwPQN/aUv0NCB9szTqjktk9T79syNnFQ0EuPAtwQlRPLJsFfClI9eDdOTlLsn+mCdCxqvG
-nrDQWzilm1DefhiYtUU79nm06PcaewaD+9CL2rvHvRirCG88gGtAPxkZumWK5r7VXNM21+9AUiRg
-OGcEMeyP84LG3rlV8zsxkVrctQgVrXYlCg17LofiDKYGvCYQbTed7N14jHyAxfDZd0jQ
------END CERTIFICATE-----
-
-Global Chambersign Root - 2008
-==============================
------BEGIN CERTIFICATE-----
-MIIHSTCCBTGgAwIBAgIJAMnN0+nVfSPOMA0GCSqGSIb3DQEBBQUAMIGsMQswCQYDVQQGEwJFVTFD
-MEEGA1UEBxM6TWFkcmlkIChzZWUgY3VycmVudCBhZGRyZXNzIGF0IHd3dy5jYW1lcmZpcm1hLmNv
-bS9hZGRyZXNzKTESMBAGA1UEBRMJQTgyNzQzMjg3MRswGQYDVQQKExJBQyBDYW1lcmZpcm1hIFMu
-QS4xJzAlBgNVBAMTHkdsb2JhbCBDaGFtYmVyc2lnbiBSb290IC0gMjAwODAeFw0wODA4MDExMjMx
-NDBaFw0zODA3MzExMjMxNDBaMIGsMQswCQYDVQQGEwJFVTFDMEEGA1UEBxM6TWFkcmlkIChzZWUg
-Y3VycmVudCBhZGRyZXNzIGF0IHd3dy5jYW1lcmZpcm1hLmNvbS9hZGRyZXNzKTESMBAGA1UEBRMJ
-QTgyNzQzMjg3MRswGQYDVQQKExJBQyBDYW1lcmZpcm1hIFMuQS4xJzAlBgNVBAMTHkdsb2JhbCBD
-aGFtYmVyc2lnbiBSb290IC0gMjAwODCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMDf
-VtPkOpt2RbQT2//BthmLN0EYlVJH6xedKYiONWwGMi5HYvNJBL99RDaxccy9Wglz1dmFRP+RVyXf
-XjaOcNFccUMd2drvXNL7G706tcuto8xEpw2uIRU/uXpbknXYpBI4iRmKt4DS4jJvVpyR1ogQC7N0
-ZJJ0YPP2zxhPYLIj0Mc7zmFLmY/CDNBAspjcDahOo7kKrmCgrUVSY7pmvWjg+b4aqIG7HkF4ddPB
-/gBVsIdU6CeQNR1MM62X/JcumIS/LMmjv9GYERTtY/jKmIhYF5ntRQOXfjyGHoiMvvKRhI9lNNgA
-TH23MRdaKXoKGCQwoze1eqkBfSbW+Q6OWfH9GzO1KTsXO0G2Id3UwD2ln58fQ1DJu7xsepeY7s2M
-H/ucUa6LcL0nn3HAa6x9kGbo1106DbDVwo3VyJ2dwW3Q0L9R5OP4wzg2rtandeavhENdk5IMagfe
-Ox2YItaswTXbo6Al/3K1dh3ebeksZixShNBFks4c5eUzHdwHU1SjqoI7mjcv3N2gZOnm3b2u/GSF
-HTynyQbehP9r6GsaPMWis0L7iwk+XwhSx2LE1AVxv8Rk5Pihg+g+EpuoHtQ2TS9x9o0o9oOpE9Jh
-wZG7SMA0j0GMS0zbaRL/UJScIINZc+18ofLx/d33SdNDWKBWY8o9PeU1VlnpDsogzCtLkykPAgMB
-AAGjggFqMIIBZjASBgNVHRMBAf8ECDAGAQH/AgEMMB0GA1UdDgQWBBS5CcqcHtvTbDprru1U8VuT
-BjUuXjCB4QYDVR0jBIHZMIHWgBS5CcqcHtvTbDprru1U8VuTBjUuXqGBsqSBrzCBrDELMAkGA1UE
-BhMCRVUxQzBBBgNVBAcTOk1hZHJpZCAoc2VlIGN1cnJlbnQgYWRkcmVzcyBhdCB3d3cuY2FtZXJm
-aXJtYS5jb20vYWRkcmVzcykxEjAQBgNVBAUTCUE4Mjc0MzI4NzEbMBkGA1UEChMSQUMgQ2FtZXJm
-aXJtYSBTLkEuMScwJQYDVQQDEx5HbG9iYWwgQ2hhbWJlcnNpZ24gUm9vdCAtIDIwMDiCCQDJzdPp
-1X0jzjAOBgNVHQ8BAf8EBAMCAQYwPQYDVR0gBDYwNDAyBgRVHSAAMCowKAYIKwYBBQUHAgEWHGh0
-dHA6Ly9wb2xpY3kuY2FtZXJmaXJtYS5jb20wDQYJKoZIhvcNAQEFBQADggIBAICIf3DekijZBZRG
-/5BXqfEv3xoNa/p8DhxJJHkn2EaqbylZUohwEurdPfWbU1Rv4WCiqAm57OtZfMY18dwY6fFn5a+6
-ReAJ3spED8IXDneRRXozX1+WLGiLwUePmJs9wOzL9dWCkoQ10b42OFZyMVtHLaoXpGNR6woBrX/s
-dZ7LoR/xfxKxueRkf2fWIyr0uDldmOghp+G9PUIadJpwr2hsUF1Jz//7Dl3mLEfXgTpZALVza2Mg
-9jFFCDkO9HB+QHBaP9BrQql0PSgvAm11cpUJjUhjxsYjV5KTXjXBjfkK9yydYhz2rXzdpjEetrHH
-foUm+qRqtdpjMNHvkzeyZi99Bffnt0uYlDXA2TopwZ2yUDMdSqlapskD7+3056huirRXhOukP9Du
-qqqHW2Pok+JrqNS4cnhrG+055F3Lm6qH1U9OAP7Zap88MQ8oAgF9mOinsKJknnn4SPIVqczmyETr
-P3iZ8ntxPjzxmKfFGBI/5rsoM0LpRQp8bfKGeS/Fghl9CYl8slR2iK7ewfPM4W7bMdaTrpmg7yVq
-c5iJWzouE4gev8CSlDQb4ye3ix5vQv/n6TebUB0tovkC7stYWDpxvGjjqsGvHCgfotwjZT+B6q6Z
-09gwzxMNTxXJhLynSC34MCN32EZLeW32jO06f2ARePTpm67VVMB0gNELQp/B
------END CERTIFICATE-----
-
-Go Daddy Root Certificate Authority - G2
-========================================
------BEGIN CERTIFICATE-----
-MIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMxEDAOBgNVBAgT
-B0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoTEUdvRGFkZHkuY29tLCBJbmMu
-MTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5
-MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgYMxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6
-b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjExMC8G
-A1UEAxMoR28gRGFkZHkgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZI
-hvcNAQEBBQADggEPADCCAQoCggEBAL9xYgjx+lk09xvJGKP3gElY6SKDE6bFIEMBO4Tx5oVJnyfq
-9oQbTqC023CYxzIBsQU+B07u9PpPL1kwIuerGVZr4oAH/PMWdYA5UXvl+TW2dE6pjYIT5LY/qQOD
-+qK+ihVqf94Lw7YZFAXK6sOoBJQ7RnwyDfMAZiLIjWltNowRGLfTshxgtDj6AozO091GB94KPutd
-fMh8+7ArU6SSYmlRJQVhGkSBjCypQ5Yj36w6gZoOKcUcqeldHraenjAKOc7xiID7S13MMuyFYkMl
-NAJWJwGRtDtwKj9useiciAF9n9T521NtYJ2/LOdYq7hfRvzOxBsDPAnrSTFcaUaz4EcCAwEAAaNC
-MEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFDqahQcQZyi27/a9
-BUFuIMGU2g/eMA0GCSqGSIb3DQEBCwUAA4IBAQCZ21151fmXWWcDYfF+OwYxdS2hII5PZYe096ac
-vNjpL9DbWu7PdIxztDhC2gV7+AJ1uP2lsdeu9tfeE8tTEH6KRtGX+rcuKxGrkLAngPnon1rpN5+r
-5N9ss4UXnT3ZJE95kTXWXwTrgIOrmgIttRD02JDHBHNA7XIloKmf7J6raBKZV8aPEjoJpL1E/QYV
-N8Gb5DKj7Tjo2GTzLH4U/ALqn83/B2gX2yKQOC16jdFU8WnjXzPKej17CuPKf1855eJ1usV2GDPO
-LPAvTK33sefOT6jEm0pUBsV/fdUID+Ic/n4XuKxe9tQWskMJDE32p2u0mYRlynqI4uJEvlz36hz1
------END CERTIFICATE-----
-
-Starfield Root Certificate Authority - G2
-=========================================
------BEGIN CERTIFICATE-----
-MIID3TCCAsWgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBjzELMAkGA1UEBhMCVVMxEDAOBgNVBAgT
-B0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoTHFN0YXJmaWVsZCBUZWNobm9s
-b2dpZXMsIEluYy4xMjAwBgNVBAMTKVN0YXJmaWVsZCBSb290IENlcnRpZmljYXRlIEF1dGhvcml0
-eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgY8xCzAJBgNVBAYTAlVTMRAw
-DgYDVQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFyZmllbGQg
-VGVjaG5vbG9naWVzLCBJbmMuMTIwMAYDVQQDEylTdGFyZmllbGQgUm9vdCBDZXJ0aWZpY2F0ZSBB
-dXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL3twQP89o/8ArFv
-W59I2Z154qK3A2FWGMNHttfKPTUuiUP3oWmb3ooa/RMgnLRJdzIpVv257IzdIvpy3Cdhl+72WoTs
-bhm5iSzchFvVdPtrX8WJpRBSiUZV9Lh1HOZ/5FSuS/hVclcCGfgXcVnrHigHdMWdSL5stPSksPNk
-N3mSwOxGXn/hbVNMYq/NHwtjuzqd+/x5AJhhdM8mgkBj87JyahkNmcrUDnXMN/uLicFZ8WJ/X7Nf
-ZTD4p7dNdloedl40wOiWVpmKs/B/pM293DIxfJHP4F8R+GuqSVzRmZTRouNjWwl2tVZi4Ut0HZbU
-JtQIBFnQmA4O5t78w+wfkPECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC
-AQYwHQYDVR0OBBYEFHwMMh+n2TB/xH1oo2Kooc6rB1snMA0GCSqGSIb3DQEBCwUAA4IBAQARWfol
-TwNvlJk7mh+ChTnUdgWUXuEok21iXQnCoKjUsHU48TRqneSfioYmUeYs0cYtbpUgSpIB7LiKZ3sx
-4mcujJUDJi5DnUox9g61DLu34jd/IroAow57UvtruzvE03lRTs2Q9GcHGcg8RnoNAX3FWOdt5oUw
-F5okxBDgBPfg8n/Uqgr/Qh037ZTlZFkSIHc40zI+OIF1lnP6aI+xy84fxez6nH7PfrHxBy22/L/K
-pL/QlwVKvOoYKAKQvVR4CSFx09F9HdkWsKlhPdAKACL8x3vLCWRFCztAgfd9fDL1mMpYjn0q7pBZ
-c2T5NnReJaH1ZgUufzkVqSr7UIuOhWn0
------END CERTIFICATE-----
-
-Starfield Services Root Certificate Authority - G2
-==================================================
------BEGIN CERTIFICATE-----
-MIID7zCCAtegAwIBAgIBADANBgkqhkiG9w0BAQsFADCBmDELMAkGA1UEBhMCVVMxEDAOBgNVBAgT
-B0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoTHFN0YXJmaWVsZCBUZWNobm9s
-b2dpZXMsIEluYy4xOzA5BgNVBAMTMlN0YXJmaWVsZCBTZXJ2aWNlcyBSb290IENlcnRpZmljYXRl
-IEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgZgxCzAJBgNV
-BAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxT
-dGFyZmllbGQgVGVjaG5vbG9naWVzLCBJbmMuMTswOQYDVQQDEzJTdGFyZmllbGQgU2VydmljZXMg
-Um9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
-AQoCggEBANUMOsQq+U7i9b4Zl1+OiFOxHz/Lz58gE20pOsgPfTz3a3Y4Y9k2YKibXlwAgLIvWX/2
-h/klQ4bnaRtSmpDhcePYLQ1Ob/bISdm28xpWriu2dBTrz/sm4xq6HZYuajtYlIlHVv8loJNwU4Pa
-hHQUw2eeBGg6345AWh1KTs9DkTvnVtYAcMtS7nt9rjrnvDH5RfbCYM8TWQIrgMw0R9+53pBlbQLP
-LJGmpufehRhJfGZOozptqbXuNC66DQO4M99H67FrjSXZm86B0UVGMpZwh94CDklDhbZsc7tk6mFB
-rMnUVN+HL8cisibMn1lUaJ/8viovxFUcdUBgF4UCVTmLfwUCAwEAAaNCMEAwDwYDVR0TAQH/BAUw
-AwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFJxfAN+qAdcwKziIorhtSpzyEZGDMA0GCSqG
-SIb3DQEBCwUAA4IBAQBLNqaEd2ndOxmfZyMIbw5hyf2E3F/YNoHN2BtBLZ9g3ccaaNnRbobhiCPP
-E95Dz+I0swSdHynVv/heyNXBve6SbzJ08pGCL72CQnqtKrcgfU28elUSwhXqvfdqlS5sdJ/PHLTy
-xQGjhdByPq1zqwubdQxtRbeOlKyWN7Wg0I8VRw7j6IPdj/3vQQF3zCepYoUz8jcI73HPdwbeyBkd
-iEDPfUYd/x7H4c7/I9vG+o1VTqkC50cRRj70/b17KSa7qWFiNyi2LSr2EIZkyXCn0q23KXB56jza
-YyWf/Wi3MOxw+3WKt21gZ7IeyLnp2KhvAotnDU0mV3HaIPzBSlCNsSi6
------END CERTIFICATE-----
-
-AffirmTrust Commercial
-======================
------BEGIN CERTIFICATE-----
-MIIDTDCCAjSgAwIBAgIId3cGJyapsXwwDQYJKoZIhvcNAQELBQAwRDELMAkGA1UEBhMCVVMxFDAS
-BgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVzdCBDb21tZXJjaWFsMB4XDTEw
-MDEyOTE0MDYwNloXDTMwMTIzMTE0MDYwNlowRDELMAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmly
-bVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVzdCBDb21tZXJjaWFsMIIBIjANBgkqhkiG9w0BAQEF
-AAOCAQ8AMIIBCgKCAQEA9htPZwcroRX1BiLLHwGy43NFBkRJLLtJJRTWzsO3qyxPxkEylFf6Eqdb
-DuKPHx6GGaeqtS25Xw2Kwq+FNXkyLbscYjfysVtKPcrNcV/pQr6U6Mje+SJIZMblq8Yrba0F8PrV
-C8+a5fBQpIs7R6UjW3p6+DM/uO+Zl+MgwdYoic+U+7lF7eNAFxHUdPALMeIrJmqbTFeurCA+ukV6
-BfO9m2kVrn1OIGPENXY6BwLJN/3HR+7o8XYdcxXyl6S1yHp52UKqK39c/s4mT6NmgTWvRLpUHhww
-MmWd5jyTXlBOeuM61G7MGvv50jeuJCqrVwMiKA1JdX+3KNp1v47j3A55MQIDAQABo0IwQDAdBgNV
-HQ4EFgQUnZPGU4teyq8/nx4P5ZmVvCT2lI8wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC
-AQYwDQYJKoZIhvcNAQELBQADggEBAFis9AQOzcAN/wr91LoWXym9e2iZWEnStB03TX8nfUYGXUPG
-hi4+c7ImfU+TqbbEKpqrIZcUsd6M06uJFdhrJNTxFq7YpFzUf1GO7RgBsZNjvbz4YYCanrHOQnDi
-qX0GJX0nof5v7LMeJNrjS1UaADs1tDvZ110w/YETifLCBivtZ8SOyUOyXGsViQK8YvxO8rUzqrJv
-0wqiUOP2O+guRMLbZjipM1ZI8W0bM40NjD9gN53Tym1+NH4Nn3J2ixufcv1SNUFFApYvHLKac0kh
-sUlHRUe072o0EclNmsxZt9YCnlpOZbWUrhvfKbAW8b8Angc6F2S1BLUjIZkKlTuXfO8=
------END CERTIFICATE-----
-
-AffirmTrust Networking
-======================
------BEGIN CERTIFICATE-----
-MIIDTDCCAjSgAwIBAgIIfE8EORzUmS0wDQYJKoZIhvcNAQEFBQAwRDELMAkGA1UEBhMCVVMxFDAS
-BgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVzdCBOZXR3b3JraW5nMB4XDTEw
-MDEyOTE0MDgyNFoXDTMwMTIzMTE0MDgyNFowRDELMAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmly
-bVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVzdCBOZXR3b3JraW5nMIIBIjANBgkqhkiG9w0BAQEF
-AAOCAQ8AMIIBCgKCAQEAtITMMxcua5Rsa2FSoOujz3mUTOWUgJnLVWREZY9nZOIG41w3SfYvm4SE
-Hi3yYJ0wTsyEheIszx6e/jarM3c1RNg1lho9Nuh6DtjVR6FqaYvZ/Ls6rnla1fTWcbuakCNrmreI
-dIcMHl+5ni36q1Mr3Lt2PpNMCAiMHqIjHNRqrSK6mQEubWXLviRmVSRLQESxG9fhwoXA3hA/Pe24
-/PHxI1Pcv2WXb9n5QHGNfb2V1M6+oF4nI979ptAmDgAp6zxG8D1gvz9Q0twmQVGeFDdCBKNwV6gb
-h+0t+nvujArjqWaJGctB+d1ENmHP4ndGyH329JKBNv3bNPFyfvMMFr20FQIDAQABo0IwQDAdBgNV
-HQ4EFgQUBx/S55zawm6iQLSwelAQUHTEyL0wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC
-AQYwDQYJKoZIhvcNAQEFBQADggEBAIlXshZ6qML91tmbmzTCnLQyFE2npN/svqe++EPbkTfOtDIu
-UFUaNU52Q3Eg75N3ThVwLofDwR1t3Mu1J9QsVtFSUzpE0nPIxBsFZVpikpzuQY0x2+c06lkh1QF6
-12S4ZDnNye2v7UsDSKegmQGA3GWjNq5lWUhPgkvIZfFXHeVZLgo/bNjR9eUJtGxUAArgFU2HdW23
-WJZa3W3SAKD0m0i+wzekujbgfIeFlxoVot4uolu9rxj5kFDNcFn4J2dHy8egBzp90SxdbBk6ZrV9
-/ZFvgrG+CJPbFEfxojfHRZ48x3evZKiT3/Zpg4Jg8klCNO1aAFSFHBY2kgxc+qatv9s=
------END CERTIFICATE-----
-
-AffirmTrust Premium
-===================
------BEGIN CERTIFICATE-----
-MIIFRjCCAy6gAwIBAgIIbYwURrGmCu4wDQYJKoZIhvcNAQEMBQAwQTELMAkGA1UEBhMCVVMxFDAS
-BgNVBAoMC0FmZmlybVRydXN0MRwwGgYDVQQDDBNBZmZpcm1UcnVzdCBQcmVtaXVtMB4XDTEwMDEy
-OTE0MTAzNloXDTQwMTIzMTE0MTAzNlowQTELMAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmlybVRy
-dXN0MRwwGgYDVQQDDBNBZmZpcm1UcnVzdCBQcmVtaXVtMIICIjANBgkqhkiG9w0BAQEFAAOCAg8A
-MIICCgKCAgEAxBLfqV/+Qd3d9Z+K4/as4Tx4mrzY8H96oDMq3I0gW64tb+eT2TZwamjPjlGjhVtn
-BKAQJG9dKILBl1fYSCkTtuG+kU3fhQxTGJoeJKJPj/CihQvL9Cl/0qRY7iZNyaqoe5rZ+jjeRFcV
-5fiMyNlI4g0WJx0eyIOFJbe6qlVBzAMiSy2RjYvmia9mx+n/K+k8rNrSs8PhaJyJ+HoAVt70VZVs
-+7pk3WKL3wt3MutizCaam7uqYoNMtAZ6MMgpv+0GTZe5HMQxK9VfvFMSF5yZVylmd2EhMQcuJUmd
-GPLu8ytxjLW6OQdJd/zvLpKQBY0tL3d770O/Nbua2Plzpyzy0FfuKE4mX4+QaAkvuPjcBukumj5R
-p9EixAqnOEhss/n/fauGV+O61oV4d7pD6kh/9ti+I20ev9E2bFhc8e6kGVQa9QPSdubhjL08s9NI
-S+LI+H+SqHZGnEJlPqQewQcDWkYtuJfzt9WyVSHvutxMAJf7FJUnM7/oQ0dG0giZFmA7mn7S5u04
-6uwBHjxIVkkJx0w3AJ6IDsBz4W9m6XJHMD4Q5QsDyZpCAGzFlH5hxIrff4IaC1nEWTJ3s7xgaVY5
-/bQGeyzWZDbZvUjthB9+pSKPKrhC9IK31FOQeE4tGv2Bb0TXOwF0lkLgAOIua+rF7nKsu7/+6qqo
-+Nz2snmKtmcCAwEAAaNCMEAwHQYDVR0OBBYEFJ3AZ6YMItkm9UWrpmVSESfYRaxjMA8GA1UdEwEB
-/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBDAUAA4ICAQCzV00QYk465KzquByv
-MiPIs0laUZx2KI15qldGF9X1Uva3ROgIRL8YhNILgM3FEv0AVQVhh0HctSSePMTYyPtwni94loMg
-Nt58D2kTiKV1NpgIpsbfrM7jWNa3Pt668+s0QNiigfV4Py/VpfzZotReBA4Xrf5B8OWycvpEgjNC
-6C1Y91aMYj+6QrCcDFx+LmUmXFNPALJ4fqENmS2NuB2OosSw/WDQMKSOyARiqcTtNd56l+0OOF6S
-L5Nwpamcb6d9Ex1+xghIsV5n61EIJenmJWtSKZGc0jlzCFfemQa0W50QBuHCAKi4HEoCChTQwUHK
-+4w1IX2COPKpVJEZNZOUbWo6xbLQu4mGk+ibyQ86p3q4ofB4Rvr8Ny/lioTz3/4E2aFooC8k4gmV
-BtWVyuEklut89pMFu+1z6S3RdTnX5yTb2E5fQ4+e0BQ5v1VwSJlXMbSc7kqYA5YwH2AG7hsj/oFg
-IxpHYoWlzBk0gG+zrBrjn/B7SK3VAdlntqlyk+otZrWyuOQ9PLLvTIzq6we/qzWaVYa8GKa1qF60
-g2xraUDTn9zxw2lrueFtCfTxqlB2Cnp9ehehVZZCmTEJ3WARjQUwfuaORtGdFNrHF+QFlozEJLUb
-zxQHskD4o55BhrwE0GuWyCqANP2/7waj3VjFhT0+j/6eKeC2uAloGRwYQw==
------END CERTIFICATE-----
-
-AffirmTrust Premium ECC
-=======================
------BEGIN CERTIFICATE-----
-MIIB/jCCAYWgAwIBAgIIdJclisc/elQwCgYIKoZIzj0EAwMwRTELMAkGA1UEBhMCVVMxFDASBgNV
-BAoMC0FmZmlybVRydXN0MSAwHgYDVQQDDBdBZmZpcm1UcnVzdCBQcmVtaXVtIEVDQzAeFw0xMDAx
-MjkxNDIwMjRaFw00MDEyMzExNDIwMjRaMEUxCzAJBgNVBAYTAlVTMRQwEgYDVQQKDAtBZmZpcm1U
-cnVzdDEgMB4GA1UEAwwXQWZmaXJtVHJ1c3QgUHJlbWl1bSBFQ0MwdjAQBgcqhkjOPQIBBgUrgQQA
-IgNiAAQNMF4bFZ0D0KF5Nbc6PJJ6yhUczWLznCZcBz3lVPqj1swS6vQUX+iOGasvLkjmrBhDeKzQ
-N8O9ss0s5kfiGuZjuD0uL3jET9v0D6RoTFVya5UdThhClXjMNzyR4ptlKymjQjBAMB0GA1UdDgQW
-BBSaryl6wBE1NSZRMADDav5A1a7WPDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAK
-BggqhkjOPQQDAwNnADBkAjAXCfOHiFBar8jAQr9HX/VsaobgxCd05DhT1wV/GzTjxi+zygk8N53X
-57hG8f2h4nECMEJZh0PUUd+60wkyWs6Iflc9nF9Ca/UHLbXwgpP5WW+uZPpY5Yse42O+tYHNbwKM
-eQ==
------END CERTIFICATE-----
-
-Certum Trusted Network CA
-=========================
------BEGIN CERTIFICATE-----
-MIIDuzCCAqOgAwIBAgIDBETAMA0GCSqGSIb3DQEBBQUAMH4xCzAJBgNVBAYTAlBMMSIwIAYDVQQK
-ExlVbml6ZXRvIFRlY2hub2xvZ2llcyBTLkEuMScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlv
-biBBdXRob3JpdHkxIjAgBgNVBAMTGUNlcnR1bSBUcnVzdGVkIE5ldHdvcmsgQ0EwHhcNMDgxMDIy
-MTIwNzM3WhcNMjkxMjMxMTIwNzM3WjB+MQswCQYDVQQGEwJQTDEiMCAGA1UEChMZVW5pemV0byBU
-ZWNobm9sb2dpZXMgUy5BLjEnMCUGA1UECxMeQ2VydHVtIENlcnRpZmljYXRpb24gQXV0aG9yaXR5
-MSIwIAYDVQQDExlDZXJ0dW0gVHJ1c3RlZCBOZXR3b3JrIENBMIIBIjANBgkqhkiG9w0BAQEFAAOC
-AQ8AMIIBCgKCAQEA4/t9o3K6wvDJFIf1awFO4W5AB7ptJ11/91sts1rHUV+rpDKmYYe2bg+G0jAC
-l/jXaVehGDldamR5xgFZrDwxSjh80gTSSyjoIF87B6LMTXPb865Px1bVWqeWifrzq2jUI4ZZJ88J
-J7ysbnKDHDBy3+Ci6dLhdHUZvSqeexVUBBvXQzmtVSjF4hq79MDkrjhJM8x2hZ85RdKknvISjFH4
-fOQtf/WsX+sWn7Et0brMkUJ3TCXJkDhv2/DM+44el1k+1WBO5gUo7Ul5E0u6SNsv+XLTOcr+H9g0
-cvW0QM8xAcPs3hEtF10fuFDRXhmnad4HMyjKUJX5p1TLVIZQRan5SQIDAQABo0IwQDAPBgNVHRMB
-Af8EBTADAQH/MB0GA1UdDgQWBBQIds3LB/8k9sXN7buQvOKEN0Z19zAOBgNVHQ8BAf8EBAMCAQYw
-DQYJKoZIhvcNAQEFBQADggEBAKaorSLOAT2mo/9i0Eidi15ysHhE49wcrwn9I0j6vSrEuVUEtRCj
-jSfeC4Jj0O7eDDd5QVsisrCaQVymcODU0HfLI9MA4GxWL+FpDQ3Zqr8hgVDZBqWo/5U30Kr+4rP1
-mS1FhIrlQgnXdAIv94nYmem8J9RHjboNRhx3zxSkHLmkMcScKHQDNP8zGSal6Q10tz6XxnboJ5aj
-Zt3hrvJBW8qYVoNzcOSGGtIxQbovvi0TWnZvTuhOgQ4/WwMioBK+ZlgRSssDxLQqKi2WF+A5VLxI
-03YnnZotBqbJ7DnSq9ufmgsnAjUpsUCV5/nonFWIGUbWtzT1fs45mtk48VH3Tyw=
------END CERTIFICATE-----
-
-Certinomis - Autorité Racine
-=============================
------BEGIN CERTIFICATE-----
-MIIFnDCCA4SgAwIBAgIBATANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJGUjETMBEGA1UEChMK
-Q2VydGlub21pczEXMBUGA1UECxMOMDAwMiA0MzM5OTg5MDMxJjAkBgNVBAMMHUNlcnRpbm9taXMg
-LSBBdXRvcml0w6kgUmFjaW5lMB4XDTA4MDkxNzA4Mjg1OVoXDTI4MDkxNzA4Mjg1OVowYzELMAkG
-A1UEBhMCRlIxEzARBgNVBAoTCkNlcnRpbm9taXMxFzAVBgNVBAsTDjAwMDIgNDMzOTk4OTAzMSYw
-JAYDVQQDDB1DZXJ0aW5vbWlzIC0gQXV0b3JpdMOpIFJhY2luZTCCAiIwDQYJKoZIhvcNAQEBBQAD
-ggIPADCCAgoCggIBAJ2Fn4bT46/HsmtuM+Cet0I0VZ35gb5j2CN2DpdUzZlMGvE5x4jYF1AMnmHa
-wE5V3udauHpOd4cN5bjr+p5eex7Ezyh0x5P1FMYiKAT5kcOrJ3NqDi5N8y4oH3DfVS9O7cdxbwly
-Lu3VMpfQ8Vh30WC8Tl7bmoT2R2FFK/ZQpn9qcSdIhDWerP5pqZ56XjUl+rSnSTV3lqc2W+HN3yNw
-2F1MpQiD8aYkOBOo7C+ooWfHpi2GR+6K/OybDnT0K0kCe5B1jPyZOQE51kqJ5Z52qz6WKDgmi92N
-jMD2AR5vpTESOH2VwnHu7XSu5DaiQ3XV8QCb4uTXzEIDS3h65X27uK4uIJPT5GHfceF2Z5c/tt9q
-c1pkIuVC28+BA5PY9OMQ4HL2AHCs8MF6DwV/zzRpRbWT5BnbUhYjBYkOjUjkJW+zeL9i9Qf6lSTC
-lrLooyPCXQP8w9PlfMl1I9f09bze5N/NgL+RiH2nE7Q5uiy6vdFrzPOlKO1Enn1So2+WLhl+HPNb
-xxaOu2B9d2ZHVIIAEWBsMsGoOBvrbpgT1u449fCfDu/+MYHB0iSVL1N6aaLwD4ZFjliCK0wi1F6g
-530mJ0jfJUaNSih8hp75mxpZuWW/Bd22Ql095gBIgl4g9xGC3srYn+Y3RyYe63j3YcNBZFgCQfna
-4NH4+ej9Uji29YnfAgMBAAGjWzBZMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0G
-A1UdDgQWBBQNjLZh2kS40RR9w759XkjwzspqsDAXBgNVHSAEEDAOMAwGCiqBegFWAgIAAQEwDQYJ
-KoZIhvcNAQEFBQADggIBACQ+YAZ+He86PtvqrxyaLAEL9MW12Ukx9F1BjYkMTv9sov3/4gbIOZ/x
-WqndIlgVqIrTseYyCYIDbNc/CMf4uboAbbnW/FIyXaR/pDGUu7ZMOH8oMDX/nyNTt7buFHAAQCva
-R6s0fl6nVjBhK4tDrP22iCj1a7Y+YEq6QpA0Z43q619FVDsXrIvkxmUP7tCMXWY5zjKn2BCXwH40
-nJ+U8/aGH88bc62UeYdocMMzpXDn2NU4lG9jeeu/Cg4I58UvD0KgKxRA/yHgBcUn4YQRE7rWhh1B
-CxMjidPJC+iKunqjo3M3NYB9Ergzd0A4wPpeMNLytqOx1qKVl4GbUu1pTP+A5FPbVFsDbVRfsbjv
-JL1vnxHDx2TCDyhihWZeGnuyt++uNckZM6i4J9szVb9o4XVIRFb7zdNIu0eJOqxp9YDG5ERQL1TE
-qkPFMTFYvZbF6nVsmnWxTfj3l/+WFvKXTej28xH5On2KOG4Ey+HTRRWqpdEdnV1j6CTmNhTih60b
-WfVEm/vXd3wfAXBioSAaosUaKPQhA+4u2cGA6rnZgtZbdsLLO7XSAPCjDuGtbkD326C00EauFddE
-wk01+dIL8hf2rGbVJLJP0RyZwG71fet0BLj5TXcJ17TPBzAJ8bgAVtkXFhYKK4bfjwEZGuW7gmP/
-vgt2Fl43N+bYdJeimUV5
------END CERTIFICATE-----
-
-Root CA Generalitat Valenciana
-==============================
------BEGIN CERTIFICATE-----
-MIIGizCCBXOgAwIBAgIEO0XlaDANBgkqhkiG9w0BAQUFADBoMQswCQYDVQQGEwJFUzEfMB0GA1UE
-ChMWR2VuZXJhbGl0YXQgVmFsZW5jaWFuYTEPMA0GA1UECxMGUEtJR1ZBMScwJQYDVQQDEx5Sb290
-IENBIEdlbmVyYWxpdGF0IFZhbGVuY2lhbmEwHhcNMDEwNzA2MTYyMjQ3WhcNMjEwNzAxMTUyMjQ3
-WjBoMQswCQYDVQQGEwJFUzEfMB0GA1UEChMWR2VuZXJhbGl0YXQgVmFsZW5jaWFuYTEPMA0GA1UE
-CxMGUEtJR1ZBMScwJQYDVQQDEx5Sb290IENBIEdlbmVyYWxpdGF0IFZhbGVuY2lhbmEwggEiMA0G
-CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDGKqtXETcvIorKA3Qdyu0togu8M1JAJke+WmmmO3I2
-F0zo37i7L3bhQEZ0ZQKQUgi0/6iMweDHiVYQOTPvaLRfX9ptI6GJXiKjSgbwJ/BXufjpTjJ3Cj9B
-ZPPrZe52/lSqfR0grvPXdMIKX/UIKFIIzFVd0g/bmoGlu6GzwZTNVOAydTGRGmKy3nXiz0+J2ZGQ
-D0EbtFpKd71ng+CT516nDOeB0/RSrFOyA8dEJvt55cs0YFAQexvba9dHq198aMpunUEDEO5rmXte
-JajCq+TA81yc477OMUxkHl6AovWDfgzWyoxVjr7gvkkHD6MkQXpYHYTqWBLI4bft75PelAgxAgMB
-AAGjggM7MIIDNzAyBggrBgEFBQcBAQQmMCQwIgYIKwYBBQUHMAGGFmh0dHA6Ly9vY3NwLnBraS5n
-dmEuZXMwEgYDVR0TAQH/BAgwBgEB/wIBAjCCAjQGA1UdIASCAiswggInMIICIwYKKwYBBAG/VQIB
-ADCCAhMwggHoBggrBgEFBQcCAjCCAdoeggHWAEEAdQB0AG8AcgBpAGQAYQBkACAAZABlACAAQwBl
-AHIAdABpAGYAaQBjAGEAYwBpAPMAbgAgAFIAYQDtAHoAIABkAGUAIABsAGEAIABHAGUAbgBlAHIA
-YQBsAGkAdABhAHQAIABWAGEAbABlAG4AYwBpAGEAbgBhAC4ADQAKAEwAYQAgAEQAZQBjAGwAYQBy
-AGEAYwBpAPMAbgAgAGQAZQAgAFAAcgDhAGMAdABpAGMAYQBzACAAZABlACAAQwBlAHIAdABpAGYA
-aQBjAGEAYwBpAPMAbgAgAHEAdQBlACAAcgBpAGcAZQAgAGUAbAAgAGYAdQBuAGMAaQBvAG4AYQBt
-AGkAZQBuAHQAbwAgAGQAZQAgAGwAYQAgAHAAcgBlAHMAZQBuAHQAZQAgAEEAdQB0AG8AcgBpAGQA
-YQBkACAAZABlACAAQwBlAHIAdABpAGYAaQBjAGEAYwBpAPMAbgAgAHMAZQAgAGUAbgBjAHUAZQBu
-AHQAcgBhACAAZQBuACAAbABhACAAZABpAHIAZQBjAGMAaQDzAG4AIAB3AGUAYgAgAGgAdAB0AHAA
-OgAvAC8AdwB3AHcALgBwAGsAaQAuAGcAdgBhAC4AZQBzAC8AYwBwAHMwJQYIKwYBBQUHAgEWGWh0
-dHA6Ly93d3cucGtpLmd2YS5lcy9jcHMwHQYDVR0OBBYEFHs100DSHHgZZu90ECjcPk+yeAT8MIGV
-BgNVHSMEgY0wgYqAFHs100DSHHgZZu90ECjcPk+yeAT8oWykajBoMQswCQYDVQQGEwJFUzEfMB0G
-A1UEChMWR2VuZXJhbGl0YXQgVmFsZW5jaWFuYTEPMA0GA1UECxMGUEtJR1ZBMScwJQYDVQQDEx5S
-b290IENBIEdlbmVyYWxpdGF0IFZhbGVuY2lhbmGCBDtF5WgwDQYJKoZIhvcNAQEFBQADggEBACRh
-TvW1yEICKrNcda3FbcrnlD+laJWIwVTAEGmiEi8YPyVQqHxK6sYJ2fR1xkDar1CdPaUWu20xxsdz
-Ckj+IHLtb8zog2EWRpABlUt9jppSCS/2bxzkoXHPjCpaF3ODR00PNvsETUlR4hTJZGH71BTg9J63
-NI8KJr2XXPR5OkowGcytT6CYirQxlyric21+eLj4iIlPsSKRZEv1UN4D2+XFducTZnV+ZfsBn5OH
-iJ35Rld8TWCvmHMTI6QgkYH60GFmuH3Rr9ZvHmw96RH9qfmCIoaZM3Fa6hlXPZHNqcCjbgcTpsnt
-+GijnsNacgmHKNHEc8RzGF9QdRYxn7fofMM=
------END CERTIFICATE-----
-
-A-Trust-nQual-03
-================
------BEGIN CERTIFICATE-----
-MIIDzzCCAregAwIBAgIDAWweMA0GCSqGSIb3DQEBBQUAMIGNMQswCQYDVQQGEwJBVDFIMEYGA1UE
-Cgw/QS1UcnVzdCBHZXMuIGYuIFNpY2hlcmhlaXRzc3lzdGVtZSBpbSBlbGVrdHIuIERhdGVudmVy
-a2VociBHbWJIMRkwFwYDVQQLDBBBLVRydXN0LW5RdWFsLTAzMRkwFwYDVQQDDBBBLVRydXN0LW5R
-dWFsLTAzMB4XDTA1MDgxNzIyMDAwMFoXDTE1MDgxNzIyMDAwMFowgY0xCzAJBgNVBAYTAkFUMUgw
-RgYDVQQKDD9BLVRydXN0IEdlcy4gZi4gU2ljaGVyaGVpdHNzeXN0ZW1lIGltIGVsZWt0ci4gRGF0
-ZW52ZXJrZWhyIEdtYkgxGTAXBgNVBAsMEEEtVHJ1c3QtblF1YWwtMDMxGTAXBgNVBAMMEEEtVHJ1
-c3QtblF1YWwtMDMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCtPWFuA/OQO8BBC4SA
-zewqo51ru27CQoT3URThoKgtUaNR8t4j8DRE/5TrzAUjlUC5B3ilJfYKvUWG6Nm9wASOhURh73+n
-yfrBJcyFLGM/BWBzSQXgYHiVEEvc+RFZznF/QJuKqiTfC0Li21a8StKlDJu3Qz7dg9MmEALP6iPE
-SU7l0+m0iKsMrmKS1GWH2WrX9IWf5DMiJaXlyDO6w8dB3F/GaswADm0yqLaHNgBid5seHzTLkDx4
-iHQF63n1k3Flyp3HaxgtPVxO59X4PzF9j4fsCiIvI+n+u33J4PTs63zEsMMtYrWacdaxaujs2e3V
-cuy+VwHOBVWf3tFgiBCzAgMBAAGjNjA0MA8GA1UdEwEB/wQFMAMBAf8wEQYDVR0OBAoECERqlWdV
-eRFPMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQUFAAOCAQEAVdRU0VlIXLOThaq/Yy/kgM40
-ozRiPvbY7meIMQQDbwvUB/tOdQ/TLtPAF8fGKOwGDREkDg6lXb+MshOWcdzUzg4NCmgybLlBMRmr
-sQd7TZjTXLDR8KdCoLXEjq/+8T/0709GAHbrAvv5ndJAlseIOrifEXnzgGWovR/TeIGgUUw3tKZd
-JXDRZslo+S4RFGjxVJgIrCaSD96JntT6s3kr0qN51OyLrIdTaEJMUVF0HhsnLuP1Hyl0Te2v9+GS
-mYHovjrHF1D2t8b8m7CKa9aIA5GPBnc6hQLdmNVDeD/GMBWsm2vLV7eJUYs66MmEDNuxUCAKGkq6
-ahq97BvIxYSazQ==
------END CERTIFICATE-----
-
-TWCA Root Certification Authority
-=================================
------BEGIN CERTIFICATE-----
-MIIDezCCAmOgAwIBAgIBATANBgkqhkiG9w0BAQUFADBfMQswCQYDVQQGEwJUVzESMBAGA1UECgwJ
-VEFJV0FOLUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFUV0NBIFJvb3QgQ2VydGlmaWNh
-dGlvbiBBdXRob3JpdHkwHhcNMDgwODI4MDcyNDMzWhcNMzAxMjMxMTU1OTU5WjBfMQswCQYDVQQG
-EwJUVzESMBAGA1UECgwJVEFJV0FOLUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFUV0NB
-IFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
-AoIBAQCwfnK4pAOU5qfeCTiRShFAh6d8WWQUe7UREN3+v9XAu1bihSX0NXIP+FPQQeFEAcK0HMMx
-QhZHhTMidrIKbw/lJVBPhYa+v5guEGcevhEFhgWQxFnQfHgQsIBct+HHK3XLfJ+utdGdIzdjp9xC
-oi2SBBtQwXu4PhvJVgSLL1KbralW6cH/ralYhzC2gfeXRfwZVzsrb+RH9JlF/h3x+JejiB03HFyP
-4HYlmlD4oFT/RJB2I9IyxsOrBr/8+7/zrX2SYgJbKdM1o5OaQ2RgXbL6Mv87BK9NQGr5x+PvI/1r
-y+UPizgN7gr8/g+YnzAx3WxSZfmLgb4i4RxYA7qRG4kHAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIB
-BjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRqOFsmjd6LWvJPelSDGRjjCDWmujANBgkqhkiG
-9w0BAQUFAAOCAQEAPNV3PdrfibqHDAhUaiBQkr6wQT25JmSDCi/oQMCXKCeCMErJk/9q56YAf4lC
-mtYR5VPOL8zy2gXE/uJQxDqGfczafhAJO5I1KlOy/usrBdlsXebQ79NqZp4VKIV66IIArB6nCWlW
-QtNoURi+VJq/REG6Sb4gumlc7rh3zc5sH62Dlhh9DrUUOYTxKOkto557HnpyWoOzeW/vtPzQCqVY
-T0bf+215WfKEIlKuD8z7fDvnaspHYcN6+NOSBB+4IIThNlQWx0DeO4pz3N/GCUzf7Nr/1FNCocny
-Yh0igzyXxfkZYiesZSLX0zzG5Y6yU8xJzrww/nsOM5D77dIUkR8Hrw==
------END CERTIFICATE-----
-
-Security Communication RootCA2
-==============================
------BEGIN CERTIFICATE-----
-MIIDdzCCAl+gAwIBAgIBADANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJKUDElMCMGA1UEChMc
-U0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEnMCUGA1UECxMeU2VjdXJpdHkgQ29tbXVuaWNh
-dGlvbiBSb290Q0EyMB4XDTA5MDUyOTA1MDAzOVoXDTI5MDUyOTA1MDAzOVowXTELMAkGA1UEBhMC
-SlAxJTAjBgNVBAoTHFNFQ09NIFRydXN0IFN5c3RlbXMgQ08uLExURC4xJzAlBgNVBAsTHlNlY3Vy
-aXR5IENvbW11bmljYXRpb24gUm9vdENBMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
-ANAVOVKxUrO6xVmCxF1SrjpDZYBLx/KWvNs2l9amZIyoXvDjChz335c9S672XewhtUGrzbl+dp++
-+T42NKA7wfYxEUV0kz1XgMX5iZnK5atq1LXaQZAQwdbWQonCv/Q4EpVMVAX3NuRFg3sUZdbcDE3R
-3n4MqzvEFb46VqZab3ZpUql6ucjrappdUtAtCms1FgkQhNBqyjoGADdH5H5XTz+L62e4iKrFvlNV
-spHEfbmwhRkGeC7bYRr6hfVKkaHnFtWOojnflLhwHyg/i/xAXmODPIMqGplrz95Zajv8bxbXH/1K
-EOtOghY6rCcMU/Gt1SSwawNQwS08Ft1ENCcadfsCAwEAAaNCMEAwHQYDVR0OBBYEFAqFqXdlBZh8
-QIH4D5csOPEK7DzPMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEB
-CwUAA4IBAQBMOqNErLlFsceTfsgLCkLfZOoc7llsCLqJX2rKSpWeeo8HxdpFcoJxDjrSzG+ntKEj
-u/Ykn8sX/oymzsLS28yN/HH8AynBbF0zX2S2ZTuJbxh2ePXcokgfGT+Ok+vx+hfuzU7jBBJV1uXk
-3fs+BXziHV7Gp7yXT2g69ekuCkO2r1dcYmh8t/2jioSgrGK+KwmHNPBqAbubKVY8/gA3zyNs8U6q
-tnRGEmyR7jTV7JqR50S+kDFy1UkC9gLl9B/rfNmWVan/7Ir5mUf/NVoCqgTLiluHcSmRvaS0eg29
-mvVXIwAHIRc/SjnRBUkLp7Y3gaVdjKozXoEofKd9J+sAro03
------END CERTIFICATE-----
-
-EC-ACC
-======
------BEGIN CERTIFICATE-----
-MIIFVjCCBD6gAwIBAgIQ7is969Qh3hSoYqwE893EATANBgkqhkiG9w0BAQUFADCB8zELMAkGA1UE
-BhMCRVMxOzA5BgNVBAoTMkFnZW5jaWEgQ2F0YWxhbmEgZGUgQ2VydGlmaWNhY2lvIChOSUYgUS0w
-ODAxMTc2LUkpMSgwJgYDVQQLEx9TZXJ2ZWlzIFB1YmxpY3MgZGUgQ2VydGlmaWNhY2lvMTUwMwYD
-VQQLEyxWZWdldSBodHRwczovL3d3dy5jYXRjZXJ0Lm5ldC92ZXJhcnJlbCAoYykwMzE1MDMGA1UE
-CxMsSmVyYXJxdWlhIEVudGl0YXRzIGRlIENlcnRpZmljYWNpbyBDYXRhbGFuZXMxDzANBgNVBAMT
-BkVDLUFDQzAeFw0wMzAxMDcyMzAwMDBaFw0zMTAxMDcyMjU5NTlaMIHzMQswCQYDVQQGEwJFUzE7
-MDkGA1UEChMyQWdlbmNpYSBDYXRhbGFuYSBkZSBDZXJ0aWZpY2FjaW8gKE5JRiBRLTA4MDExNzYt
-SSkxKDAmBgNVBAsTH1NlcnZlaXMgUHVibGljcyBkZSBDZXJ0aWZpY2FjaW8xNTAzBgNVBAsTLFZl
-Z2V1IGh0dHBzOi8vd3d3LmNhdGNlcnQubmV0L3ZlcmFycmVsIChjKTAzMTUwMwYDVQQLEyxKZXJh
-cnF1aWEgRW50aXRhdHMgZGUgQ2VydGlmaWNhY2lvIENhdGFsYW5lczEPMA0GA1UEAxMGRUMtQUND
-MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsyLHT+KXQpWIR4NA9h0X84NzJB5R85iK
-w5K4/0CQBXCHYMkAqbWUZRkiFRfCQ2xmRJoNBD45b6VLeqpjt4pEndljkYRm4CgPukLjbo73FCeT
-ae6RDqNfDrHrZqJyTxIThmV6PttPB/SnCWDaOkKZx7J/sxaVHMf5NLWUhdWZXqBIoH7nF2W4onW4
-HvPlQn2v7fOKSGRdghST2MDk/7NQcvJ29rNdQlB50JQ+awwAvthrDk4q7D7SzIKiGGUzE3eeml0a
-E9jD2z3Il3rucO2n5nzbcc8tlGLfbdb1OL4/pYUKGbio2Al1QnDE6u/LDsg0qBIimAy4E5S2S+zw
-0JDnJwIDAQABo4HjMIHgMB0GA1UdEQQWMBSBEmVjX2FjY0BjYXRjZXJ0Lm5ldDAPBgNVHRMBAf8E
-BTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUoMOLRKo3pUW/l4Ba0fF4opvpXY0wfwYD
-VR0gBHgwdjB0BgsrBgEEAfV4AQMBCjBlMCwGCCsGAQUFBwIBFiBodHRwczovL3d3dy5jYXRjZXJ0
-Lm5ldC92ZXJhcnJlbDA1BggrBgEFBQcCAjApGidWZWdldSBodHRwczovL3d3dy5jYXRjZXJ0Lm5l
-dC92ZXJhcnJlbCAwDQYJKoZIhvcNAQEFBQADggEBAKBIW4IB9k1IuDlVNZyAelOZ1Vr/sXE7zDkJ
-lF7W2u++AVtd0x7Y/X1PzaBB4DSTv8vihpw3kpBWHNzrKQXlxJ7HNd+KDM3FIUPpqojlNcAZQmNa
-Al6kSBg6hW/cnbw/nZzBh7h6YQjpdwt/cKt63dmXLGQehb+8dJahw3oS7AwaboMMPOhyRp/7SNVe
-l+axofjk70YllJyJ22k4vuxcDlbHZVHlUIiIv0LVKz3l+bqeLrPK9HOSAgu+TGbrIP65y7WZf+a2
-E/rKS03Z7lNGBjvGTq2TWoF+bCpLagVFjPIhpDGQh2xlnJ2lYJU6Un/10asIbvPuW/mIPX64b24D
-5EI=
------END CERTIFICATE-----
diff --git a/ruby_1_9_3/lib/rubygems/syck_hack.rb b/ruby_1_9_3/lib/rubygems/syck_hack.rb
deleted file mode 100644
index 1971165452..0000000000
--- a/ruby_1_9_3/lib/rubygems/syck_hack.rb
+++ /dev/null
@@ -1,145 +0,0 @@
-# :stopdoc:
-
-# Hack to handle syck's DefaultKey bug
-#
-# This file is always loaded AFTER either syck or psych are already
-# loaded. It then looks at what constants are available and creates
-# a consistent view on all rubys.
-#
-# All this is so that there is always a YAML::Syck::DefaultKey
-# class no matter if the full yaml library has loaded or not.
-#
-
-module YAML
- # In newer 1.9.2, there is a Syck toplevel constant instead of it
- # being underneith YAML. If so, reference it back under YAML as
- # well.
- if defined? ::Syck
- # for tests that change YAML::ENGINE
- # 1.8 does not support the second argument to const_defined?
- remove_const :Syck rescue nil
-
- Syck = ::Syck
-
- # JRuby's "Syck" is called "Yecht"
- elsif defined? YAML::Yecht
- Syck = YAML::Yecht
-
- # Otherwise, if there is no YAML::Syck, then we've got just psych
- # loaded, so lets define a stub for DefaultKey.
- elsif !defined? YAML::Syck
- module Syck
- class DefaultKey
- end
- end
- end
-
- # Now that we've got something that is always here, define #to_s
- # so when code tries to use this, it at least just shows up like it
- # should.
- module Syck
- class DefaultKey
- remove_method :to_s rescue nil
-
- def to_s
- '='
- end
- end
- end
-end
-
-# Sometime in the 1.9 dev cycle, the Syck constant was moved from under YAML
-# to be a toplevel constant. So gemspecs created under these versions of Syck
-# will have references to Syck::DefaultKey.
-#
-# So we need to be sure that we reference Syck at the toplevel too so that
-# we can always load these kind of gemspecs.
-#
-if !defined?(Syck)
- Syck = YAML::Syck
-end
-
-# Now that we've got Syck setup in all the right places, store
-# a reference to the DefaultKey class inside Gem. We do this so that
-# if later on YAML, etc are redefined, we've still got a consistent
-# place to find the DefaultKey class for comparison.
-
-module Gem
- # for tests that change YAML::ENGINE
- remove_const :SyckDefaultKey if const_defined? :SyckDefaultKey
-
- SyckDefaultKey = YAML::Syck::DefaultKey
-end
-
-# :startdoc:
-# :stopdoc:
-
-# Hack to handle syck's DefaultKey bug
-#
-# This file is always loaded AFTER either syck or psych are already
-# loaded. It then looks at what constants are available and creates
-# a consistent view on all rubys.
-#
-# All this is so that there is always a YAML::Syck::DefaultKey
-# class no matter if the full yaml library has loaded or not.
-#
-
-module YAML
- # In newer 1.9.2, there is a Syck toplevel constant instead of it
- # being underneith YAML. If so, reference it back under YAML as
- # well.
- if defined? ::Syck
- # for tests that change YAML::ENGINE
- remove_const :Syck if const_defined? :Syck, false
-
- Syck = ::Syck
-
- # JRuby's "Syck" is called "Yecht"
- elsif defined? YAML::Yecht
- Syck = YAML::Yecht
-
- # Otherwise, if there is no YAML::Syck, then we've got just psych
- # loaded, so lets define a stub for DefaultKey.
- elsif !defined? YAML::Syck
- module Syck
- class DefaultKey
- end
- end
- end
-
- # Now that we've got something that is always here, define #to_s
- # so when code tries to use this, it at least just shows up like it
- # should.
- module Syck
- class DefaultKey
- def to_s
- '='
- end
- end
- end
-end
-
-# Sometime in the 1.9 dev cycle, the Syck constant was moved from under YAML
-# to be a toplevel constant. So gemspecs created under these versions of Syck
-# will have references to Syck::DefaultKey.
-#
-# So we need to be sure that we reference Syck at the toplevel too so that
-# we can always load these kind of gemspecs.
-#
-if !defined?(Syck)
- Syck = YAML::Syck
-end
-
-# Now that we've got Syck setup in all the right places, store
-# a reference to the DefaultKey class inside Gem. We do this so that
-# if later on YAML, etc are redefined, we've still got a consistent
-# place to find the DefaultKey class for comparison.
-
-module Gem
- # for tests that change YAML::ENGINE
- remove_const :SyckDefaultKey if const_defined? :SyckDefaultKey
-
- SyckDefaultKey = YAML::Syck::DefaultKey
-end
-
-# :startdoc:
diff --git a/ruby_1_9_3/lib/rubygems/test_case.rb b/ruby_1_9_3/lib/rubygems/test_case.rb
deleted file mode 100644
index 9fbdfca52e..0000000000
--- a/ruby_1_9_3/lib/rubygems/test_case.rb
+++ /dev/null
@@ -1,870 +0,0 @@
-at_exit { $SAFE = 1 }
-
-if defined? Gem::QuickLoader
- Gem::QuickLoader.load_full_rubygems_library
-else
- require 'rubygems'
-end
-
-begin
- gem 'minitest'
-rescue Gem::LoadError
-end
-
-require "rubygems/deprecate"
-require 'minitest/autorun'
-require 'fileutils'
-require 'tmpdir'
-require 'uri'
-require 'rubygems/package'
-require 'rubygems/test_utilities'
-require 'pp'
-require 'zlib'
-require 'pathname'
-Gem.load_yaml
-
-require 'rubygems/mock_gem_ui'
-
-module Gem
-
- ##
- # Allows setting the gem path searcher. This method is available when
- # requiring 'rubygems/test_case'
-
- def self.searcher=(searcher)
- @searcher = searcher
- end
-
- ##
- # Allows setting the default SourceIndex. This method is available when
- # requiring 'rubygems/test_case'
-
- def self.source_index=(si)
- raise "This method is not supported"
- Gem::Specification.reset if si # HACK
- @@source_index = si
- end
-
- ##
- # Allows toggling Windows behavior. This method is available when requiring
- # 'rubygems/test_case'
-
- def self.win_platform=(val)
- @@win_platform = val
- end
-
- ##
- # Allows setting path to ruby. This method is available when requiring
- # 'rubygems/test_case'
-
- def self.ruby= ruby
- @ruby = ruby
- end
-
- ##
- # When rubygems/test_case is required the default user interaction is a
- # MockGemUi.
-
- module DefaultUserInteraction
- @ui = Gem::MockGemUi.new
- end
-end
-
-##
-# RubyGemTestCase provides a variety of methods for testing rubygems and
-# gem-related behavior in a sandbox. Through RubyGemTestCase you can install
-# and uninstall gems, fetch remote gems through a stub fetcher and be assured
-# your normal set of gems is not affected.
-#
-# Tests are always run at a safe level of 1.
-
-class Gem::TestCase < MiniTest::Unit::TestCase
-
- # TODO: move to minitest
- def assert_path_exists path, msg = nil
- msg = message(msg) { "Expected path '#{path}' to exist" }
- assert File.exist?(path), msg
- end
-
- # TODO: move to minitest
- def refute_path_exists path, msg = nil
- msg = message(msg) { "Expected path '#{path}' to not exist" }
- refute File.exist?(path), msg
- end
-
- include Gem::DefaultUserInteraction
-
- undef_method :default_test if instance_methods.include? 'default_test' or
- instance_methods.include? :default_test
-
- @@project_dir = Dir.pwd unless defined?(@@project_dir)
-
- ##
- # #setup prepares a sandboxed location to install gems. All installs are
- # directed to a temporary directory. All install plugins are removed.
- #
- # If the +RUBY+ environment variable is set the given path is used for
- # Gem::ruby. The local platform is set to <tt>i386-mswin32</tt> for Windows
- # or <tt>i686-darwin8.10.1</tt> otherwise.
- #
- # If the +KEEP_FILES+ environment variable is set the files will not be
- # removed from <tt>/tmp/test_rubygems_#{$$}.#{Time.now.to_i}</tt>.
-
- def setup
- super
-
- @orig_gem_home = ENV['GEM_HOME']
- @orig_gem_path = ENV['GEM_PATH']
-
- @current_dir = Dir.pwd
- @ui = Gem::MockGemUi.new
-
- tmpdir = nil
- Dir.chdir Dir.tmpdir do tmpdir = Dir.pwd end # HACK OSX /private/tmp
-
- if ENV['KEEP_FILES'] then
- @tempdir = File.join(tmpdir, "test_rubygems_#{$$}.#{Time.now.to_i}")
- else
- @tempdir = File.join(tmpdir, "test_rubygems_#{$$}")
- end
- @tempdir.untaint
- @gemhome = File.join @tempdir, 'gemhome'
- @userhome = File.join @tempdir, 'userhome'
-
- @orig_ruby = if ruby = ENV['RUBY'] then
- Gem.class_eval { ruby, @ruby = @ruby, ruby }
- ruby
- end
-
- Gem.ensure_gem_subdirectories @gemhome
-
- @orig_LOAD_PATH = $LOAD_PATH.dup
- $LOAD_PATH.map! { |s| File.expand_path s }
-
- Dir.chdir @tempdir
-
- @orig_ENV_HOME = ENV['HOME']
- ENV['HOME'] = @userhome
- Gem.instance_variable_set :@user_home, nil
-
- FileUtils.mkdir_p @gemhome
- FileUtils.mkdir_p @userhome
-
- Gem.use_paths(@gemhome)
-
- Gem.loaded_specs.clear
- Gem.unresolved_deps.clear
-
- Gem.configuration.verbose = true
- Gem.configuration.update_sources = true
-
- @gem_repo = "http://gems.example.com/"
- @uri = URI.parse @gem_repo
- Gem.sources.replace [@gem_repo]
-
- Gem.searcher = nil
- Gem::SpecFetcher.fetcher = nil
-
- @orig_BASERUBY = Gem::ConfigMap[:BASERUBY]
- Gem::ConfigMap[:BASERUBY] = Gem::ConfigMap[:ruby_install_name]
-
- @orig_arch = Gem::ConfigMap[:arch]
-
- if win_platform?
- util_set_arch 'i386-mswin32'
- else
- util_set_arch 'i686-darwin8.10.1'
- end
-
- @marshal_version = "#{Marshal::MAJOR_VERSION}.#{Marshal::MINOR_VERSION}"
-
- # TODO: move to installer test cases
- Gem.post_build_hooks.clear
- Gem.post_install_hooks.clear
- Gem.post_uninstall_hooks.clear
- Gem.pre_install_hooks.clear
- Gem.pre_uninstall_hooks.clear
-
- # TODO: move to installer test cases
- Gem.post_build do |installer|
- @post_build_hook_arg = installer
- true
- end
-
- Gem.post_install do |installer|
- @post_install_hook_arg = installer
- end
-
- Gem.post_uninstall do |uninstaller|
- @post_uninstall_hook_arg = uninstaller
- end
-
- Gem.pre_install do |installer|
- @pre_install_hook_arg = installer
- true
- end
-
- Gem.pre_uninstall do |uninstaller|
- @pre_uninstall_hook_arg = uninstaller
- end
- end
-
- ##
- # #teardown restores the process to its original state and removes the
- # tempdir unless the +KEEP_FILES+ environment variable was set.
-
- def teardown
- $LOAD_PATH.replace @orig_LOAD_PATH
-
- Gem::ConfigMap[:BASERUBY] = @orig_BASERUBY
- Gem::ConfigMap[:arch] = @orig_arch
-
- if defined? Gem::RemoteFetcher then
- Gem::RemoteFetcher.fetcher = nil
- end
-
- Dir.chdir @current_dir
-
- FileUtils.rm_rf @tempdir unless ENV['KEEP_FILES']
-
- ENV['GEM_HOME'] = @orig_gem_home
- ENV['GEM_PATH'] = @orig_gem_path
-
- _ = @orig_ruby
- Gem.class_eval { @ruby = _ } if _
-
- if @orig_ENV_HOME then
- ENV['HOME'] = @orig_ENV_HOME
- else
- ENV.delete 'HOME'
- end
- end
-
- ##
- # Builds and installs the Gem::Specification +spec+
-
- def install_gem spec, options = {}
- require 'rubygems/installer'
-
- use_ui Gem::MockGemUi.new do
- Dir.chdir @tempdir do
- Gem::Builder.new(spec).build
- end
- end
-
- gem = File.join(@tempdir, File.basename(spec.cache_file)).untaint
-
- Gem::Installer.new(gem, options.merge({:wrappers => true})).install
- end
-
- ##
- # Builds and installs the Gem::Specification +spec+ into the user dir
-
- def install_gem_user spec
- install_gem spec, :user_install => true
- end
-
- ##
- # Uninstalls the Gem::Specification +spec+
- def uninstall_gem spec
- require 'rubygems/uninstaller'
-
- Gem::Uninstaller.new(spec.name,
- :executables => true, :user_install => true).uninstall
- end
-
- ##
- # creates a temporary directory with hax
-
- def create_tmpdir
- tmpdir = nil
- Dir.chdir Dir.tmpdir do tmpdir = Dir.pwd end # HACK OSX /private/tmp
- tmpdir = File.join tmpdir, "test_rubygems_#{$$}"
- FileUtils.mkdir_p tmpdir
- return tmpdir
- end
-
- ##
- # Enables pretty-print for all tests
-
- def mu_pp(obj)
- s = ''
- s = PP.pp obj, s
- s = s.force_encoding(Encoding.default_external) if defined? Encoding
- s.chomp
- end
-
- ##
- # Reads a Marshal file at +path+
-
- def read_cache(path)
- open path.dup.untaint, 'rb' do |io|
- Marshal.load io.read
- end
- end
-
- ##
- # Reads a binary file at +path+
-
- def read_binary(path)
- Gem.read_binary path
- end
-
- ##
- # Writes a binary file to +path+ which is relative to +@gemhome+
-
- def write_file(path)
- path = File.join @gemhome, path unless Pathname.new(path).absolute?
- dir = File.dirname path
- FileUtils.mkdir_p dir
-
- open path, 'wb' do |io|
- yield io if block_given?
- end
-
- path
- end
-
- def all_spec_names
- Gem::Specification.map(&:full_name)
- end
-
- ##
- # Creates a Gem::Specification with a minimum of extra work. +name+ and
- # +version+ are the gem's name and version, platform, author, email,
- # homepage, summary and description are defaulted. The specification is
- # yielded for customization.
- #
- # The gem is added to the installed gems in +@gemhome+ and to the current
- # source_index.
- #
- # Use this with #write_file to build an installed gem.
-
- def quick_gem(name, version='2')
- require 'rubygems/specification'
-
- spec = Gem::Specification.new do |s|
- s.platform = Gem::Platform::RUBY
- s.name = name
- s.version = version
- s.author = 'A User'
- s.email = 'example@example.com'
- s.homepage = 'http://example.com'
- s.summary = "this is a summary"
- s.description = "This is a test description"
-
- yield(s) if block_given?
- end
-
- Gem::Specification.map # HACK: force specs to (re-)load before we write
-
- written_path = write_file spec.spec_file do |io|
- io.write spec.to_ruby_for_cache
- end
-
- spec.loaded_from = spec.loaded_from = written_path
-
- Gem::Specification.add_spec spec.for_cache
-
- return spec
- end
-
- def quick_spec name, version = '2'
- # TODO: deprecate
- require 'rubygems/specification'
-
- spec = Gem::Specification.new do |s|
- s.platform = Gem::Platform::RUBY
- s.name = name
- s.version = version
- s.author = 'A User'
- s.email = 'example@example.com'
- s.homepage = 'http://example.com'
- s.summary = "this is a summary"
- s.description = "This is a test description"
-
- yield(s) if block_given?
- end
-
- spec.loaded_from = spec.spec_file
-
- Gem::Specification.add_spec spec
-
- return spec
- end
-
- ##
- # Builds a gem from +spec+ and places it in <tt>File.join @gemhome,
- # 'cache'</tt>. Automatically creates files based on +spec.files+
-
- def util_build_gem(spec)
- dir = spec.gem_dir
- FileUtils.mkdir_p dir
-
- Dir.chdir dir do
- spec.files.each do |file|
- next if File.exist? file
- FileUtils.mkdir_p File.dirname(file)
- File.open file, 'w' do |fp| fp.puts "# #{file}" end
- end
-
- use_ui Gem::MockGemUi.new do
- Gem::Builder.new(spec).build
- end
-
- cache = spec.cache_file
- FileUtils.mv File.basename(cache), cache
- end
- end
-
- ##
- # Removes all installed gems from +@gemhome+.
-
- def util_clear_gems
- FileUtils.rm_rf File.join(@gemhome, "gems") # TODO: use Gem::Dirs
- FileUtils.rm_rf File.join(@gemhome, "specifications")
- Gem::Specification.reset
- end
-
- ##
- # Install the provided specs
-
- def install_specs(*specs)
- Gem::Specification.add_specs(*specs)
- Gem.searcher = nil
- end
-
- ##
- # Create a new spec (or gem if passed an array of files) and set it
- # up properly. Use this instead of util_spec and util_gem.
-
- def new_spec name, version, deps = nil, *files
- require 'rubygems/specification'
-
- spec = Gem::Specification.new do |s|
- s.platform = Gem::Platform::RUBY
- s.name = name
- s.version = version
- s.author = 'A User'
- s.email = 'example@example.com'
- s.homepage = 'http://example.com'
- s.summary = "this is a summary"
- s.description = "This is a test description"
-
- Array(deps).each do |n, req|
- s.add_dependency n, (req || '>= 0')
- end
-
- s.files.push(*files) unless files.empty?
-
- yield s if block_given?
- end
-
- spec.loaded_from = spec.spec_file
-
- unless files.empty? then
- write_file spec.spec_file do |io|
- io.write spec.to_ruby_for_cache
- end
-
- util_build_gem spec
-
- cache_file = File.join @tempdir, 'gems', "#{spec.full_name}.gem"
- FileUtils.mkdir_p File.dirname cache_file
- FileUtils.mv spec.cache_file, cache_file
- FileUtils.rm spec.spec_file
- end
-
- spec
- end
-
- ##
- # Creates a spec with +name+, +version+ and +deps+.
-
- def util_spec(name, version, deps = nil, &block)
- # TODO: deprecate
- raise "deps or block, not both" if deps and block
-
- if deps then
- block = proc do |s|
- # Since Hash#each is unordered in 1.8, sort
- # the keys and iterate that way so the tests are
- # deteriminstic on all implementations.
- deps.keys.sort.each do |n|
- s.add_dependency n, (deps[n] || '>= 0')
- end
- end
- end
-
- quick_spec(name, version, &block)
- end
-
- ##
- # Creates a gem with +name+, +version+ and +deps+. The specification will
- # be yielded before gem creation for customization. The gem will be placed
- # in <tt>File.join @tempdir, 'gems'</tt>. The specification and .gem file
- # location are returned.
-
- def util_gem(name, version, deps = nil, &block)
- # TODO: deprecate
- raise "deps or block, not both" if deps and block
-
- if deps then
- block = proc do |s|
- # Since Hash#each is unordered in 1.8, sort
- # the keys and iterate that way so the tests are
- # deteriminstic on all implementations.
- deps.keys.sort.each do |n|
- s.add_dependency n, (deps[n] || '>= 0')
- end
- end
- end
-
- spec = quick_gem(name, version, &block)
-
- util_build_gem spec
-
- cache_file = File.join @tempdir, 'gems', "#{spec.original_name}.gem"
- FileUtils.mkdir_p File.dirname cache_file
- FileUtils.mv spec.cache_file, cache_file
- FileUtils.rm spec.spec_file
-
- spec.loaded_from = nil
-
- [spec, cache_file]
- end
-
- ##
- # Gzips +data+.
-
- def util_gzip(data)
- out = StringIO.new
-
- Zlib::GzipWriter.wrap out do |io|
- io.write data
- end
-
- out.string
- end
-
- ##
- # Creates several default gems which all have a lib/code.rb file. The gems
- # are not installed but are available in the cache dir.
- #
- # +@a1+:: gem a version 1, this is the best-described gem.
- # +@a2+:: gem a version 2
- # +@a3a:: gem a version 3.a
- # +@a_evil9+:: gem a_evil version 9, use this to ensure similarly-named gems
- # don't collide with a.
- # +@b2+:: gem b version 2
- # +@c1_2+:: gem c version 1.2
- # +@pl1+:: gem pl version 1, this gem has a legacy platform of i386-linux.
- #
- # Additional +prerelease+ gems may also be created:
- #
- # +@a2_pre+:: gem a version 2.a
- # TODO: nuke this and fix tests. this should speed up a lot
-
- def util_make_gems(prerelease = false)
- @a1 = quick_gem 'a', '1' do |s|
- s.files = %w[lib/code.rb]
- s.require_paths = %w[lib]
- s.date = Gem::Specification::TODAY - 86400
- s.homepage = 'http://a.example.com'
- s.email = %w[example@example.com example2@example.com]
- s.authors = %w[Example Example2]
- s.description = <<-DESC
-This line is really, really long. So long, in fact, that it is more than eighty characters long! The purpose of this line is for testing wrapping behavior because sometimes people don't wrap their text to eighty characters. Without the wrapping, the text might not look good in the RSS feed.
-
-Also, a list:
- * An entry that\'s actually kind of sort
- * an entry that\'s really long, which will probably get wrapped funny. That's ok, somebody wasn't thinking straight when they made it more than eighty characters.
- DESC
- end
-
- init = proc do |s|
- s.files = %w[lib/code.rb]
- s.require_paths = %w[lib]
- end
-
- @a2 = quick_gem('a', '2', &init)
- @a3a = quick_gem('a', '3.a', &init)
- @a_evil9 = quick_gem('a_evil', '9', &init)
- @b2 = quick_gem('b', '2', &init)
- @c1_2 = quick_gem('c', '1.2', &init)
-
- @pl1 = quick_gem 'pl', '1' do |s| # l for legacy
- s.files = %w[lib/code.rb]
- s.require_paths = %w[lib]
- s.platform = Gem::Platform.new 'i386-linux'
- s.instance_variable_set :@original_platform, 'i386-linux'
- end
-
- if prerelease
- @a2_pre = quick_gem('a', '2.a', &init)
- write_file File.join(*%W[gems #{@a2_pre.original_name} lib code.rb])
- util_build_gem @a2_pre
- end
-
- write_file File.join(*%W[gems #{@a1.original_name} lib code.rb])
- write_file File.join(*%W[gems #{@a2.original_name} lib code.rb])
- write_file File.join(*%W[gems #{@a3a.original_name} lib code.rb])
- write_file File.join(*%W[gems #{@b2.original_name} lib code.rb])
- write_file File.join(*%W[gems #{@c1_2.original_name} lib code.rb])
- write_file File.join(*%W[gems #{@pl1.original_name} lib code.rb])
-
- [@a1, @a2, @a3a, @a_evil9, @b2, @c1_2, @pl1].each do |spec|
- util_build_gem spec
- end
-
- FileUtils.rm_r File.join(@gemhome, "gems", @pl1.original_name)
- end
-
- ##
- # Set the platform to +arch+
-
- def util_set_arch(arch)
- Gem::ConfigMap[:arch] = arch
- platform = Gem::Platform.new arch
-
- Gem.instance_variable_set :@platforms, nil
- Gem::Platform.instance_variable_set :@local, nil
-
- platform
- end
-
- ##
- # Sets up a fake fetcher using the gems from #util_make_gems. Optionally
- # additional +prerelease+ gems may be included.
- #
- # Gems created by this method may be fetched using Gem::RemoteFetcher.
-
- def util_setup_fake_fetcher(prerelease = false)
- require 'zlib'
- require 'socket'
- require 'rubygems/remote_fetcher'
-
- @fetcher = Gem::FakeFetcher.new
-
- util_make_gems(prerelease)
- Gem::Specification.reset
-
- @all_gems = [@a1, @a2, @a3a, @a_evil9, @b2, @c1_2].sort
- @all_gem_names = @all_gems.map { |gem| gem.full_name }
-
- gem_names = [@a1.full_name, @a2.full_name, @a3a.full_name, @b2.full_name]
- @gem_names = gem_names.sort.join("\n")
-
- Gem::RemoteFetcher.fetcher = @fetcher
- end
-
- ##
- # Sets up Gem::SpecFetcher to return information from the gems in +specs+.
- # Best used with +@all_gems+ from #util_setup_fake_fetcher.
-
- def util_setup_spec_fetcher(*specs)
- specs -= Gem::Specification._all
- Gem::Specification.add_specs(*specs)
-
- spec_fetcher = Gem::SpecFetcher.fetcher
-
- prerelease, _ = Gem::Specification.partition { |spec|
- spec.version.prerelease?
- }
-
- spec_fetcher.specs[@uri] = []
- Gem::Specification.each do |spec|
- spec_tuple = [spec.name, spec.version, spec.original_platform]
- spec_fetcher.specs[@uri] << spec_tuple
- end
-
- spec_fetcher.latest_specs[@uri] = []
- Gem::Specification.latest_specs.each do |spec|
- spec_tuple = [spec.name, spec.version, spec.original_platform]
- spec_fetcher.latest_specs[@uri] << spec_tuple
- end
-
- spec_fetcher.prerelease_specs[@uri] = []
- prerelease.each do |spec|
- spec_tuple = [spec.name, spec.version, spec.original_platform]
- spec_fetcher.prerelease_specs[@uri] << spec_tuple
- end
-
- v = Gem.marshal_version
-
- Gem::Specification.each do |spec|
- path = "#{@gem_repo}quick/Marshal.#{v}/#{spec.original_name}.gemspec.rz"
- data = Marshal.dump spec
- data_deflate = Zlib::Deflate.deflate data
- @fetcher.data[path] = data_deflate
- end unless Gem::RemoteFetcher === @fetcher # HACK for test_download_to_cache
-
- nil # force errors
- end
-
- ##
- # Deflates +data+
-
- def util_zip(data)
- Zlib::Deflate.deflate data
- end
-
- ##
- # Is this test being run on a Windows platform?
-
- def self.win_platform?
- Gem.win_platform?
- end
-
- ##
- # Is this test being run on a Windows platform?
-
- def win_platform?
- Gem.win_platform?
- end
-
- ##
- # Returns whether or not we're on a version of Ruby built with VC++ (or
- # Borland) versus Cygwin, Mingw, etc.
-
- def self.vc_windows?
- RUBY_PLATFORM.match('mswin')
- end
-
- ##
- # Returns whether or not we're on a version of Ruby built with VC++ (or
- # Borland) versus Cygwin, Mingw, etc.
-
- def vc_windows?
- RUBY_PLATFORM.match('mswin')
- end
-
- ##
- # Returns the make command for the current platform. For versions of Ruby
- # built on MS Windows with VC++ or Borland it will return 'nmake'. On all
- # other platforms, including Cygwin, it will return 'make'.
-
- def self.make_command
- ENV["make"] || (vc_windows? ? 'nmake' : 'make')
- end
-
- ##
- # Returns the make command for the current platform. For versions of Ruby
- # built on MS Windows with VC++ or Borland it will return 'nmake'. On all
- # other platforms, including Cygwin, it will return 'make'.
-
- def make_command
- ENV["make"] || (vc_windows? ? 'nmake' : 'make')
- end
-
- ##
- # Returns whether or not the nmake command could be found.
-
- def nmake_found?
- system('nmake /? 1>NUL 2>&1')
- end
-
- ##
- # Allows tests to use a random (but controlled) port number instead of
- # a hardcoded one. This helps CI tools when running parallels builds on
- # the same builder slave.
-
- def self.process_based_port
- @@process_based_port ||= 8000 + $$ % 1000
- end
-
- ##
- # See ::process_based_port
-
- def process_based_port
- self.class.process_based_port
- end
-
- ##
- # Allows the proper version of +rake+ to be used for the test.
-
- def build_rake_in
- gem_ruby = Gem.ruby
- Gem.ruby = @@ruby
- env_rake = ENV["rake"]
- ENV["rake"] = @@rake
- yield @@rake
- ensure
- Gem.ruby = gem_ruby
- if env_rake
- ENV["rake"] = env_rake
- else
- ENV.delete("rake")
- end
- end
-
- ##
- # Finds the path to the ruby executable
-
- def self.rubybin
- ruby = ENV["RUBY"]
- return ruby if ruby
- ruby = "ruby"
- rubyexe = "#{ruby}.exe"
-
- 3.times do
- if File.exist? ruby and File.executable? ruby and !File.directory? ruby
- return File.expand_path(ruby)
- end
- if File.exist? rubyexe and File.executable? rubyexe
- return File.expand_path(rubyexe)
- end
- ruby = File.join("..", ruby)
- end
-
- begin
- require "rbconfig"
- File.join(RbConfig::CONFIG["bindir"],
- RbConfig::CONFIG["ruby_install_name"] +
- RbConfig::CONFIG["EXEEXT"])
- rescue LoadError
- "ruby"
- end
- end
-
- @@ruby = rubybin
- env_rake = ENV['rake']
- ruby19_rake = File.expand_path("bin/rake", @@project_dir)
- @@rake = if env_rake then
- ENV["rake"]
- elsif File.exist? ruby19_rake then
- @@ruby + " " + ruby19_rake
- else
- 'rake'
- end
-
- ##
- # Construct a new Gem::Dependency.
-
- def dep name, *requirements
- Gem::Dependency.new name, *requirements
- end
-
- ##
- # Constructs a new Gem::Requirement.
-
- def req *requirements
- return requirements.first if Gem::Requirement === requirements.first
- Gem::Requirement.create requirements
- end
-
- ##
- # Constructs a new Gem::Specification.
-
- def spec name, version, &block
- Gem::Specification.new name, v(version), &block
- end
-
- ##
- # Construct a new Gem::Version.
-
- def v string
- Gem::Version.create string
- end
-
-end
diff --git a/ruby_1_9_3/lib/rubygems/test_utilities.rb b/ruby_1_9_3/lib/rubygems/test_utilities.rb
deleted file mode 100644
index 1a8fb5a0ad..0000000000
--- a/ruby_1_9_3/lib/rubygems/test_utilities.rb
+++ /dev/null
@@ -1,160 +0,0 @@
-require 'tempfile'
-require 'rubygems'
-require 'rubygems/remote_fetcher'
-
-##
-# A fake Gem::RemoteFetcher for use in tests or to avoid real live HTTP
-# requests when testing code that uses RubyGems.
-#
-# Example:
-#
-# @fetcher = Gem::FakeFetcher.new
-# @fetcher.data['http://gems.example.com/yaml'] = source_index.to_yaml
-# Gem::RemoteFetcher.fetcher = @fetcher
-#
-# # invoke RubyGems code
-#
-# paths = @fetcher.paths
-# assert_equal 'http://gems.example.com/yaml', paths.shift
-# assert paths.empty?, paths.join(', ')
-#
-# See RubyGems' tests for more examples of FakeFetcher.
-
-class Gem::FakeFetcher
-
- attr_reader :data
- attr_reader :last_request
- attr_accessor :paths
-
- def initialize
- @data = {}
- @paths = []
- end
-
- def find_data(path)
- path = path.to_s
- @paths << path
- raise ArgumentError, 'need full URI' unless path =~ %r'^https?://'
-
- unless @data.key? path then
- raise Gem::RemoteFetcher::FetchError.new("no data for #{path}", path)
- end
-
- @data[path]
- end
-
- def fetch_path path, mtime = nil
- data = find_data(path)
-
- if data.respond_to?(:call) then
- data.call
- else
- if path.to_s =~ /gz$/ and not data.nil? and not data.empty? then
- data = Gem.gunzip data
- end
-
- data
- end
- end
-
- # Thanks, FakeWeb!
- def open_uri_or_path(path)
- data = find_data(path)
- body, code, msg = data
-
- response = Net::HTTPResponse.send(:response_class, code.to_s).new("1.0", code.to_s, msg)
- response.instance_variable_set(:@body, body)
- response.instance_variable_set(:@read, true)
- response
- end
-
- def request(uri, request_class, last_modified = nil)
- data = find_data(uri)
- body, code, msg = data
-
- @last_request = request_class.new uri.request_uri
- yield @last_request if block_given?
-
- response = Net::HTTPResponse.send(:response_class, code.to_s).new("1.0", code.to_s, msg)
- response.instance_variable_set(:@body, body)
- response.instance_variable_set(:@read, true)
- response
- end
-
- def fetch_size(path)
- path = path.to_s
- @paths << path
-
- raise ArgumentError, 'need full URI' unless path =~ %r'^http://'
-
- unless @data.key? path then
- raise Gem::RemoteFetcher::FetchError.new("no data for #{path}", path)
- end
-
- data = @data[path]
-
- data.respond_to?(:call) ? data.call : data.length
- end
-
- def download spec, source_uri, install_dir = Gem.dir
- name = File.basename spec.cache_file
- path = File.join install_dir, "cache", name
-
- Gem.ensure_gem_subdirectories install_dir
-
- if source_uri =~ /^http/ then
- File.open(path, "wb") do |f|
- f.write fetch_path(File.join(source_uri, "gems", name))
- end
- else
- FileUtils.cp source_uri, path
- end
-
- path
- end
-
- def download_to_cache dependency
- found = Gem::SpecFetcher.fetcher.fetch dependency, true, true,
- dependency.prerelease?
-
- return if found.empty?
-
- spec, source_uri = found.first
-
- download spec, source_uri
- end
-
-end
-
-# :stopdoc:
-class Gem::RemoteFetcher
-
- def self.fetcher=(fetcher)
- @fetcher = fetcher
- end
-
-end
-# :startdoc:
-
-##
-# A StringIO duck-typed class that uses Tempfile instead of String as the
-# backing store.
-#
-# This is available when rubygems/test_utilities is required.
-#--
-# This class was added to flush out problems in Rubinius' IO implementation.
-
-class TempIO < Tempfile
- def initialize(string = '')
- super "TempIO"
- binmode
- write string
- rewind
- end
-
- def string
- flush
- Gem.read_binary path
- end
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/text.rb b/ruby_1_9_3/lib/rubygems/text.rb
deleted file mode 100644
index 793cd953cb..0000000000
--- a/ruby_1_9_3/lib/rubygems/text.rb
+++ /dev/null
@@ -1,65 +0,0 @@
-require 'rubygems'
-
-##
-# A collection of text-wrangling methods
-
-module Gem::Text
-
- ##
- # Wraps +text+ to +wrap+ characters and optionally indents by +indent+
- # characters
-
- def format_text(text, wrap, indent=0)
- result = []
- work = text.dup
-
- while work.length > wrap do
- if work =~ /^(.{0,#{wrap}})[ \n]/ then
- result << $1.rstrip
- work.slice!(0, $&.length)
- else
- result << work.slice!(0, wrap)
- end
- end
-
- result << work if work.length.nonzero?
- result.join("\n").gsub(/^/, " " * indent)
- end
-
- # This code is based directly on the Text gem implementation
- # Returns a value representing the "cost" of transforming str1 into str2
- def levenshtein_distance str1, str2
- s = str1
- t = str2
- n = s.length
- m = t.length
- max = n/2
-
- return m if (0 == n)
- return n if (0 == m)
- return n if (n - m).abs > max
-
- d = (0..m).to_a
- x = nil
-
- n.times do |i|
- e = i+1
-
- m.times do |j|
- cost = (s[i] == t[j]) ? 0 : 1
- x = [
- d[j+1] + 1, # insertion
- e + 1, # deletion
- d[j] + cost # substitution
- ].min
- d[j] = e
- e = x
- end
-
- d[m] = x
- end
-
- return x
- end
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/uninstaller.rb b/ruby_1_9_3/lib/rubygems/uninstaller.rb
deleted file mode 100644
index cc32ea48c4..0000000000
--- a/ruby_1_9_3/lib/rubygems/uninstaller.rb
+++ /dev/null
@@ -1,271 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-require 'fileutils'
-require 'rubygems'
-require 'rubygems/dependency_list'
-require 'rubygems/doc_manager'
-require 'rubygems/user_interaction'
-
-##
-# An Uninstaller.
-#
-# The uninstaller fires pre and post uninstall hooks. Hooks can be added
-# either through a rubygems_plugin.rb file in an installed gem or via a
-# rubygems/defaults/#{RUBY_ENGINE}.rb or rubygems/defaults/operating_system.rb
-# file. See Gem.pre_uninstall and Gem.post_uninstall for details.
-
-class Gem::Uninstaller
-
- include Gem::UserInteraction
-
- ##
- # The directory a gem's executables will be installed into
-
- attr_reader :bin_dir
-
- ##
- # The gem repository the gem will be installed into
-
- attr_reader :gem_home
-
- ##
- # The Gem::Specification for the gem being uninstalled, only set during
- # #uninstall_gem
-
- attr_reader :spec
-
- ##
- # Constructs an uninstaller that will uninstall +gem+
-
- def initialize(gem, options = {})
- @gem = gem
- @version = options[:version] || Gem::Requirement.default
- @gem_home = File.expand_path(options[:install_dir] || Gem.dir)
- @force_executables = options[:executables]
- @force_all = options[:all]
- @force_ignore = options[:ignore]
- @bin_dir = options[:bin_dir]
- @format_executable = options[:format_executable]
-
- # only add user directory if install_dir is not set
- @user_install = false
- @user_install = options[:user_install] unless options[:install_dir]
-
- if @user_install then
- Gem.use_paths Gem.user_dir, @gem_home
- else
- Gem.use_paths @gem_home
- end
- end
-
- ##
- # Performs the uninstall of the gem. This removes the spec, the Gem
- # directory, and the cached .gem file.
-
- def uninstall
- list = Gem::Specification.find_all_by_name(@gem, @version)
-
- if list.empty? then
- raise Gem::InstallError, "gem #{@gem.inspect} is not installed"
-
- elsif list.size > 1 and @force_all then
- remove_all list
-
- elsif list.size > 1 then
- gem_names = list.collect {|gem| gem.full_name} + ["All versions"]
-
- say
- _, index = choose_from_list "Select gem to uninstall:", gem_names
-
- if index == list.size then
- remove_all list
- elsif index >= 0 && index < list.size then
- uninstall_gem list[index]
- else
- say "Error: must enter a number [1-#{list.size+1}]"
- end
- else
- uninstall_gem list.first
- end
- end
-
- ##
- # Uninstalls gem +spec+
-
- def uninstall_gem(spec)
- @spec = spec
-
- unless dependencies_ok? spec
- unless ask_if_ok(spec)
- raise Gem::DependencyRemovalException,
- "Uninstallation aborted due to dependent gem(s)"
- end
- end
-
- Gem.pre_uninstall_hooks.each do |hook|
- hook.call self
- end
-
- remove_executables @spec
- remove @spec
-
- Gem.post_uninstall_hooks.each do |hook|
- hook.call self
- end
-
- @spec = nil
- end
-
- ##
- # Removes installed executables and batch files (windows only) for
- # +gemspec+.
-
- def remove_executables(spec)
- return if spec.nil? or spec.executables.empty?
-
- list = Gem::Specification.find_all { |s|
- s.name == spec.name && s.version != spec.version
- }
-
- executables = spec.executables.clone
-
- list.each do |s|
- s.executables.each do |exe_name|
- executables.delete exe_name
- end
- end
-
- return if executables.empty?
-
- executables = executables.map { |exec| formatted_program_filename exec }
-
- remove = if @force_executables.nil? then
- ask_yes_no("Remove executables:\n" \
- "\t#{executables.join ', '}\n\n" \
- "in addition to the gem?",
- true)
- else
- @force_executables
- end
-
- unless remove then
- say "Executables and scripts will remain installed."
- else
- bin_dir = @bin_dir || Gem.bindir(spec.base_dir)
-
- raise Gem::FilePermissionError, bin_dir unless File.writable? bin_dir
-
- executables.each do |exe_name|
- say "Removing #{exe_name}"
-
- exe_file = File.join bin_dir, exe_name
-
- FileUtils.rm_f exe_file
- FileUtils.rm_f "#{exe_file}.bat"
- end
- end
- end
-
- ##
- # Removes all gems in +list+.
- #
- # NOTE: removes uninstalled gems from +list+.
-
- def remove_all(list)
- list.each { |spec| uninstall_gem spec }
- end
-
- ##
- # spec:: the spec of the gem to be uninstalled
- # list:: the list of all such gems
- #
- # Warning: this method modifies the +list+ parameter. Once it has
- # uninstalled a gem, it is removed from that list.
-
- def remove(spec)
- unless path_ok?(@gem_home, spec) or
- (@user_install and path_ok?(Gem.user_dir, spec)) then
- e = Gem::GemNotInHomeException.new \
- "Gem is not installed in directory #{@gem_home}"
- e.spec = spec
-
- raise e
- end
-
- raise Gem::FilePermissionError, spec.base_dir unless
- File.writable?(spec.base_dir)
-
- FileUtils.rm_rf spec.full_gem_path
-
- # TODO: should this be moved to spec?... I vote eww (also exists in docmgr)
- old_platform_name = [spec.name,
- spec.version,
- spec.original_platform].join '-'
-
- gemspec = spec.spec_file
-
- unless File.exist? gemspec then
- gemspec = File.join(File.dirname(gemspec), "#{old_platform_name}.gemspec")
- end
-
- FileUtils.rm_rf gemspec
-
- gem = spec.cache_file
- gem = File.join(spec.cache_dir, "#{old_platform_name}.gem") unless
- File.exist? gem
-
- FileUtils.rm_rf gem
-
- Gem::DocManager.new(spec).uninstall_doc
-
- say "Successfully uninstalled #{spec.full_name}"
-
- Gem::Specification.remove_spec spec
- end
-
- ##
- # Is +spec+ in +gem_dir+?
-
- def path_ok?(gem_dir, spec)
- full_path = File.join gem_dir, 'gems', spec.full_name
- original_path = File.join gem_dir, 'gems', spec.original_name
-
- full_path == spec.full_gem_path || original_path == spec.full_gem_path
- end
-
- def dependencies_ok?(spec)
- return true if @force_ignore
-
- deplist = Gem::DependencyList.from_specs
- deplist.ok_to_remove?(spec.full_name)
- end
-
- def ask_if_ok(spec)
- msg = ['']
- msg << 'You have requested to uninstall the gem:'
- msg << "\t#{spec.full_name}"
-
- spec.dependent_gems.each do |dep_spec, dep, satlist|
- msg <<
- ("#{dep_spec.name}-#{dep_spec.version} depends on " +
- "[#{dep.name} (#{dep.requirement})]")
- end
-
- msg << 'If you remove this gems, one or more dependencies will not be met.'
- msg << 'Continue with Uninstall?'
- return ask_yes_no(msg.join("\n"), true)
- end
-
- def formatted_program_filename(filename)
- if @format_executable then
- require 'rubygems/installer'
- Gem::Installer.exec_format % File.basename(filename)
- else
- filename
- end
- end
-end
diff --git a/ruby_1_9_3/lib/rubygems/user_interaction.rb b/ruby_1_9_3/lib/rubygems/user_interaction.rb
deleted file mode 100644
index 8024d37287..0000000000
--- a/ruby_1_9_3/lib/rubygems/user_interaction.rb
+++ /dev/null
@@ -1,562 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-##
-# Module that defines the default UserInteraction. Any class including this
-# module will have access to the +ui+ method that returns the default UI.
-
-module Gem::DefaultUserInteraction
-
- ##
- # The default UI is a class variable of the singleton class for this
- # module.
-
- @ui = nil
-
- ##
- # Return the default UI.
-
- def self.ui
- @ui ||= Gem::ConsoleUI.new
- end
-
- ##
- # Set the default UI. If the default UI is never explicitly set, a simple
- # console based UserInteraction will be used automatically.
-
- def self.ui=(new_ui)
- @ui = new_ui
- end
-
- ##
- # Use +new_ui+ for the duration of +block+.
-
- def self.use_ui(new_ui)
- old_ui = @ui
- @ui = new_ui
- yield
- ensure
- @ui = old_ui
- end
-
- ##
- # See DefaultUserInteraction::ui
-
- def ui
- Gem::DefaultUserInteraction.ui
- end
-
- ##
- # See DefaultUserInteraction::ui=
-
- def ui=(new_ui)
- Gem::DefaultUserInteraction.ui = new_ui
- end
-
- ##
- # See DefaultUserInteraction::use_ui
-
- def use_ui(new_ui, &block)
- Gem::DefaultUserInteraction.use_ui(new_ui, &block)
- end
-
-end
-
-##
-# Make the default UI accessible without the "ui." prefix. Classes
-# including this module may use the interaction methods on the default UI
-# directly. Classes may also reference the ui and ui= methods.
-#
-# Example:
-#
-# class X
-# include Gem::UserInteraction
-#
-# def get_answer
-# n = ask("What is the meaning of life?")
-# end
-# end
-
-module Gem::UserInteraction
-
- include Gem::DefaultUserInteraction
-
- def alert(*args)
- ui.alert(*args)
- end
-
- def alert_error(*args)
- ui.alert_error(*args)
- end
-
- def alert_warning(*args)
- ui.alert_warning(*args)
- end
-
- def ask(*args)
- ui.ask(*args)
- end
-
- def ask_for_password(*args)
- ui.ask_for_password(*args)
- end
-
- def ask_yes_no(*args)
- ui.ask_yes_no(*args)
- end
-
- def choose_from_list(*args)
- ui.choose_from_list(*args)
- end
-
- def say(*args)
- ui.say(*args)
- end
-
- def terminate_interaction(*args)
- ui.terminate_interaction(*args)
- end
-end
-
-##
-# Gem::StreamUI implements a simple stream based user interface.
-
-class Gem::StreamUI
-
- attr_reader :ins, :outs, :errs
-
- def initialize(in_stream, out_stream, err_stream=STDERR, usetty=true)
- @ins = in_stream
- @outs = out_stream
- @errs = err_stream
- @usetty = usetty
- end
-
- def tty?
- if RUBY_VERSION < '1.9.3' and RUBY_PLATFORM =~ /mingw|mswin/ then
- @usetty
- else
- @usetty && @ins.tty?
- end
- end
-
- ##
- # Choose from a list of options. +question+ is a prompt displayed above
- # the list. +list+ is a list of option strings. Returns the pair
- # [option_name, option_index].
-
- def choose_from_list(question, list)
- @outs.puts question
-
- list.each_with_index do |item, index|
- @outs.puts " #{index+1}. #{item}"
- end
-
- @outs.print "> "
- @outs.flush
-
- result = @ins.gets
-
- return nil, nil unless result
-
- result = result.strip.to_i - 1
- return list[result], result
- end
-
- ##
- # Ask a question. Returns a true for yes, false for no. If not connected
- # to a tty, raises an exception if default is nil, otherwise returns
- # default.
-
- def ask_yes_no(question, default=nil)
- unless tty? then
- if default.nil? then
- raise Gem::OperationNotSupportedError,
- "Not connected to a tty and no default specified"
- else
- return default
- end
- end
-
- default_answer = case default
- when nil
- 'yn'
- when true
- 'Yn'
- else
- 'yN'
- end
-
- result = nil
-
- while result.nil? do
- result = case ask "#{question} [#{default_answer}]"
- when /^y/i then true
- when /^n/i then false
- when /^$/ then default
- else nil
- end
- end
-
- return result
- end
-
- ##
- # Ask a question. Returns an answer if connected to a tty, nil otherwise.
-
- def ask(question)
- return nil if not tty?
-
- @outs.print(question + " ")
- @outs.flush
-
- result = @ins.gets
- result.chomp! if result
- result
- end
-
- if RUBY_VERSION > '1.9.2' then
- ##
- # Ask for a password. Does not echo response to terminal.
-
- def ask_for_password(question)
- return nil if not tty?
-
- require 'io/console'
-
- @outs.print(question + " ")
- @outs.flush
-
- password = @ins.noecho {@ins.gets}
- password.chomp! if password
- password
- end
- else
- ##
- # Ask for a password. Does not echo response to terminal.
-
- def ask_for_password(question)
- return nil if not tty?
-
- @outs.print(question + " ")
- @outs.flush
-
- Gem.win_platform? ? ask_for_password_on_windows : ask_for_password_on_unix
- end
-
- ##
- # Asks for a password that works on windows. Ripped from the Heroku gem.
-
- def ask_for_password_on_windows
- return nil if not tty?
-
- require "Win32API"
- char = nil
- password = ''
-
- while char = Win32API.new("crtdll", "_getch", [ ], "L").Call do
- break if char == 10 || char == 13 # received carriage return or newline
- if char == 127 || char == 8 # backspace and delete
- password.slice!(-1, 1)
- else
- password << char.chr
- end
- end
-
- puts
- password
- end
-
- ##
- # Asks for a password that works on unix
-
- def ask_for_password_on_unix
- return nil if not tty?
-
- system "stty -echo"
- password = @ins.gets
- password.chomp! if password
- system "stty echo"
- password
- end
- end
-
- ##
- # Display a statement.
-
- def say(statement="")
- @outs.puts statement
- end
-
- ##
- # Display an informational alert. Will ask +question+ if it is not nil.
-
- def alert(statement, question=nil)
- @outs.puts "INFO: #{statement}"
- ask(question) if question
- end
-
- ##
- # Display a warning in a location expected to get error messages. Will
- # ask +question+ if it is not nil.
-
- def alert_warning(statement, question=nil)
- @errs.puts "WARNING: #{statement}"
- ask(question) if question
- end
-
- ##
- # Display an error message in a location expected to get error messages.
- # Will ask +question+ if it is not nil.
-
- def alert_error(statement, question=nil)
- @errs.puts "ERROR: #{statement}"
- ask(question) if question
- end
-
- ##
- # Display a debug message on the same location as error messages.
-
- def debug(statement)
- @errs.puts statement
- end
-
- ##
- # Terminate the application with exit code +status+, running any exit
- # handlers that might have been defined.
-
- def terminate_interaction(status = 0)
- raise Gem::SystemExitException, status
- end
-
- ##
- # Return a progress reporter object chosen from the current verbosity.
-
- def progress_reporter(*args)
- if self.kind_of?(Gem::SilentUI)
- return SilentProgressReporter.new(@outs, *args)
- end
-
- case Gem.configuration.verbose
- when nil, false
- SilentProgressReporter.new(@outs, *args)
- when true
- SimpleProgressReporter.new(@outs, *args)
- else
- VerboseProgressReporter.new(@outs, *args)
- end
- end
-
- ##
- # An absolutely silent progress reporter.
-
- class SilentProgressReporter
- attr_reader :count
-
- def initialize(out_stream, size, initial_message, terminal_message = nil)
- end
-
- def updated(message)
- end
-
- def done
- end
- end
-
- ##
- # A basic dotted progress reporter.
-
- class SimpleProgressReporter
-
- include Gem::DefaultUserInteraction
-
- attr_reader :count
-
- def initialize(out_stream, size, initial_message,
- terminal_message = "complete")
- @out = out_stream
- @total = size
- @count = 0
- @terminal_message = terminal_message
-
- @out.puts initial_message
- end
-
- ##
- # Prints out a dot and ignores +message+.
-
- def updated(message)
- @count += 1
- @out.print "."
- @out.flush
- end
-
- ##
- # Prints out the terminal message.
-
- def done
- @out.puts "\n#{@terminal_message}"
- end
-
- end
-
- ##
- # A progress reporter that prints out messages about the current progress.
-
- class VerboseProgressReporter
-
- include Gem::DefaultUserInteraction
-
- attr_reader :count
-
- def initialize(out_stream, size, initial_message,
- terminal_message = 'complete')
- @out = out_stream
- @total = size
- @count = 0
- @terminal_message = terminal_message
-
- @out.puts initial_message
- end
-
- ##
- # Prints out the position relative to the total and the +message+.
-
- def updated(message)
- @count += 1
- @out.puts "#{@count}/#{@total}: #{message}"
- end
-
- ##
- # Prints out the terminal message.
-
- def done
- @out.puts @terminal_message
- end
- end
-
- ##
- # Return a download reporter object chosen from the current verbosity
-
- def download_reporter(*args)
- if self.kind_of?(Gem::SilentUI)
- return SilentDownloadReporter.new(@outs, *args)
- end
-
- case Gem.configuration.verbose
- when nil, false
- SilentDownloadReporter.new(@outs, *args)
- else
- VerboseDownloadReporter.new(@outs, *args)
- end
- end
-
- ##
- # An absolutely silent download reporter.
-
- class SilentDownloadReporter
- def initialize(out_stream, *args)
- end
-
- def fetch(filename, filesize)
- end
-
- def update(current)
- end
-
- def done
- end
- end
-
- ##
- # A progress reporter that prints out messages about the current progress.
-
- class VerboseDownloadReporter
- attr_reader :file_name, :total_bytes, :progress
-
- def initialize(out_stream, *args)
- @out = out_stream
- @progress = 0
- end
-
- def fetch(file_name, total_bytes)
- @file_name = file_name
- @total_bytes = total_bytes.to_i
- @units = @total_bytes.zero? ? 'B' : '%'
-
- update_display(false)
- end
-
- def update(bytes)
- new_progress = if @units == 'B' then
- bytes
- else
- ((bytes.to_f * 100) / total_bytes.to_f).ceil
- end
-
- return if new_progress == @progress
-
- @progress = new_progress
- update_display
- end
-
- def done
- @progress = 100 if @units == '%'
- update_display(true, true)
- end
-
- private
-
- def update_display(show_progress = true, new_line = false)
- return unless @out.tty?
-
- if show_progress then
- @out.print "\rFetching: %s (%3d%s)" % [@file_name, @progress, @units]
- else
- @out.print "Fetching: %s" % @file_name
- end
- @out.puts if new_line
- end
- end
-end
-
-##
-# Subclass of StreamUI that instantiates the user interaction using STDIN,
-# STDOUT, and STDERR.
-
-class Gem::ConsoleUI < Gem::StreamUI
- def initialize
- super STDIN, STDOUT, STDERR, true
- end
-end
-
-##
-# SilentUI is a UI choice that is absolutely silent.
-
-class Gem::SilentUI < Gem::StreamUI
- def initialize
- reader, writer = nil, nil
-
- begin
- reader = File.open('/dev/null', 'r')
- writer = File.open('/dev/null', 'w')
- rescue Errno::ENOENT
- reader = File.open('nul', 'r')
- writer = File.open('nul', 'w')
- end
-
- super reader, writer, writer, false
- end
-
- def download_reporter(*args)
- SilentDownloadReporter.new(@outs, *args)
- end
-
- def progress_reporter(*args)
- SilentProgressReporter.new(@outs, *args)
- end
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/validator.rb b/ruby_1_9_3/lib/rubygems/validator.rb
deleted file mode 100644
index ffeed88660..0000000000
--- a/ruby_1_9_3/lib/rubygems/validator.rb
+++ /dev/null
@@ -1,169 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-require 'rubygems/format'
-require 'rubygems/installer'
-
-##
-# Validator performs various gem file and gem database validation
-
-class Gem::Validator
-
- include Gem::UserInteraction
-
- def initialize
- require 'find'
- require 'digest'
- end
-
- ##
- # Given a gem file's contents, validates against its own MD5 checksum
- # gem_data:: [String] Contents of the gem file
-
- def verify_gem(gem_data)
- raise Gem::VerificationError, 'empty gem file' if gem_data.size == 0
-
- unless gem_data =~ /MD5SUM/ then
- return # Don't worry about it...this sucks. Need to fix MD5 stuff for
- # new format
- # FIXME
- end
-
- sum_data = gem_data.gsub(/MD5SUM = "([a-z0-9]+)"/,
- "MD5SUM = \"#{"F" * 32}\"")
-
- unless Digest::MD5.hexdigest(sum_data) == $1.to_s then
- raise Gem::VerificationError, 'invalid checksum for gem file'
- end
- end
-
- ##
- # Given the path to a gem file, validates against its own MD5 checksum
- #
- # gem_path:: [String] Path to gem file
-
- def verify_gem_file(gem_path)
- open gem_path, Gem.binary_mode do |file|
- gem_data = file.read
- verify_gem gem_data
- end
- rescue Errno::ENOENT, Errno::EINVAL
- raise Gem::VerificationError, "missing gem file #{gem_path}"
- end
-
- private
-
- def find_files_for_gem(gem_directory)
- installed_files = []
- Find.find gem_directory do |file_name|
- fn = file_name[gem_directory.size..file_name.size-1].sub(/^\//, "")
- installed_files << fn unless
- fn =~ /CVS/ || fn.empty? || File.directory?(file_name)
- end
- installed_files
- end
-
- public
-
- ErrorData = Struct.new :path, :problem
-
- ##
- # Checks the gem directory for the following potential
- # inconsistencies/problems:
- #
- # * Checksum gem itself
- # * For each file in each gem, check consistency of installed versions
- # * Check for files that aren't part of the gem but are in the gems directory
- # * 1 cache - 1 spec - 1 directory.
- #
- # returns a hash of ErrorData objects, keyed on the problem gem's name.
-
- def alien(gems=[])
- errors = Hash.new { |h,k| h[k] = {} }
-
- Gem::SourceIndex.from_installed_gems.each do |gem_name, gem_spec|
- next unless gems.include? gem_spec.name unless gems.empty?
-
- install_dir = gem_spec.installation_path
- gem_path = Gem.cache_gem(gem_spec.file_name, install_dir)
- spec_path = File.join install_dir, "specifications", gem_spec.spec_name
- gem_directory = gem_spec.full_gem_path
-
- unless File.directory? gem_directory then
- errors[gem_name][gem_spec.full_name] =
- "Gem registered but doesn't exist at #{gem_directory}"
- next
- end
-
- unless File.exist? spec_path then
- errors[gem_name][spec_path] = "Spec file missing for installed gem"
- end
-
- begin
- verify_gem_file(gem_path)
-
- good, gone, unreadable = nil, nil, nil, nil
-
- open gem_path, Gem.binary_mode do |file|
- format = Gem::Format.from_file_by_path(gem_path)
-
- good, gone = format.file_entries.partition { |entry, _|
- File.exist? File.join(gem_directory, entry['path'])
- }
-
- gone.map! { |entry, _| entry['path'] }
- gone.sort.each do |path|
- errors[gem_name][path] = "Missing file"
- end
-
- good, unreadable = good.partition { |entry, _|
- File.readable? File.join(gem_directory, entry['path'])
- }
-
- unreadable.map! { |entry, _| entry['path'] }
- unreadable.sort.each do |path|
- errors[gem_name][path] = "Unreadable file"
- end
-
- good.each do |entry, data|
- begin
- next unless data # HACK `gem check -a mkrf`
-
- open File.join(gem_directory, entry['path']), Gem.binary_mode do |f|
- unless Digest::MD5.hexdigest(f.read).to_s ==
- Digest::MD5.hexdigest(data).to_s then
- errors[gem_name][entry['path']] = "Modified from original"
- end
- end
- end
- end
- end
-
- installed_files = find_files_for_gem(gem_directory)
- good.map! { |entry, _| entry['path'] }
- extras = installed_files - good - unreadable
-
- extras.each do |extra|
- errors[gem_name][extra] = "Extra file"
- end
- rescue Gem::VerificationError => e
- errors[gem_name][gem_path] = e.message
- end
- end
-
- errors.each do |name, subhash|
- errors[name] = subhash.map { |path, msg| ErrorData.new(path, msg) }
- end
-
- errors
- end
-
- def remove_leading_dot_dir(path)
- path.sub(/^\.\//, "")
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/rubygems/version.rb b/ruby_1_9_3/lib/rubygems/version.rb
deleted file mode 100644
index 2ced9ccdfb..0000000000
--- a/ruby_1_9_3/lib/rubygems/version.rb
+++ /dev/null
@@ -1,329 +0,0 @@
-##
-# The Version class processes string versions into comparable
-# values. A version string should normally be a series of numbers
-# separated by periods. Each part (digits separated by periods) is
-# considered its own number, and these are used for sorting. So for
-# instance, 3.10 sorts higher than 3.2 because ten is greater than
-# two.
-#
-# If any part contains letters (currently only a-z are supported) then
-# that version is considered prerelease. Versions with a prerelease
-# part in the Nth part sort less than versions with N-1
-# parts. Prerelease parts are sorted alphabetically using the normal
-# Ruby string sorting rules. If a prerelease part contains both
-# letters and numbers, it will be broken into multiple parts to
-# provide expected sort behavior (1.0.a10 becomes 1.0.a.10, and is
-# greater than 1.0.a9).
-#
-# Prereleases sort between real releases (newest to oldest):
-#
-# 1. 1.0
-# 2. 1.0.b1
-# 3. 1.0.a.2
-# 4. 0.9
-#
-# == How Software Changes
-#
-# Users expect to be able to specify a version constraint that gives them
-# some reasonable expectation that new versions of a library will work with
-# their software if the version constraint is true, and not work with their
-# software if the version constraint is false. In other words, the perfect
-# system will accept all compatible versions of the library and reject all
-# incompatible versions.
-#
-# Libraries change in 3 ways (well, more than 3, but stay focused here!).
-#
-# 1. The change may be an implementation detail only and have no effect on
-# the client software.
-# 2. The change may add new features, but do so in a way that client software
-# written to an earlier version is still compatible.
-# 3. The change may change the public interface of the library in such a way
-# that old software is no longer compatible.
-#
-# Some examples are appropriate at this point. Suppose I have a Stack class
-# that supports a <tt>push</tt> and a <tt>pop</tt> method.
-#
-# === Examples of Category 1 changes:
-#
-# * Switch from an array based implementation to a linked-list based
-# implementation.
-# * Provide an automatic (and transparent) backing store for large stacks.
-#
-# === Examples of Category 2 changes might be:
-#
-# * Add a <tt>depth</tt> method to return the current depth of the stack.
-# * Add a <tt>top</tt> method that returns the current top of stack (without
-# changing the stack).
-# * Change <tt>push</tt> so that it returns the item pushed (previously it
-# had no usable return value).
-#
-# === Examples of Category 3 changes might be:
-#
-# * Changes <tt>pop</tt> so that it no longer returns a value (you must use
-# <tt>top</tt> to get the top of the stack).
-# * Rename the methods to <tt>push_item</tt> and <tt>pop_item</tt>.
-#
-# == RubyGems Rational Versioning
-#
-# * Versions shall be represented by three non-negative integers, separated
-# by periods (e.g. 3.1.4). The first integers is the "major" version
-# number, the second integer is the "minor" version number, and the third
-# integer is the "build" number.
-#
-# * A category 1 change (implementation detail) will increment the build
-# number.
-#
-# * A category 2 change (backwards compatible) will increment the minor
-# version number and reset the build number.
-#
-# * A category 3 change (incompatible) will increment the major build number
-# and reset the minor and build numbers.
-#
-# * Any "public" release of a gem should have a different version. Normally
-# that means incrementing the build number. This means a developer can
-# generate builds all day long for himself, but as soon as he/she makes a
-# public release, the version must be updated.
-#
-# === Examples
-#
-# Let's work through a project lifecycle using our Stack example from above.
-#
-# Version 0.0.1:: The initial Stack class is release.
-# Version 0.0.2:: Switched to a linked=list implementation because it is
-# cooler.
-# Version 0.1.0:: Added a <tt>depth</tt> method.
-# Version 1.0.0:: Added <tt>top</tt> and made <tt>pop</tt> return nil
-# (<tt>pop</tt> used to return the old top item).
-# Version 1.1.0:: <tt>push</tt> now returns the value pushed (it used it
-# return nil).
-# Version 1.1.1:: Fixed a bug in the linked list implementation.
-# Version 1.1.2:: Fixed a bug introduced in the last fix.
-#
-# Client A needs a stack with basic push/pop capability. He writes to the
-# original interface (no <tt>top</tt>), so his version constraint looks
-# like:
-#
-# gem 'stack', '~> 0.0'
-#
-# Essentially, any version is OK with Client A. An incompatible change to
-# the library will cause him grief, but he is willing to take the chance (we
-# call Client A optimistic).
-#
-# Client B is just like Client A except for two things: (1) He uses the
-# <tt>depth</tt> method and (2) he is worried about future
-# incompatibilities, so he writes his version constraint like this:
-#
-# gem 'stack', '~> 0.1'
-#
-# The <tt>depth</tt> method was introduced in version 0.1.0, so that version
-# or anything later is fine, as long as the version stays below version 1.0
-# where incompatibilities are introduced. We call Client B pessimistic
-# because he is worried about incompatible future changes (it is OK to be
-# pessimistic!).
-#
-# == Preventing Version Catastrophe:
-#
-# From: http://blog.zenspider.com/2008/10/rubygems-howto-preventing-cata.html
-#
-# Let's say you're depending on the fnord gem version 2.y.z. If you
-# specify your dependency as ">= 2.0.0" then, you're good, right? What
-# happens if fnord 3.0 comes out and it isn't backwards compatible
-# with 2.y.z? Your stuff will break as a result of using ">=". The
-# better route is to specify your dependency with a "spermy" version
-# specifier. They're a tad confusing, so here is how the dependency
-# specifiers work:
-#
-# Specification From ... To (exclusive)
-# ">= 3.0" 3.0 ... &infin;
-# "~> 3.0" 3.0 ... 4.0
-# "~> 3.0.0" 3.0.0 ... 3.1
-# "~> 3.5" 3.5 ... 4.0
-# "~> 3.5.0" 3.5.0 ... 3.6
-
-class Gem::Version
- autoload :Requirement, 'rubygems/requirement'
-
- include Comparable
-
- VERSION_PATTERN = '[0-9]+(\.[0-9a-zA-Z]+)*' # :nodoc:
- ANCHORED_VERSION_PATTERN = /\A\s*(#{VERSION_PATTERN})*\s*\z/ # :nodoc:
-
- ##
- # A string representation of this Version.
-
- attr_reader :version
- alias to_s version
-
- ##
- # True if the +version+ string matches RubyGems' requirements.
-
- def self.correct? version
- version.to_s =~ ANCHORED_VERSION_PATTERN
- end
-
- ##
- # Factory method to create a Version object. Input may be a Version
- # or a String. Intended to simplify client code.
- #
- # ver1 = Version.create('1.3.17') # -> (Version object)
- # ver2 = Version.create(ver1) # -> (ver1)
- # ver3 = Version.create(nil) # -> nil
-
- def self.create input
- if input.respond_to? :version then
- input
- elsif input.nil? then
- nil
- else
- new input
- end
- end
-
- ##
- # Constructs a Version from the +version+ string. A version string is a
- # series of digits or ASCII letters separated by dots.
-
- def initialize version
- raise ArgumentError, "Malformed version number string #{version}" unless
- self.class.correct?(version)
-
- @version = version.to_s
- @version.strip!
- end
-
- ##
- # Return a new version object where the next to the last revision
- # number is one greater (e.g., 5.3.1 => 5.4).
- #
- # Pre-release (alpha) parts, e.g, 5.3.1.b.2 => 5.4, are ignored.
-
- def bump
- segments = self.segments.dup
- segments.pop while segments.any? { |s| String === s }
- segments.pop if segments.size > 1
-
- segments[-1] = segments[-1].succ
- self.class.new segments.join(".")
- end
-
- ##
- # A Version is only eql? to another version if it's specified to the
- # same precision. Version "1.0" is not the same as version "1".
-
- def eql? other
- self.class === other and @version == other.version
- end
-
- def hash # :nodoc:
- @hash ||= segments.hash
- end
-
- def init_with coder # :nodoc:
- yaml_initialize coder.tag, coder.map
- end
-
- def inspect # :nodoc:
- "#<#{self.class} #{version.inspect}>"
- end
-
- ##
- # Dump only the raw version string, not the complete object. It's a
- # string for backwards (RubyGems 1.3.5 and earlier) compatibility.
-
- def marshal_dump
- [version]
- end
-
- ##
- # Load custom marshal format. It's a string for backwards (RubyGems
- # 1.3.5 and earlier) compatibility.
-
- def marshal_load array
- initialize array[0]
- end
-
- def yaml_initialize(tag, map)
- @version = map['version']
- @segments = nil
- @hash = nil
- end
-
- ##
- # A version is considered a prerelease if it contains a letter.
-
- def prerelease?
- @prerelease ||= @version =~ /[a-zA-Z]/
- end
-
- def pretty_print q # :nodoc:
- q.text "Gem::Version.new(#{version.inspect})"
- end
-
- ##
- # The release for this version (e.g. 1.2.0.a -> 1.2.0).
- # Non-prerelease versions return themselves.
-
- def release
- return self unless prerelease?
-
- segments = self.segments.dup
- segments.pop while segments.any? { |s| String === s }
- self.class.new segments.join('.')
- end
-
- def segments # :nodoc:
-
- # segments is lazy so it can pick up version values that come from
- # old marshaled versions, which don't go through marshal_load.
-
- @segments ||= @version.scan(/[0-9]+|[a-z]+/i).map do |s|
- /^\d+$/ =~ s ? s.to_i : s
- end
- end
-
- ##
- # A recommended version for use with a ~> Requirement.
-
- def spermy_recommendation
- segments = self.segments.dup
-
- segments.pop while segments.any? { |s| String === s }
- segments.pop while segments.size > 2
- segments.push 0 while segments.size < 2
-
- "~> #{segments.join(".")}"
- end
-
- ##
- # Compares this version with +other+ returning -1, 0, or 1 if the
- # other version is larger, the same, or smaller than this
- # one. Attempts to compare to something that's not a
- # <tt>Gem::Version</tt> return +nil+.
-
- def <=> other
- return unless Gem::Version === other
- return 0 if @version == other.version
-
- lhsegments = segments
- rhsegments = other.segments
-
- lhsize = lhsegments.size
- rhsize = rhsegments.size
- limit = (lhsize > rhsize ? lhsize : rhsize) - 1
-
- i = 0
-
- while i <= limit
- lhs, rhs = lhsegments[i] || 0, rhsegments[i] || 0
- i += 1
-
- next if lhs == rhs
- return -1 if String === lhs && Numeric === rhs
- return 1 if Numeric === lhs && String === rhs
-
- return lhs <=> rhs
- end
-
- return 0
- end
-end
diff --git a/ruby_1_9_3/lib/rubygems/version_option.rb b/ruby_1_9_3/lib/rubygems/version_option.rb
deleted file mode 100644
index a3de4dc9e7..0000000000
--- a/ruby_1_9_3/lib/rubygems/version_option.rb
+++ /dev/null
@@ -1,65 +0,0 @@
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-require 'rubygems'
-
-##
-# Mixin methods for --version and --platform Gem::Command options.
-
-module Gem::VersionOption
-
- ##
- # Add the --platform option to the option parser.
-
- def add_platform_option(task = command, *wrap)
- OptionParser.accept Gem::Platform do |value|
- if value == Gem::Platform::RUBY then
- value
- else
- Gem::Platform.new value
- end
- end
-
- add_option('--platform PLATFORM', Gem::Platform,
- "Specify the platform of gem to #{task}", *wrap) do
- |value, options|
- unless options[:added_platform] then
- Gem.platforms = [Gem::Platform::RUBY]
- options[:added_platform] = true
- end
-
- Gem.platforms << value unless Gem.platforms.include? value
- end
- end
-
- ##
- # Add the --prerelease option to the option parser.
-
- def add_prerelease_option(*wrap)
- add_option("--[no-]prerelease",
- "Allow prerelease versions of a gem", *wrap) do |value, options|
- options[:prerelease] = value
- end
- end
-
- ##
- # Add the --version option to the option parser.
-
- def add_version_option(task = command, *wrap)
- OptionParser.accept Gem::Requirement do |value|
- Gem::Requirement.new value
- end
-
- add_option('-v', '--version VERSION', Gem::Requirement,
- "Specify version of gem to #{task}", *wrap) do
- |value, options|
- options[:version] = value
- options[:prerelease] = true if value.prerelease?
- end
- end
-
-end
-
diff --git a/ruby_1_9_3/lib/scanf.rb b/ruby_1_9_3/lib/scanf.rb
deleted file mode 100644
index 6d67627f39..0000000000
--- a/ruby_1_9_3/lib/scanf.rb
+++ /dev/null
@@ -1,771 +0,0 @@
-# scanf for Ruby
-#
-#--
-# $Release Version: 1.1.2 $
-# $Revision$
-# $Id$
-# $Author$
-#++
-#
-# == Description
-#
-# scanf is an implementation of the C function scanf(3), modified as necessary
-# for ruby compatibility.
-#
-# the methods provided are String#scanf, IO#scanf, and
-# Kernel#scanf. Kernel#scanf is a wrapper around STDIN.scanf. IO#scanf
-# can be used on any IO stream, including file handles and sockets.
-# scanf can be called either with or without a block.
-#
-# Scanf scans an input string or stream according to a <b>format</b>, as
-# described below in Conversions, and returns an array of matches between
-# the format and the input. The format is defined in a string, and is
-# similar (though not identical) to the formats used in Kernel#printf and
-# Kernel#sprintf.
-#
-# The format may contain <b>conversion specifiers</b>, which tell scanf
-# what form (type) each particular matched substring should be converted
-# to (e.g., decimal integer, floating point number, literal string,
-# etc.) The matches and conversions take place from left to right, and
-# the conversions themselves are returned as an array.
-#
-# The format string may also contain characters other than those in the
-# conversion specifiers. White space (blanks, tabs, or newlines) in the
-# format string matches any amount of white space, including none, in
-# the input. Everything else matches only itself.
-#
-# Scanning stops, and scanf returns, when any input character fails to
-# match the specifications in the format string, or when input is
-# exhausted, or when everything in the format string has been
-# matched. All matches found up to the stopping point are returned in
-# the return array (or yielded to the block, if a block was given).
-#
-#
-# == Basic usage
-#
-# require 'scanf'
-#
-# # String#scanf and IO#scanf take a single argument, the format string
-# array = a_string.scanf("%d%s")
-# array = an_io.scanf("%d%s")
-#
-# # Kernel#scanf reads from STDIN
-# array = scanf("%d%s")
-#
-# == Block usage
-#
-# When called with a block, scanf keeps scanning the input, cycling back
-# to the beginning of the format string, and yields a new array of
-# conversions to the block every time the format string is matched
-# (including partial matches, but not including complete failures). The
-# actual return value of scanf when called with a block is an array
-# containing the results of all the executions of the block.
-#
-# str = "123 abc 456 def 789 ghi"
-# str.scanf("%d%s") { |num,str| [ num * 2, str.upcase ] }
-# # => [[246, "ABC"], [912, "DEF"], [1578, "GHI"]]
-#
-# == Conversions
-#
-# The single argument to scanf is a format string, which generally
-# includes one or more conversion specifiers. Conversion specifiers
-# begin with the percent character ('%') and include information about
-# what scanf should next scan for (string, decimal number, single
-# character, etc.).
-#
-# There may be an optional maximum field width, expressed as a decimal
-# integer, between the % and the conversion. If no width is given, a
-# default of `infinity' is used (with the exception of the %c specifier;
-# see below). Otherwise, given a field width of <em>n</em> for a given
-# conversion, at most <em>n</em> characters are scanned in processing
-# that conversion. Before conversion begins, most conversions skip
-# white space in the input string; this white space is not counted
-# against the field width.
-#
-# The following conversions are available.
-#
-# [%]
-# Matches a literal `%'. That is, `%%' in the format string matches a
-# single input `%' character. No conversion is done, and the resulting
-# '%' is not included in the return array.
-#
-# [d]
-# Matches an optionally signed decimal integer.
-#
-# [u]
-# Same as d.
-#
-# [i]
-# Matches an optionally signed integer. The integer is read in base
-# 16 if it begins with `0x' or `0X', in base 8 if it begins with `0',
-# and in base 10 other- wise. Only characters that correspond to the
-# base are recognized.
-#
-# [o]
-# Matches an optionally signed octal integer.
-#
-# [x, X]
-# Matches an optionally signed hexadecimal integer,
-#
-# [a, e, f, g, A, E, F, G]
-# Matches an optionally signed floating-point number.
-#
-# [s]
-# Matches a sequence of non-white-space character. The input string stops at
-# white space or at the maximum field width, whichever occurs first.
-#
-# [c]
-# Matches a single character, or a sequence of <em>n</em> characters if a
-# field width of <em>n</em> is specified. The usual skip of leading white
-# space is suppressed. To skip white space first, use an explicit space in
-# the format.
-#
-# [[]
-# Matches a nonempty sequence of characters from the specified set
-# of accepted characters. The usual skip of leading white space is
-# suppressed. This bracketed sub-expression is interpreted exactly like a
-# character class in a Ruby regular expression. (In fact, it is placed as-is
-# in a regular expression.) The matching against the input string ends with
-# the appearance of a character not in (or, with a circumflex, in) the set,
-# or when the field width runs out, whichever comes first.
-#
-# === Assignment suppression
-#
-# To require that a particular match occur, but without including the result
-# in the return array, place the <b>assignment suppression flag</b>, which is
-# the star character ('*'), immediately after the leading '%' of a format
-# specifier (just before the field width, if any).
-#
-# == scanf for Ruby compared with scanf in C
-#
-# scanf for Ruby is based on the C function scanf(3), but with modifications,
-# dictated mainly by the underlying differences between the languages.
-#
-# === Unimplemented flags and specifiers
-#
-# * The only flag implemented in scanf for Ruby is '<tt>*</tt>' (ignore
-# upcoming conversion). Many of the flags available in C versions of
-# scanf(3) have to do with the type of upcoming pointer arguments, and are
-# meaningless in Ruby.
-#
-# * The <tt>n</tt> specifier (store number of characters consumed so far in
-# next pointer) is not implemented.
-#
-# * The <tt>p</tt> specifier (match a pointer value) is not implemented.
-#
-# === Altered specifiers
-#
-# [o, u, x, X]
-# In scanf for Ruby, all of these specifiers scan for an optionally signed
-# integer, rather than for an unsigned integer like their C counterparts.
-#
-# === Return values
-#
-# scanf for Ruby returns an array of successful conversions, whereas
-# scanf(3) returns the number of conversions successfully
-# completed. (See below for more details on scanf for Ruby's return
-# values.)
-#
-# == Return values
-#
-# Without a block, scanf returns an array containing all the conversions
-# it has found. If none are found, scanf will return an empty array. An
-# unsuccessful match is never ignored, but rather always signals the end
-# of the scanning operation. If the first unsuccessful match takes place
-# after one or more successful matches have already taken place, the
-# returned array will contain the results of those successful matches.
-#
-# With a block scanf returns a 'map'-like array of transformations from
-# the block -- that is, an array reflecting what the block did with each
-# yielded result from the iterative scanf operation. (See "Block
-# usage", above.)
-#
-# == Current limitations and bugs
-#
-# When using IO#scanf under Windows, make sure you open your files in
-# binary mode:
-#
-# File.open("filename", "rb")
-#
-# so that scanf can keep track of characters correctly.
-#
-# Support for character classes is reasonably complete (since it
-# essentially piggy-backs on Ruby's regular expression handling of
-# character classes), but users are advised that character class testing
-# has not been exhaustive, and that they should exercise some caution
-# in using any of the more complex and/or arcane character class
-# idioms.
-#
-# == License and copyright
-#
-# Copyright:: (c) 2002-2003 David Alan Black
-# License:: Distributed on the same licensing terms as Ruby itself
-#
-# == Warranty disclaimer
-#
-# This software is provided "as is" and without any express or implied
-# warranties, including, without limitation, the implied warranties of
-# merchantability and fitness for a particular purpose.
-#
-# == Credits and acknowledgements
-#
-# scanf was developed as the major activity of the Austin Ruby Codefest
-# (Austin, Texas, August 2002).
-#
-# Principal author:: David Alan Black (mailto:dblack@superlink.net)
-# Co-author:: Hal Fulton (mailto:hal9000@hypermetrics.com)
-# Project contributors:: Nolan Darilek, Jason Johnston
-#
-# Thanks to Hal Fulton for hosting the Codefest.
-#
-# Thanks to Matz for suggestions about the class design.
-#
-# Thanks to Gavin Sinclair for some feedback on the documentation.
-#
-# The text for parts of this document, especially the Description and
-# Conversions sections, above, were adapted from the Linux Programmer's
-# Manual manpage for scanf(3), dated 1995-11-01.
-#
-# == Bugs and bug reports
-#
-# scanf for Ruby is based on something of an amalgam of C scanf
-# implementations and documentation, rather than on a single canonical
-# description. Suggestions for features and behaviors which appear in
-# other scanfs, and would be meaningful in Ruby, are welcome, as are
-# reports of suspicious behaviors and/or bugs. (Please see "Credits and
-# acknowledgements", above, for email addresses.)
-
-module Scanf
- # :stopdoc:
-
- # ==Technical notes
- #
- # ===Rationale behind scanf for Ruby
- #
- # The impetus for a scanf implementation in Ruby comes chiefly from the fact
- # that existing pattern matching operations, such as Regexp#match and
- # String#scan, return all results as strings, which have to be converted to
- # integers or floats explicitly in cases where what's ultimately wanted are
- # integer or float values.
- #
- # ===Design of scanf for Ruby
- #
- # scanf for Ruby is essentially a <format string>-to-<regular
- # expression> converter.
- #
- # When scanf is called, a FormatString object is generated from the
- # format string ("%d%s...") argument. The FormatString object breaks the
- # format string down into atoms ("%d", "%5f", "blah", etc.), and from
- # each atom it creates a FormatSpecifier object, which it
- # saves.
- #
- # Each FormatSpecifier has a regular expression fragment and a "handler"
- # associated with it. For example, the regular expression fragment
- # associated with the format "%d" is "([-+]?\d+)", and the handler
- # associated with it is a wrapper around String#to_i. scanf itself calls
- # FormatString#match, passing in the input string. FormatString#match
- # iterates through its FormatSpecifiers; for each one, it matches the
- # corresponding regular expression fragment against the string. If
- # there's a match, it sends the matched string to the handler associated
- # with the FormatSpecifier.
- #
- # Thus, to follow up the "%d" example: if "123" occurs in the input
- # string when a FormatSpecifier consisting of "%d" is reached, the "123"
- # will be matched against "([-+]?\d+)", and the matched string will be
- # rendered into an integer by a call to to_i.
- #
- # The rendered match is then saved to an accumulator array, and the
- # input string is reduced to the post-match substring. Thus the string
- # is "eaten" from the left as the FormatSpecifiers are applied in
- # sequence. (This is done to a duplicate string; the original string is
- # not altered.)
- #
- # As soon as a regular expression fragment fails to match the string, or
- # when the FormatString object runs out of FormatSpecifiers, scanning
- # stops and results accumulated so far are returned in an array.
-
- class FormatSpecifier
-
- attr_reader :re_string, :matched_string, :conversion, :matched
-
- private
-
- def skip; /^\s*%\*/.match(@spec_string); end
-
- def extract_float(s)
- return nil unless s &&! skip
- if /\A(?<sign>[-+]?)0[xX](?<frac>\.\h+|\h+(?:\.\h*)?)[pP](?<exp>[-+]\d+)/ =~ s
- f1, f2 = frac.split('.')
- f = f1.hex
- if f2
- len = f2.length
- if len > 0
- f += f2.hex / (16.0 ** len)
- end
- end
- (sign == ?- ? -1 : 1) * Math.ldexp(f, exp.to_i)
- elsif /\A([-+]?\d+)\.([eE][-+]\d+)/ =~ s
- ($1 << $2).to_f
- else
- s.to_f
- end
- end
- def extract_decimal(s); s.to_i if s &&! skip; end
- def extract_hex(s); s.hex if s &&! skip; end
- def extract_octal(s); s.oct if s &&! skip; end
- def extract_integer(s); Integer(s) if s &&! skip; end
- def extract_plain(s); s unless skip; end
-
- def nil_proc(s); nil; end
-
- public
-
- def to_s
- @spec_string
- end
-
- def count_space?
- /(?:\A|\S)%\*?\d*c|%\d*\[/.match(@spec_string)
- end
-
- def initialize(str)
- @spec_string = str
- h = '[A-Fa-f0-9]'
-
- @re_string, @handler =
- case @spec_string
-
- # %[[:...:]]
- when /%\*?(\[\[:[a-z]+:\]\])/
- [ "(#{$1}+)", :extract_plain ]
-
- # %5[[:...:]]
- when /%\*?(\d+)(\[\[:[a-z]+:\]\])/
- [ "(#{$2}{1,#{$1}})", :extract_plain ]
-
- # %[...]
- when /%\*?\[([^\]]*)\]/
- yes = $1
- if /^\^/.match(yes) then no = yes[1..-1] else no = '^' + yes end
- [ "([#{yes}]+)(?=[#{no}]|\\z)", :extract_plain ]
-
- # %5[...]
- when /%\*?(\d+)\[([^\]]*)\]/
- yes = $2
- w = $1
- [ "([#{yes}]{1,#{w}})", :extract_plain ]
-
- # %i
- when /%\*?i/
- [ "([-+]?(?:(?:0[0-7]+)|(?:0[Xx]#{h}+)|(?:[1-9]\\d*)))", :extract_integer ]
-
- # %5i
- when /%\*?(\d+)i/
- n = $1.to_i
- s = "("
- if n > 1 then s += "[1-9]\\d{1,#{n-1}}|" end
- if n > 1 then s += "0[0-7]{1,#{n-1}}|" end
- if n > 2 then s += "[-+]0[0-7]{1,#{n-2}}|" end
- if n > 2 then s += "[-+][1-9]\\d{1,#{n-2}}|" end
- if n > 2 then s += "0[Xx]#{h}{1,#{n-2}}|" end
- if n > 3 then s += "[-+]0[Xx]#{h}{1,#{n-3}}|" end
- s += "\\d"
- s += ")"
- [ s, :extract_integer ]
-
- # %d, %u
- when /%\*?[du]/
- [ '([-+]?\d+)', :extract_decimal ]
-
- # %5d, %5u
- when /%\*?(\d+)[du]/
- n = $1.to_i
- s = "("
- if n > 1 then s += "[-+]\\d{1,#{n-1}}|" end
- s += "\\d{1,#{$1}})"
- [ s, :extract_decimal ]
-
- # %x
- when /%\*?[Xx]/
- [ "([-+]?(?:0[Xx])?#{h}+)", :extract_hex ]
-
- # %5x
- when /%\*?(\d+)[Xx]/
- n = $1.to_i
- s = "("
- if n > 3 then s += "[-+]0[Xx]#{h}{1,#{n-3}}|" end
- if n > 2 then s += "0[Xx]#{h}{1,#{n-2}}|" end
- if n > 1 then s += "[-+]#{h}{1,#{n-1}}|" end
- s += "#{h}{1,#{n}}"
- s += ")"
- [ s, :extract_hex ]
-
- # %o
- when /%\*?o/
- [ '([-+]?[0-7]+)', :extract_octal ]
-
- # %5o
- when /%\*?(\d+)o/
- [ "([-+][0-7]{1,#{$1.to_i-1}}|[0-7]{1,#{$1}})", :extract_octal ]
-
- # %f
- when /%\*?[aefgAEFG]/
- [ '([-+]?(?:0[xX](?:\.\h+|\h+(?:\.\h*)?)[pP][-+]\d+|\d+(?![\d.])|\d*\.\d*(?:[eE][-+]?\d+)?))', :extract_float ]
-
- # %5f
- when /%\*?(\d+)[aefgAEFG]/
- [ '(?=[-+]?(?:0[xX](?:\.\h+|\h+(?:\.\h*)?)[pP][-+]\d+|\d+(?![\d.])|\d*\.\d*(?:[eE][-+]?\d+)?))' +
- "(\\S{1,#{$1}})", :extract_float ]
-
- # %5s
- when /%\*?(\d+)s/
- [ "(\\S{1,#{$1}})", :extract_plain ]
-
- # %s
- when /%\*?s/
- [ '(\S+)', :extract_plain ]
-
- # %c
- when /\s%\*?c/
- [ "\\s*(.)", :extract_plain ]
-
- # %c
- when /%\*?c/
- [ "(.)", :extract_plain ]
-
- # %5c (whitespace issues are handled by the count_*_space? methods)
- when /%\*?(\d+)c/
- [ "(.{1,#{$1}})", :extract_plain ]
-
- # %%
- when /%%/
- [ '(\s*%)', :nil_proc ]
-
- # literal characters
- else
- [ "(#{Regexp.escape(@spec_string)})", :nil_proc ]
- end
-
- @re_string = '\A' + @re_string
- end
-
- def to_re
- Regexp.new(@re_string,Regexp::MULTILINE)
- end
-
- def match(str)
- @matched = false
- s = str.dup
- s.sub!(/\A\s+/,'') unless count_space?
- res = to_re.match(s)
- if res
- @conversion = send(@handler, res[1])
- @matched_string = @conversion.to_s
- @matched = true
- end
- res
- end
-
- def letter
- @spec_string[/%\*?\d*([a-z\[])/, 1]
- end
-
- def width
- w = @spec_string[/%\*?(\d+)/, 1]
- w && w.to_i
- end
-
- def mid_match?
- return false unless @matched
- cc_no_width = letter == '[' &&! width
- c_or_cc_width = (letter == 'c' || letter == '[') && width
- width_left = c_or_cc_width && (matched_string.size < width)
-
- return width_left || cc_no_width
- end
-
- end
-
- class FormatString
-
- attr_reader :string_left, :last_spec_tried,
- :last_match_tried, :matched_count, :space
-
- SPECIFIERS = 'diuXxofFeEgGscaA'
- REGEX = /
- # possible space, followed by...
- (?:\s*
- # percent sign, followed by...
- %
- # another percent sign, or...
- (?:%|
- # optional assignment suppression flag
- \*?
- # optional maximum field width
- \d*
- # named character class, ...
- (?:\[\[:\w+:\]\]|
- # traditional character class, or...
- \[[^\]]*\]|
- # specifier letter.
- [#{SPECIFIERS}])))|
- # or miscellaneous characters
- [^%\s]+/ix
-
- def initialize(str)
- @specs = []
- @i = 1
- s = str.to_s
- return unless /\S/.match(s)
- @space = true if /\s\z/.match(s)
- @specs.replace s.scan(REGEX).map {|spec| FormatSpecifier.new(spec) }
- end
-
- def to_s
- @specs.join('')
- end
-
- def prune(n=matched_count)
- n.times { @specs.shift }
- end
-
- def spec_count
- @specs.size
- end
-
- def last_spec
- @i == spec_count - 1
- end
-
- def match(str)
- accum = []
- @string_left = str
- @matched_count = 0
-
- @specs.each_with_index do |spec,i|
- @i=i
- @last_spec_tried = spec
- @last_match_tried = spec.match(@string_left)
- break unless @last_match_tried
- @matched_count += 1
-
- accum << spec.conversion
-
- @string_left = @last_match_tried.post_match
- break if @string_left.empty?
- end
- return accum.compact
- end
- end
- # :startdoc:
-end
-
-class IO
-
- #:stopdoc:
- # The trick here is doing a match where you grab one *line*
- # of input at a time. The linebreak may or may not occur
- # at the boundary where the string matches a format specifier.
- # And if it does, some rule about whitespace may or may not
- # be in effect...
- #
- # That's why this is much more elaborate than the string
- # version.
- #
- # For each line:
- #
- # Match succeeds (non-emptily)
- # and the last attempted spec/string sub-match succeeded:
- #
- # could the last spec keep matching?
- # yes: save interim results and continue (next line)
- #
- # The last attempted spec/string did not match:
- #
- # are we on the next-to-last spec in the string?
- # yes:
- # is fmt_string.string_left all spaces?
- # yes: does current spec care about input space?
- # yes: fatal failure
- # no: save interim results and continue
- # no: continue [this state could be analyzed further]
- #
- #:startdoc:
-
- # Scans the current string until the match is exhausted,
- # yielding each match as it is encountered in the string.
- # A block is not necessary though, as the results will simply
- # be aggregated into the final array.
- #
- # "123 456".block_scanf("%d")
- # # => [123, 456]
- #
- # If a block is given, the value from that is returned from
- # the yield is added to an output array.
- #
- # "123 456".block_scanf("%d) do |digit,| # the ',' unpacks the Array
- # digit + 100
- # end
- # # => [223, 556]
- #
- # See Scanf for details on creating a format string.
- #
- # You will need to require 'scanf' to use use IO#scanf.
- def scanf(str,&b) #:yield: current_match
- return block_scanf(str,&b) if b
- return [] unless str.size > 0
-
- start_position = pos rescue 0
- matched_so_far = 0
- source_buffer = ""
- result_buffer = []
- final_result = []
-
- fstr = Scanf::FormatString.new(str)
-
- loop do
- if eof || (tty? &&! fstr.match(source_buffer))
- final_result.concat(result_buffer)
- break
- end
-
- source_buffer << gets
-
- current_match = fstr.match(source_buffer)
-
- spec = fstr.last_spec_tried
-
- if spec.matched
- if spec.mid_match?
- result_buffer.replace(current_match)
- next
- end
-
- elsif (fstr.matched_count == fstr.spec_count - 1)
- if /\A\s*\z/.match(fstr.string_left)
- break if spec.count_space?
- result_buffer.replace(current_match)
- next
- end
- end
-
- final_result.concat(current_match)
-
- matched_so_far += source_buffer.size
- source_buffer.replace(fstr.string_left)
- matched_so_far -= source_buffer.size
- break if fstr.last_spec
- fstr.prune
- end
- seek(start_position + matched_so_far, IO::SEEK_SET) rescue Errno::ESPIPE
- soak_up_spaces if fstr.last_spec && fstr.space
-
- return final_result
- end
-
- private
-
- def soak_up_spaces
- c = getc
- ungetc(c) if c
- until eof ||! c || /\S/.match(c.chr)
- c = getc
- end
- ungetc(c) if (c && /\S/.match(c.chr))
- end
-
- def block_scanf(str)
- final = []
-# Sub-ideal, since another FS gets created in scanf.
-# But used here to determine the number of specifiers.
- fstr = Scanf::FormatString.new(str)
- last_spec = fstr.last_spec
- begin
- current = scanf(str)
- break if current.empty?
- final.push(yield(current))
- end until eof || fstr.last_spec_tried == last_spec
- return final
- end
-end
-
-class String
-
- # :section: scanf
- #
- # You will need to require 'scanf' to use these methods
-
- # Scans the current string. If a block is given, it
- # functions exactly like block_scanf.
- #
- # arr = "123 456".scanf("%d%d")
- # # => [123, 456]
- #
- # require 'pp'
- #
- # "this 123 read that 456 other".scanf("%s%d%s") {|m| pp m}
- #
- # # ["this", 123, "read"]
- # # ["that", 456, "other"]
- # # => [["this", 123, "read"], ["that", 456, "other"]]
- #
- # See Scanf for details on creating a format string.
- #
- # You will need to require 'scanf' to use String#scanf
- def scanf(fstr,&b) #:yield: current_match
- if b
- block_scanf(fstr,&b)
- else
- fs =
- if fstr.is_a? Scanf::FormatString
- fstr
- else
- Scanf::FormatString.new(fstr)
- end
- fs.match(self)
- end
- end
-
- # Scans the current string until the match is exhausted
- # yielding each match as it is encountered in the string.
- # A block is not necessary as the results will simply
- # be aggregated into the final array.
- #
- # "123 456".block_scanf("%d")
- # # => [123, 456]
- #
- # If a block is given, the value from that is returned from
- # the yield is added to an output array.
- #
- # "123 456".block_scanf("%d) do |digit,| # the ',' unpacks the Array
- # digit + 100
- # end
- # # => [223, 556]
- #
- # See Scanf for details on creating a format string.
- #
- # You will need to require 'scanf' to use String#block_scanf
- def block_scanf(fstr,&b) #:yield: current_match
- fs = Scanf::FormatString.new(fstr)
- str = self.dup
- final = []
- begin
- current = str.scanf(fs)
- final.push(yield(current)) unless current.empty?
- str = fs.string_left
- end until current.empty? || str.empty?
- return final
- end
-end
-
-module Kernel
- private
- # Scans STDIN for data matching +format+. See IO#scanf for details.
- #
- # See Scanf for details on creating a format string.
- #
- # You will need to require 'scanf' to use Kernel#scanf.
- def scanf(format, &b) #:doc:
- STDIN.scanf(format ,&b)
- end
-end
diff --git a/ruby_1_9_3/lib/securerandom.rb b/ruby_1_9_3/lib/securerandom.rb
deleted file mode 100644
index d4ab947f54..0000000000
--- a/ruby_1_9_3/lib/securerandom.rb
+++ /dev/null
@@ -1,265 +0,0 @@
-# = Secure random number generator interface.
-#
-# This library is an interface for secure random number generator which is
-# suitable for generating session key in HTTP cookies, etc.
-#
-# It supports following secure random number generators.
-#
-# * openssl
-# * /dev/urandom
-# * Win32
-#
-# == Example
-#
-# # random hexadecimal string.
-# p SecureRandom.hex(10) #=> "52750b30ffbc7de3b362"
-# p SecureRandom.hex(10) #=> "92b15d6c8dc4beb5f559"
-# p SecureRandom.hex(11) #=> "6aca1b5c58e4863e6b81b8"
-# p SecureRandom.hex(12) #=> "94b2fff3e7fd9b9c391a2306"
-# p SecureRandom.hex(13) #=> "39b290146bea6ce975c37cfc23"
-# ...
-#
-# # random base64 string.
-# p SecureRandom.base64(10) #=> "EcmTPZwWRAozdA=="
-# p SecureRandom.base64(10) #=> "9b0nsevdwNuM/w=="
-# p SecureRandom.base64(10) #=> "KO1nIU+p9DKxGg=="
-# p SecureRandom.base64(11) #=> "l7XEiFja+8EKEtY="
-# p SecureRandom.base64(12) #=> "7kJSM/MzBJI+75j8"
-# p SecureRandom.base64(13) #=> "vKLJ0tXBHqQOuIcSIg=="
-# ...
-#
-# # random binary string.
-# p SecureRandom.random_bytes(10) #=> "\016\t{\370g\310pbr\301"
-# p SecureRandom.random_bytes(10) #=> "\323U\030TO\234\357\020\a\337"
-# ...
-
-begin
- require 'openssl'
-rescue LoadError
-end
-
-module SecureRandom
- # SecureRandom.random_bytes generates a random binary string.
- #
- # The argument _n_ specifies the length of the result string.
- #
- # If _n_ is not specified, 16 is assumed.
- # It may be larger in future.
- #
- # The result may contain any byte: "\x00" - "\xff".
- #
- # p SecureRandom.random_bytes #=> "\xD8\\\xE0\xF4\r\xB2\xFC*WM\xFF\x83\x18\xF45\xB6"
- # p SecureRandom.random_bytes #=> "m\xDC\xFC/\a\x00Uf\xB2\xB2P\xBD\xFF6S\x97"
- #
- # If secure random number generator is not available,
- # NotImplementedError is raised.
- def self.random_bytes(n=nil)
- n = n ? n.to_int : 16
-
- if defined? OpenSSL::Random
- @pid = 0 if !defined?(@pid)
- pid = $$
- if @pid != pid
- now = Time.now
- ary = [now.to_i, now.nsec, @pid, pid]
- OpenSSL::Random.seed(ary.to_s)
- @pid = pid
- end
- return OpenSSL::Random.random_bytes(n)
- end
-
- if !defined?(@has_urandom) || @has_urandom
- flags = File::RDONLY
- flags |= File::NONBLOCK if defined? File::NONBLOCK
- flags |= File::NOCTTY if defined? File::NOCTTY
- begin
- File.open("/dev/urandom", flags) {|f|
- unless f.stat.chardev?
- raise Errno::ENOENT
- end
- @has_urandom = true
- ret = f.readpartial(n)
- if ret.length != n
- raise NotImplementedError, "Unexpected partial read from random device: only #{ret.length} for #{n} bytes"
- end
- return ret
- }
- rescue Errno::ENOENT
- @has_urandom = false
- end
- end
-
- if !defined?(@has_win32)
- begin
- require 'Win32API'
-
- crypt_acquire_context = Win32API.new("advapi32", "CryptAcquireContext", 'PPPII', 'L')
- @crypt_gen_random = Win32API.new("advapi32", "CryptGenRandom", 'LIP', 'L')
-
- hProvStr = " " * 4
- prov_rsa_full = 1
- crypt_verifycontext = 0xF0000000
-
- if crypt_acquire_context.call(hProvStr, nil, nil, prov_rsa_full, crypt_verifycontext) == 0
- raise SystemCallError, "CryptAcquireContext failed: #{lastWin32ErrorMessage}"
- end
- @hProv, = hProvStr.unpack('L')
-
- @has_win32 = true
- rescue LoadError
- @has_win32 = false
- end
- end
- if @has_win32
- bytes = " ".force_encoding("ASCII-8BIT") * n
- if @crypt_gen_random.call(@hProv, bytes.size, bytes) == 0
- raise SystemCallError, "CryptGenRandom failed: #{lastWin32ErrorMessage}"
- end
- return bytes
- end
-
- raise NotImplementedError, "No random device"
- end
-
- # SecureRandom.hex generates a random hex string.
- #
- # The argument _n_ specifies the length of the random length.
- # The length of the result string is twice of _n_.
- #
- # If _n_ is not specified, 16 is assumed.
- # It may be larger in future.
- #
- # The result may contain 0-9 and a-f.
- #
- # p SecureRandom.hex #=> "eb693ec8252cd630102fd0d0fb7c3485"
- # p SecureRandom.hex #=> "91dc3bfb4de5b11d029d376634589b61"
- #
- # If secure random number generator is not available,
- # NotImplementedError is raised.
- def self.hex(n=nil)
- random_bytes(n).unpack("H*")[0]
- end
-
- # SecureRandom.base64 generates a random base64 string.
- #
- # The argument _n_ specifies the length of the random length.
- # The length of the result string is about 4/3 of _n_.
- #
- # If _n_ is not specified, 16 is assumed.
- # It may be larger in future.
- #
- # The result may contain A-Z, a-z, 0-9, "+", "/" and "=".
- #
- # p SecureRandom.base64 #=> "/2BuBuLf3+WfSKyQbRcc/A=="
- # p SecureRandom.base64 #=> "6BbW0pxO0YENxn38HMUbcQ=="
- #
- # If secure random number generator is not available,
- # NotImplementedError is raised.
- #
- # See RFC 3548 for the definition of base64.
- def self.base64(n=nil)
- [random_bytes(n)].pack("m*").delete("\n")
- end
-
- # SecureRandom.urlsafe_base64 generates a random URL-safe base64 string.
- #
- # The argument _n_ specifies the length of the random length.
- # The length of the result string is about 4/3 of _n_.
- #
- # If _n_ is not specified, 16 is assumed.
- # It may be larger in future.
- #
- # The boolean argument _padding_ specifies the padding.
- # If it is false or nil, padding is not generated.
- # Otherwise padding is generated.
- # By default, padding is not generated because "=" may be used as a URL delimiter.
- #
- # The result may contain A-Z, a-z, 0-9, "-" and "_".
- # "=" is also used if _padding_ is true.
- #
- # p SecureRandom.urlsafe_base64 #=> "b4GOKm4pOYU_-BOXcrUGDg"
- # p SecureRandom.urlsafe_base64 #=> "UZLdOkzop70Ddx-IJR0ABg"
- #
- # p SecureRandom.urlsafe_base64(nil, true) #=> "i0XQ-7gglIsHGV2_BNPrdQ=="
- # p SecureRandom.urlsafe_base64(nil, true) #=> "-M8rLhr7JEpJlqFGUMmOxg=="
- #
- # If secure random number generator is not available,
- # NotImplementedError is raised.
- #
- # See RFC 3548 for the definition of URL-safe base64.
- def self.urlsafe_base64(n=nil, padding=false)
- s = [random_bytes(n)].pack("m*")
- s.delete!("\n")
- s.tr!("+/", "-_")
- s.delete!("=") if !padding
- s
- end
-
- # SecureRandom.random_number generates a random number.
- #
- # If a positive integer is given as _n_,
- # SecureRandom.random_number returns an integer:
- # 0 <= SecureRandom.random_number(n) < n.
- #
- # p SecureRandom.random_number(100) #=> 15
- # p SecureRandom.random_number(100) #=> 88
- #
- # If 0 is given or an argument is not given,
- # SecureRandom.random_number returns a float:
- # 0.0 <= SecureRandom.random_number() < 1.0.
- #
- # p SecureRandom.random_number #=> 0.596506046187744
- # p SecureRandom.random_number #=> 0.350621695741409
- #
- def self.random_number(n=0)
- if 0 < n
- hex = n.to_s(16)
- hex = '0' + hex if (hex.length & 1) == 1
- bin = [hex].pack("H*")
- mask = bin[0].ord
- mask |= mask >> 1
- mask |= mask >> 2
- mask |= mask >> 4
- begin
- rnd = SecureRandom.random_bytes(bin.length)
- rnd[0] = (rnd[0].ord & mask).chr
- end until rnd < bin
- rnd.unpack("H*")[0].hex
- else
- # assumption: Float::MANT_DIG <= 64
- i64 = SecureRandom.random_bytes(8).unpack("Q")[0]
- Math.ldexp(i64 >> (64-Float::MANT_DIG), -Float::MANT_DIG)
- end
- end
-
- # SecureRandom.uuid generates a v4 random UUID (Universally Unique IDentifier).
- #
- # p SecureRandom.uuid #=> "2d931510-d99f-494a-8c67-87feb05e1594"
- # p SecureRandom.uuid #=> "bad85eb9-0713-4da7-8d36-07a8e4b00eab"
- # p SecureRandom.uuid #=> "62936e70-1815-439b-bf89-8492855a7e6b"
- #
- # The version 4 UUID is purely random (except the version).
- # It doesn't contain meaningful information such as MAC address, time, etc.
- #
- # See RFC 4122 for details of UUID.
- #
- def self.uuid
- ary = self.random_bytes(16).unpack("NnnnnN")
- ary[2] = (ary[2] & 0x0fff) | 0x4000
- ary[3] = (ary[3] & 0x3fff) | 0x8000
- "%08x-%04x-%04x-%04x-%04x%08x" % ary
- end
-
- # Following code is based on David Garamond's GUID library for Ruby.
- def self.lastWin32ErrorMessage # :nodoc:
- get_last_error = Win32API.new("kernel32", "GetLastError", '', 'L')
- format_message = Win32API.new("kernel32", "FormatMessageA", 'LPLLPLPPPPPPPP', 'L')
- format_message_ignore_inserts = 0x00000200
- format_message_from_system = 0x00001000
-
- code = get_last_error.call
- msg = "\0" * 1024
- len = format_message.call(format_message_ignore_inserts + format_message_from_system, 0, code, 0, msg, 1024, nil, nil, nil, nil, nil, nil, nil, nil)
- msg[0, len].tr("\r", '').chomp
- end
-end
diff --git a/ruby_1_9_3/lib/set.rb b/ruby_1_9_3/lib/set.rb
deleted file mode 100755
index 07031bf894..0000000000
--- a/ruby_1_9_3/lib/set.rb
+++ /dev/null
@@ -1,1352 +0,0 @@
-#!/usr/bin/env ruby
-#--
-# set.rb - defines the Set class
-#++
-# Copyright (c) 2002-2008 Akinori MUSHA <knu@iDaemons.org>
-#
-# Documentation by Akinori MUSHA and Gavin Sinclair.
-#
-# All rights reserved. You can redistribute and/or modify it under the same
-# terms as Ruby.
-#
-# $Id$
-#
-# == Overview
-#
-# This library provides the Set class, which deals with a collection
-# of unordered values with no duplicates. It is a hybrid of Array's
-# intuitive inter-operation facilities and Hash's fast lookup. If you
-# need to keep values ordered, use the SortedSet class.
-#
-# The method +to_set+ is added to Enumerable for convenience.
-#
-# See the Set and SortedSet documentation for examples of usage.
-
-
-#
-# Set implements a collection of unordered values with no duplicates.
-# This is a hybrid of Array's intuitive inter-operation facilities and
-# Hash's fast lookup.
-#
-# The equality of each couple of elements is determined according to
-# Object#eql? and Object#hash, since Set uses Hash as storage.
-#
-# Set is easy to use with Enumerable objects (implementing +each+).
-# Most of the initializer methods and binary operators accept generic
-# Enumerable objects besides sets and arrays. An Enumerable object
-# can be converted to Set using the +to_set+ method.
-#
-# == Example
-#
-# require 'set'
-# s1 = Set.new [1, 2] # -> #<Set: {1, 2}>
-# s2 = [1, 2].to_set # -> #<Set: {1, 2}>
-# s1 == s2 # -> true
-# s1.add("foo") # -> #<Set: {1, 2, "foo"}>
-# s1.merge([2, 6]) # -> #<Set: {6, 1, 2, "foo"}>
-# s1.subset? s2 # -> false
-# s2.subset? s1 # -> true
-#
-# == Contact
-#
-# - Akinori MUSHA <knu@iDaemons.org> (current maintainer)
-#
-class Set
- include Enumerable
-
- # Creates a new set containing the given objects.
- def self.[](*ary)
- new(ary)
- end
-
- # Creates a new set containing the elements of the given enumerable
- # object.
- #
- # If a block is given, the elements of enum are preprocessed by the
- # given block.
- def initialize(enum = nil, &block) # :yields: o
- @hash ||= Hash.new
-
- enum.nil? and return
-
- if block
- do_with_enum(enum) { |o| add(block[o]) }
- else
- merge(enum)
- end
- end
-
- def do_with_enum(enum, &block) # :nodoc:
- if enum.respond_to?(:each_entry)
- enum.each_entry(&block)
- elsif enum.respond_to?(:each)
- enum.each(&block)
- else
- raise ArgumentError, "value must be enumerable"
- end
- end
- private :do_with_enum
-
- # Copy internal hash.
- def initialize_copy(orig)
- @hash = orig.instance_eval{@hash}.dup
- end
-
- def freeze # :nodoc:
- super
- @hash.freeze
- self
- end
-
- def taint # :nodoc:
- super
- @hash.taint
- self
- end
-
- def untaint # :nodoc:
- super
- @hash.untaint
- self
- end
-
- # Returns the number of elements.
- def size
- @hash.size
- end
- alias length size
-
- # Returns true if the set contains no elements.
- def empty?
- @hash.empty?
- end
-
- # Removes all elements and returns self.
- def clear
- @hash.clear
- self
- end
-
- # Replaces the contents of the set with the contents of the given
- # enumerable object and returns self.
- def replace(enum)
- if enum.instance_of?(self.class)
- @hash.replace(enum.instance_variable_get(:@hash))
- else
- clear
- merge(enum)
- end
-
- self
- end
-
- # Converts the set to an array. The order of elements is uncertain.
- def to_a
- @hash.keys
- end
-
- def flatten_merge(set, seen = Set.new) # :nodoc:
- set.each { |e|
- if e.is_a?(Set)
- if seen.include?(e_id = e.object_id)
- raise ArgumentError, "tried to flatten recursive Set"
- end
-
- seen.add(e_id)
- flatten_merge(e, seen)
- seen.delete(e_id)
- else
- add(e)
- end
- }
-
- self
- end
- protected :flatten_merge
-
- # Returns a new set that is a copy of the set, flattening each
- # containing set recursively.
- def flatten
- self.class.new.flatten_merge(self)
- end
-
- # Equivalent to Set#flatten, but replaces the receiver with the
- # result in place. Returns nil if no modifications were made.
- def flatten!
- if detect { |e| e.is_a?(Set) }
- replace(flatten())
- else
- nil
- end
- end
-
- # Returns true if the set contains the given object.
- def include?(o)
- @hash.include?(o)
- end
- alias member? include?
-
- # Returns true if the set is a superset of the given set.
- def superset?(set)
- set.is_a?(Set) or raise ArgumentError, "value must be a set"
- return false if size < set.size
- set.all? { |o| include?(o) }
- end
-
- # Returns true if the set is a proper superset of the given set.
- def proper_superset?(set)
- set.is_a?(Set) or raise ArgumentError, "value must be a set"
- return false if size <= set.size
- set.all? { |o| include?(o) }
- end
-
- # Returns true if the set is a subset of the given set.
- def subset?(set)
- set.is_a?(Set) or raise ArgumentError, "value must be a set"
- return false if set.size < size
- all? { |o| set.include?(o) }
- end
-
- # Returns true if the set is a proper subset of the given set.
- def proper_subset?(set)
- set.is_a?(Set) or raise ArgumentError, "value must be a set"
- return false if set.size <= size
- all? { |o| set.include?(o) }
- end
-
- # Calls the given block once for each element in the set, passing
- # the element as parameter. Returns an enumerator if no block is
- # given.
- def each
- block_given? or return enum_for(__method__)
- @hash.each_key { |o| yield(o) }
- self
- end
-
- # Adds the given object to the set and returns self. Use +merge+ to
- # add many elements at once.
- def add(o)
- @hash[o] = true
- self
- end
- alias << add
-
- # Adds the given object to the set and returns self. If the
- # object is already in the set, returns nil.
- def add?(o)
- if include?(o)
- nil
- else
- add(o)
- end
- end
-
- # Deletes the given object from the set and returns self. Use +subtract+ to
- # delete many items at once.
- def delete(o)
- @hash.delete(o)
- self
- end
-
- # Deletes the given object from the set and returns self. If the
- # object is not in the set, returns nil.
- def delete?(o)
- if include?(o)
- delete(o)
- else
- nil
- end
- end
-
- # Deletes every element of the set for which block evaluates to
- # true, and returns self.
- def delete_if
- block_given? or return enum_for(__method__)
- to_a.each { |o| @hash.delete(o) if yield(o) }
- self
- end
-
- # Deletes every element of the set for which block evaluates to
- # false, and returns self.
- def keep_if
- block_given? or return enum_for(__method__)
- to_a.each { |o| @hash.delete(o) unless yield(o) }
- self
- end
-
- # Replaces the elements with ones returned by collect().
- def collect!
- block_given? or return enum_for(__method__)
- set = self.class.new
- each { |o| set << yield(o) }
- replace(set)
- end
- alias map! collect!
-
- # Equivalent to Set#delete_if, but returns nil if no changes were
- # made.
- def reject!
- block_given? or return enum_for(__method__)
- n = size
- delete_if { |o| yield(o) }
- size == n ? nil : self
- end
-
- # Equivalent to Set#keep_if, but returns nil if no changes were
- # made.
- def select!
- block_given? or return enum_for(__method__)
- n = size
- keep_if { |o| yield(o) }
- size == n ? nil : self
- end
-
- # Merges the elements of the given enumerable object to the set and
- # returns self.
- def merge(enum)
- if enum.instance_of?(self.class)
- @hash.update(enum.instance_variable_get(:@hash))
- else
- do_with_enum(enum) { |o| add(o) }
- end
-
- self
- end
-
- # Deletes every element that appears in the given enumerable object
- # and returns self.
- def subtract(enum)
- do_with_enum(enum) { |o| delete(o) }
- self
- end
-
- # Returns a new set built by merging the set and the elements of the
- # given enumerable object.
- def |(enum)
- dup.merge(enum)
- end
- alias + | ##
- alias union | ##
-
- # Returns a new set built by duplicating the set, removing every
- # element that appears in the given enumerable object.
- def -(enum)
- dup.subtract(enum)
- end
- alias difference - ##
-
- # Returns a new set containing elements common to the set and the
- # given enumerable object.
- def &(enum)
- n = self.class.new
- do_with_enum(enum) { |o| n.add(o) if include?(o) }
- n
- end
- alias intersection & ##
-
- # Returns a new set containing elements exclusive between the set
- # and the given enumerable object. (set ^ enum) is equivalent to
- # ((set | enum) - (set & enum)).
- def ^(enum)
- n = Set.new(enum)
- each { |o| if n.include?(o) then n.delete(o) else n.add(o) end }
- n
- end
-
- # Returns true if two sets are equal. The equality of each couple
- # of elements is defined according to Object#eql?.
- def ==(other)
- if self.equal?(other)
- true
- elsif other.instance_of?(self.class)
- @hash == other.instance_variable_get(:@hash)
- elsif other.is_a?(Set) && self.size == other.size
- other.all? { |o| @hash.include?(o) }
- else
- false
- end
- end
-
- def hash # :nodoc:
- @hash.hash
- end
-
- def eql?(o) # :nodoc:
- return false unless o.is_a?(Set)
- @hash.eql?(o.instance_eval{@hash})
- end
-
- # Classifies the set by the return value of the given block and
- # returns a hash of {value => set of elements} pairs. The block is
- # called once for each element of the set, passing the element as
- # parameter.
- #
- # e.g.:
- #
- # require 'set'
- # files = Set.new(Dir.glob("*.rb"))
- # hash = files.classify { |f| File.mtime(f).year }
- # p hash # => {2000=>#<Set: {"a.rb", "b.rb"}>,
- # # 2001=>#<Set: {"c.rb", "d.rb", "e.rb"}>,
- # # 2002=>#<Set: {"f.rb"}>}
- def classify # :yields: o
- block_given? or return enum_for(__method__)
-
- h = {}
-
- each { |i|
- x = yield(i)
- (h[x] ||= self.class.new).add(i)
- }
-
- h
- end
-
- # Divides the set into a set of subsets according to the commonality
- # defined by the given block.
- #
- # If the arity of the block is 2, elements o1 and o2 are in common
- # if block.call(o1, o2) is true. Otherwise, elements o1 and o2 are
- # in common if block.call(o1) == block.call(o2).
- #
- # e.g.:
- #
- # require 'set'
- # numbers = Set[1, 3, 4, 6, 9, 10, 11]
- # set = numbers.divide { |i,j| (i - j).abs == 1 }
- # p set # => #<Set: {#<Set: {1}>,
- # # #<Set: {11, 9, 10}>,
- # # #<Set: {3, 4}>,
- # # #<Set: {6}>}>
- def divide(&func)
- func or return enum_for(__method__)
-
- if func.arity == 2
- require 'tsort'
-
- class << dig = {} # :nodoc:
- include TSort
-
- alias tsort_each_node each_key
- def tsort_each_child(node, &block)
- fetch(node).each(&block)
- end
- end
-
- each { |u|
- dig[u] = a = []
- each{ |v| func.call(u, v) and a << v }
- }
-
- set = Set.new()
- dig.each_strongly_connected_component { |css|
- set.add(self.class.new(css))
- }
- set
- else
- Set.new(classify(&func).values)
- end
- end
-
- InspectKey = :__inspect_key__ # :nodoc:
-
- # Returns a string containing a human-readable representation of the
- # set. ("#<Set: {element1, element2, ...}>")
- def inspect
- ids = (Thread.current[InspectKey] ||= [])
-
- if ids.include?(object_id)
- return sprintf('#<%s: {...}>', self.class.name)
- end
-
- begin
- ids << object_id
- return sprintf('#<%s: {%s}>', self.class, to_a.inspect[1..-2])
- ensure
- ids.pop
- end
- end
-
- def pretty_print(pp) # :nodoc:
- pp.text sprintf('#<%s: {', self.class.name)
- pp.nest(1) {
- pp.seplist(self) { |o|
- pp.pp o
- }
- }
- pp.text "}>"
- end
-
- def pretty_print_cycle(pp) # :nodoc:
- pp.text sprintf('#<%s: {%s}>', self.class.name, empty? ? '' : '...')
- end
-end
-
-#
-# SortedSet implements a Set that guarantees that it's element are
-# yielded in sorted order (according to the return values of their
-# #<=> methods) when iterating over them.
-#
-# All elements that are added to a SortedSet must respond to the <=>
-# method for comparison.
-#
-# Also, all elements must be <em>mutually comparable</em>: <tt>el1 <=>
-# el2</tt> must not return <tt>nil</tt> for any elements <tt>el1</tt>
-# and <tt>el2</tt>, else an ArgumentError will be raised when
-# iterating over the SortedSet.
-#
-# == Example
-#
-# require "set"
-#
-# set = SortedSet.new([2, 1, 5, 6, 4, 5, 3, 3, 3])
-# ary = []
-#
-# set.each do |obj|
-# ary << obj
-# end
-#
-# p ary # => [1, 2, 3, 4, 5, 6]
-#
-# set2 = SortedSet.new([1, 2, "3"])
-# set2.each { |obj| } # => raises ArgumentError: comparison of Fixnum with String failed
-#
-class SortedSet < Set
- @@setup = false
-
- class << self
- def [](*ary) # :nodoc:
- new(ary)
- end
-
- def setup # :nodoc:
- @@setup and return
-
- module_eval {
- # a hack to shut up warning
- alias old_init initialize
- }
- begin
- require 'rbtree'
-
- module_eval %{
- def initialize(*args, &block)
- @hash = RBTree.new
- super
- end
-
- def add(o)
- o.respond_to?(:<=>) or raise ArgumentError, "value must respond to <=>"
- super
- end
- alias << add
- }
- rescue LoadError
- module_eval %{
- def initialize(*args, &block)
- @keys = nil
- super
- end
-
- def clear
- @keys = nil
- super
- end
-
- def replace(enum)
- @keys = nil
- super
- end
-
- def add(o)
- o.respond_to?(:<=>) or raise ArgumentError, "value must respond to <=>"
- @keys = nil
- super
- end
- alias << add
-
- def delete(o)
- @keys = nil
- @hash.delete(o)
- self
- end
-
- def delete_if
- block_given? or return enum_for(__method__)
- n = @hash.size
- super
- @keys = nil if @hash.size != n
- self
- end
-
- def keep_if
- block_given? or return enum_for(__method__)
- n = @hash.size
- super
- @keys = nil if @hash.size != n
- self
- end
-
- def merge(enum)
- @keys = nil
- super
- end
-
- def each
- block_given? or return enum_for(__method__)
- to_a.each { |o| yield(o) }
- self
- end
-
- def to_a
- (@keys = @hash.keys).sort! unless @keys
- @keys
- end
- }
- end
- module_eval {
- # a hack to shut up warning
- remove_method :old_init
- }
-
- @@setup = true
- end
- end
-
- def initialize(*args, &block) # :nodoc:
- SortedSet.setup
- initialize(*args, &block)
- end
-end
-
-module Enumerable
- # Makes a set from the enumerable object with given arguments.
- # Needs to +require "set"+ to use this method.
- def to_set(klass = Set, *args, &block)
- klass.new(self, *args, &block)
- end
-end
-
-# =begin
-# == RestricedSet class
-# RestricedSet implements a set with restrictions defined by a given
-# block.
-#
-# === Super class
-# Set
-#
-# === Class Methods
-# --- RestricedSet::new(enum = nil) { |o| ... }
-# --- RestricedSet::new(enum = nil) { |rset, o| ... }
-# Creates a new restricted set containing the elements of the given
-# enumerable object. Restrictions are defined by the given block.
-#
-# If the block's arity is 2, it is called with the RestrictedSet
-# itself and an object to see if the object is allowed to be put in
-# the set.
-#
-# Otherwise, the block is called with an object to see if the object
-# is allowed to be put in the set.
-#
-# === Instance Methods
-# --- restriction_proc
-# Returns the restriction procedure of the set.
-#
-# =end
-#
-# class RestricedSet < Set
-# def initialize(*args, &block)
-# @proc = block or raise ArgumentError, "missing a block"
-#
-# if @proc.arity == 2
-# instance_eval %{
-# def add(o)
-# @hash[o] = true if @proc.call(self, o)
-# self
-# end
-# alias << add
-#
-# def add?(o)
-# if include?(o) || !@proc.call(self, o)
-# nil
-# else
-# @hash[o] = true
-# self
-# end
-# end
-#
-# def replace(enum)
-# enum.respond_to?(:each) or raise ArgumentError, "value must be enumerable"
-# clear
-# enum.each_entry { |o| add(o) }
-#
-# self
-# end
-#
-# def merge(enum)
-# enum.respond_to?(:each) or raise ArgumentError, "value must be enumerable"
-# enum.each_entry { |o| add(o) }
-#
-# self
-# end
-# }
-# else
-# instance_eval %{
-# def add(o)
-# if @proc.call(o)
-# @hash[o] = true
-# end
-# self
-# end
-# alias << add
-#
-# def add?(o)
-# if include?(o) || !@proc.call(o)
-# nil
-# else
-# @hash[o] = true
-# self
-# end
-# end
-# }
-# end
-#
-# super(*args)
-# end
-#
-# def restriction_proc
-# @proc
-# end
-# end
-
-if $0 == __FILE__
- eval DATA.read, nil, $0, __LINE__+4
-end
-
-__END__
-
-require 'test/unit'
-
-class TC_Set < Test::Unit::TestCase
- def test_aref
- assert_nothing_raised {
- Set[]
- Set[nil]
- Set[1,2,3]
- }
-
- assert_equal(0, Set[].size)
- assert_equal(1, Set[nil].size)
- assert_equal(1, Set[[]].size)
- assert_equal(1, Set[[nil]].size)
-
- set = Set[2,4,6,4]
- assert_equal(Set.new([2,4,6]), set)
- end
-
- def test_s_new
- assert_nothing_raised {
- Set.new()
- Set.new(nil)
- Set.new([])
- Set.new([1,2])
- Set.new('a'..'c')
- }
- assert_raises(ArgumentError) {
- Set.new(false)
- }
- assert_raises(ArgumentError) {
- Set.new(1)
- }
- assert_raises(ArgumentError) {
- Set.new(1,2)
- }
-
- assert_equal(0, Set.new().size)
- assert_equal(0, Set.new(nil).size)
- assert_equal(0, Set.new([]).size)
- assert_equal(1, Set.new([nil]).size)
-
- ary = [2,4,6,4]
- set = Set.new(ary)
- ary.clear
- assert_equal(false, set.empty?)
- assert_equal(3, set.size)
-
- ary = [1,2,3]
-
- s = Set.new(ary) { |o| o * 2 }
- assert_equal([2,4,6], s.sort)
- end
-
- def test_clone
- set1 = Set.new
- set2 = set1.clone
- set1 << 'abc'
- assert_equal(Set.new, set2)
- end
-
- def test_dup
- set1 = Set[1,2]
- set2 = set1.dup
-
- assert_not_same(set1, set2)
-
- assert_equal(set1, set2)
-
- set1.add(3)
-
- assert_not_equal(set1, set2)
- end
-
- def test_size
- assert_equal(0, Set[].size)
- assert_equal(2, Set[1,2].size)
- assert_equal(2, Set[1,2,1].size)
- end
-
- def test_empty?
- assert_equal(true, Set[].empty?)
- assert_equal(false, Set[1, 2].empty?)
- end
-
- def test_clear
- set = Set[1,2]
- ret = set.clear
-
- assert_same(set, ret)
- assert_equal(true, set.empty?)
- end
-
- def test_replace
- set = Set[1,2]
- ret = set.replace('a'..'c')
-
- assert_same(set, ret)
- assert_equal(Set['a','b','c'], set)
- end
-
- def test_to_a
- set = Set[1,2,3,2]
- ary = set.to_a
-
- assert_equal([1,2,3], ary.sort)
- end
-
- def test_flatten
- # test1
- set1 = Set[
- 1,
- Set[
- 5,
- Set[7,
- Set[0]
- ],
- Set[6,2],
- 1
- ],
- 3,
- Set[3,4]
- ]
-
- set2 = set1.flatten
- set3 = Set.new(0..7)
-
- assert_not_same(set2, set1)
- assert_equal(set3, set2)
-
- # test2; destructive
- orig_set1 = set1
- set1.flatten!
-
- assert_same(orig_set1, set1)
- assert_equal(set3, set1)
-
- # test3; multiple occurrences of a set in an set
- set1 = Set[1, 2]
- set2 = Set[set1, Set[set1, 4], 3]
-
- assert_nothing_raised {
- set2.flatten!
- }
-
- assert_equal(Set.new(1..4), set2)
-
- # test4; recursion
- set2 = Set[]
- set1 = Set[1, set2]
- set2.add(set1)
-
- assert_raises(ArgumentError) {
- set1.flatten!
- }
-
- # test5; miscellaneous
- empty = Set[]
- set = Set[Set[empty, "a"],Set[empty, "b"]]
-
- assert_nothing_raised {
- set.flatten
- }
-
- set1 = empty.merge(Set["no_more", set])
-
- assert_nil(Set.new(0..31).flatten!)
-
- x = Set[Set[],Set[1,2]].flatten!
- y = Set[1,2]
-
- assert_equal(x, y)
- end
-
- def test_include?
- set = Set[1,2,3]
-
- assert_equal(true, set.include?(1))
- assert_equal(true, set.include?(2))
- assert_equal(true, set.include?(3))
- assert_equal(false, set.include?(0))
- assert_equal(false, set.include?(nil))
-
- set = Set["1",nil,"2",nil,"0","1",false]
- assert_equal(true, set.include?(nil))
- assert_equal(true, set.include?(false))
- assert_equal(true, set.include?("1"))
- assert_equal(false, set.include?(0))
- assert_equal(false, set.include?(true))
- end
-
- def test_superset?
- set = Set[1,2,3]
-
- assert_raises(ArgumentError) {
- set.superset?()
- }
-
- assert_raises(ArgumentError) {
- set.superset?(2)
- }
-
- assert_raises(ArgumentError) {
- set.superset?([2])
- }
-
- assert_equal(true, set.superset?(Set[]))
- assert_equal(true, set.superset?(Set[1,2]))
- assert_equal(true, set.superset?(Set[1,2,3]))
- assert_equal(false, set.superset?(Set[1,2,3,4]))
- assert_equal(false, set.superset?(Set[1,4]))
-
- assert_equal(true, Set[].superset?(Set[]))
- end
-
- def test_proper_superset?
- set = Set[1,2,3]
-
- assert_raises(ArgumentError) {
- set.proper_superset?()
- }
-
- assert_raises(ArgumentError) {
- set.proper_superset?(2)
- }
-
- assert_raises(ArgumentError) {
- set.proper_superset?([2])
- }
-
- assert_equal(true, set.proper_superset?(Set[]))
- assert_equal(true, set.proper_superset?(Set[1,2]))
- assert_equal(false, set.proper_superset?(Set[1,2,3]))
- assert_equal(false, set.proper_superset?(Set[1,2,3,4]))
- assert_equal(false, set.proper_superset?(Set[1,4]))
-
- assert_equal(false, Set[].proper_superset?(Set[]))
- end
-
- def test_subset?
- set = Set[1,2,3]
-
- assert_raises(ArgumentError) {
- set.subset?()
- }
-
- assert_raises(ArgumentError) {
- set.subset?(2)
- }
-
- assert_raises(ArgumentError) {
- set.subset?([2])
- }
-
- assert_equal(true, set.subset?(Set[1,2,3,4]))
- assert_equal(true, set.subset?(Set[1,2,3]))
- assert_equal(false, set.subset?(Set[1,2]))
- assert_equal(false, set.subset?(Set[]))
-
- assert_equal(true, Set[].subset?(Set[1]))
- assert_equal(true, Set[].subset?(Set[]))
- end
-
- def test_proper_subset?
- set = Set[1,2,3]
-
- assert_raises(ArgumentError) {
- set.proper_subset?()
- }
-
- assert_raises(ArgumentError) {
- set.proper_subset?(2)
- }
-
- assert_raises(ArgumentError) {
- set.proper_subset?([2])
- }
-
- assert_equal(true, set.proper_subset?(Set[1,2,3,4]))
- assert_equal(false, set.proper_subset?(Set[1,2,3]))
- assert_equal(false, set.proper_subset?(Set[1,2]))
- assert_equal(false, set.proper_subset?(Set[]))
-
- assert_equal(false, Set[].proper_subset?(Set[]))
- end
-
- def test_each
- ary = [1,3,5,7,10,20]
- set = Set.new(ary)
-
- ret = set.each { |o| }
- assert_same(set, ret)
-
- e = set.each
- assert_instance_of(Enumerator, e)
-
- assert_nothing_raised {
- set.each { |o|
- ary.delete(o) or raise "unexpected element: #{o}"
- }
-
- ary.empty? or raise "forgotten elements: #{ary.join(', ')}"
- }
- end
-
- def test_add
- set = Set[1,2,3]
-
- ret = set.add(2)
- assert_same(set, ret)
- assert_equal(Set[1,2,3], set)
-
- ret = set.add?(2)
- assert_nil(ret)
- assert_equal(Set[1,2,3], set)
-
- ret = set.add(4)
- assert_same(set, ret)
- assert_equal(Set[1,2,3,4], set)
-
- ret = set.add?(5)
- assert_same(set, ret)
- assert_equal(Set[1,2,3,4,5], set)
- end
-
- def test_delete
- set = Set[1,2,3]
-
- ret = set.delete(4)
- assert_same(set, ret)
- assert_equal(Set[1,2,3], set)
-
- ret = set.delete?(4)
- assert_nil(ret)
- assert_equal(Set[1,2,3], set)
-
- ret = set.delete(2)
- assert_equal(set, ret)
- assert_equal(Set[1,3], set)
-
- ret = set.delete?(1)
- assert_equal(set, ret)
- assert_equal(Set[3], set)
- end
-
- def test_delete_if
- set = Set.new(1..10)
- ret = set.delete_if { |i| i > 10 }
- assert_same(set, ret)
- assert_equal(Set.new(1..10), set)
-
- set = Set.new(1..10)
- ret = set.delete_if { |i| i % 3 == 0 }
- assert_same(set, ret)
- assert_equal(Set[1,2,4,5,7,8,10], set)
- end
-
- def test_collect!
- set = Set[1,2,3,'a','b','c',-1..1,2..4]
-
- ret = set.collect! { |i|
- case i
- when Numeric
- i * 2
- when String
- i.upcase
- else
- nil
- end
- }
-
- assert_same(set, ret)
- assert_equal(Set[2,4,6,'A','B','C',nil], set)
- end
-
- def test_reject!
- set = Set.new(1..10)
-
- ret = set.reject! { |i| i > 10 }
- assert_nil(ret)
- assert_equal(Set.new(1..10), set)
-
- ret = set.reject! { |i| i % 3 == 0 }
- assert_same(set, ret)
- assert_equal(Set[1,2,4,5,7,8,10], set)
- end
-
- def test_merge
- set = Set[1,2,3]
-
- ret = set.merge([2,4,6])
- assert_same(set, ret)
- assert_equal(Set[1,2,3,4,6], set)
- end
-
- def test_subtract
- set = Set[1,2,3]
-
- ret = set.subtract([2,4,6])
- assert_same(set, ret)
- assert_equal(Set[1,3], set)
- end
-
- def test_plus
- set = Set[1,2,3]
-
- ret = set + [2,4,6]
- assert_not_same(set, ret)
- assert_equal(Set[1,2,3,4,6], ret)
- end
-
- def test_minus
- set = Set[1,2,3]
-
- ret = set - [2,4,6]
- assert_not_same(set, ret)
- assert_equal(Set[1,3], ret)
- end
-
- def test_and
- set = Set[1,2,3,4]
-
- ret = set & [2,4,6]
- assert_not_same(set, ret)
- assert_equal(Set[2,4], ret)
- end
-
- def test_xor
- set = Set[1,2,3,4]
- ret = set ^ [2,4,5,5]
- assert_not_same(set, ret)
- assert_equal(Set[1,3,5], ret)
- end
-
- def test_eq
- set1 = Set[2,3,1]
- set2 = Set[1,2,3]
-
- assert_equal(set1, set1)
- assert_equal(set1, set2)
- assert_not_equal(Set[1], [1])
-
- set1 = Class.new(Set)["a", "b"]
- set2 = Set["a", "b", set1]
- set1 = set1.add(set1.clone)
-
-# assert_equal(set1, set2)
-# assert_equal(set2, set1)
- assert_equal(set2, set2.clone)
- assert_equal(set1.clone, set1)
-
- assert_not_equal(Set[Exception.new,nil], Set[Exception.new,Exception.new], "[ruby-dev:26127]")
- end
-
- # def test_hash
- # end
-
- # def test_eql?
- # end
-
- def test_classify
- set = Set.new(1..10)
- ret = set.classify { |i| i % 3 }
-
- assert_equal(3, ret.size)
- assert_instance_of(Hash, ret)
- ret.each_value { |value| assert_instance_of(Set, value) }
- assert_equal(Set[3,6,9], ret[0])
- assert_equal(Set[1,4,7,10], ret[1])
- assert_equal(Set[2,5,8], ret[2])
- end
-
- def test_divide
- set = Set.new(1..10)
- ret = set.divide { |i| i % 3 }
-
- assert_equal(3, ret.size)
- n = 0
- ret.each { |s| n += s.size }
- assert_equal(set.size, n)
- assert_equal(set, ret.flatten)
-
- set = Set[7,10,5,11,1,3,4,9,0]
- ret = set.divide { |a,b| (a - b).abs == 1 }
-
- assert_equal(4, ret.size)
- n = 0
- ret.each { |s| n += s.size }
- assert_equal(set.size, n)
- assert_equal(set, ret.flatten)
- ret.each { |s|
- if s.include?(0)
- assert_equal(Set[0,1], s)
- elsif s.include?(3)
- assert_equal(Set[3,4,5], s)
- elsif s.include?(7)
- assert_equal(Set[7], s)
- elsif s.include?(9)
- assert_equal(Set[9,10,11], s)
- else
- raise "unexpected group: #{s.inspect}"
- end
- }
- end
-
- def test_inspect
- set1 = Set[1]
-
- assert_equal('#<Set: {1}>', set1.inspect)
-
- set2 = Set[Set[0], 1, 2, set1]
- assert_equal(false, set2.inspect.include?('#<Set: {...}>'))
-
- set1.add(set2)
- assert_equal(true, set1.inspect.include?('#<Set: {...}>'))
- end
-
- # def test_pretty_print
- # end
-
- # def test_pretty_print_cycle
- # end
-end
-
-class TC_SortedSet < Test::Unit::TestCase
- def test_sortedset
- s = SortedSet[4,5,3,1,2]
-
- assert_equal([1,2,3,4,5], s.to_a)
-
- prev = nil
- s.each { |o| assert(prev < o) if prev; prev = o }
- assert_not_nil(prev)
-
- s.map! { |o| -2 * o }
-
- assert_equal([-10,-8,-6,-4,-2], s.to_a)
-
- prev = nil
- ret = s.each { |o| assert(prev < o) if prev; prev = o }
- assert_not_nil(prev)
- assert_same(s, ret)
-
- s = SortedSet.new([2,1,3]) { |o| o * -2 }
- assert_equal([-6,-4,-2], s.to_a)
-
- s = SortedSet.new(['one', 'two', 'three', 'four'])
- a = []
- ret = s.delete_if { |o| a << o; o.start_with?('t') }
- assert_same(s, ret)
- assert_equal(['four', 'one'], s.to_a)
- assert_equal(['four', 'one', 'three', 'two'], a)
-
- s = SortedSet.new(['one', 'two', 'three', 'four'])
- a = []
- ret = s.reject! { |o| a << o; o.start_with?('t') }
- assert_same(s, ret)
- assert_equal(['four', 'one'], s.to_a)
- assert_equal(['four', 'one', 'three', 'two'], a)
-
- s = SortedSet.new(['one', 'two', 'three', 'four'])
- a = []
- ret = s.reject! { |o| a << o; false }
- assert_same(nil, ret)
- assert_equal(['four', 'one', 'three', 'two'], s.to_a)
- assert_equal(['four', 'one', 'three', 'two'], a)
- end
-end
-
-class TC_Enumerable < Test::Unit::TestCase
- def test_to_set
- ary = [2,5,4,3,2,1,3]
-
- set = ary.to_set
- assert_instance_of(Set, set)
- assert_equal([1,2,3,4,5], set.sort)
-
- set = ary.to_set { |o| o * -2 }
- assert_instance_of(Set, set)
- assert_equal([-10,-8,-6,-4,-2], set.sort)
-
- set = ary.to_set(SortedSet)
- assert_instance_of(SortedSet, set)
- assert_equal([1,2,3,4,5], set.to_a)
-
- set = ary.to_set(SortedSet) { |o| o * -2 }
- assert_instance_of(SortedSet, set)
- assert_equal([-10,-8,-6,-4,-2], set.sort)
- end
-end
-
-# class TC_RestricedSet < Test::Unit::TestCase
-# def test_s_new
-# assert_raises(ArgumentError) { RestricedSet.new }
-#
-# s = RestricedSet.new([-1,2,3]) { |o| o > 0 }
-# assert_equal([2,3], s.sort)
-# end
-#
-# def test_restriction_proc
-# s = RestricedSet.new([-1,2,3]) { |o| o > 0 }
-#
-# f = s.restriction_proc
-# assert_instance_of(Proc, f)
-# assert(f[1])
-# assert(!f[0])
-# end
-#
-# def test_replace
-# s = RestricedSet.new(-3..3) { |o| o > 0 }
-# assert_equal([1,2,3], s.sort)
-#
-# s.replace([-2,0,3,4,5])
-# assert_equal([3,4,5], s.sort)
-# end
-#
-# def test_merge
-# s = RestricedSet.new { |o| o > 0 }
-# s.merge(-5..5)
-# assert_equal([1,2,3,4,5], s.sort)
-#
-# s.merge([10,-10,-8,8])
-# assert_equal([1,2,3,4,5,8,10], s.sort)
-# end
-# end
diff --git a/ruby_1_9_3/lib/shell.rb b/ruby_1_9_3/lib/shell.rb
deleted file mode 100644
index 9e409a1004..0000000000
--- a/ruby_1_9_3/lib/shell.rb
+++ /dev/null
@@ -1,300 +0,0 @@
-#
-# shell.rb -
-# $Release Version: 0.7 $
-# $Revision: 1.9 $
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-require "e2mmap"
-
-require "thread" unless defined?(Mutex)
-
-require "forwardable"
-
-require "shell/error"
-require "shell/command-processor"
-require "shell/process-controller"
-
-class Shell
- @RCS_ID='-$Id: shell.rb,v 1.9 2002/03/04 12:01:10 keiju Exp keiju $-'
-
- include Error
- extend Exception2MessageMapper
-
-# @cascade = true
- # debug: true -> normal debug
- # debug: 1 -> eval definition debug
- # debug: 2 -> detail inspect debug
- @debug = false
- @verbose = true
-
- @debug_display_process_id = false
- @debug_display_thread_id = true
- @debug_output_mutex = Mutex.new
-
- class << Shell
- extend Forwardable
-
- attr_accessor :cascade, :debug, :verbose
-
-# alias cascade? cascade
- alias debug? debug
- alias verbose? verbose
- @verbose = true
-
- def debug=(val)
- @debug = val
- @verbose = val if val
- end
-
- def cd(path)
- new(path)
- end
-
- def default_system_path
- if @default_system_path
- @default_system_path
- else
- ENV["PATH"].split(":")
- end
- end
-
- def default_system_path=(path)
- @default_system_path = path
- end
-
- def default_record_separator
- if @default_record_separator
- @default_record_separator
- else
- $/
- end
- end
-
- def default_record_separator=(rs)
- @default_record_separator = rs
- end
-
- # os resource mutex
- mutex_methods = ["unlock", "lock", "locked?", "synchronize", "try_lock", "exclusive_unlock"]
- for m in mutex_methods
- def_delegator("@debug_output_mutex", m, "debug_output_"+m.to_s)
- end
-
- end
-
- def initialize(pwd = Dir.pwd, umask = nil)
- @cwd = File.expand_path(pwd)
- @dir_stack = []
- @umask = umask
-
- @system_path = Shell.default_system_path
- @record_separator = Shell.default_record_separator
-
- @command_processor = CommandProcessor.new(self)
- @process_controller = ProcessController.new(self)
-
- @verbose = Shell.verbose
- @debug = Shell.debug
- end
-
- attr_reader :system_path
-
- def system_path=(path)
- @system_path = path
- rehash
- end
-
- attr_accessor :umask, :record_separator
- attr_accessor :verbose, :debug
-
- def debug=(val)
- @debug = val
- @verbose = val if val
- end
-
- alias verbose? verbose
- alias debug? debug
-
- attr_reader :command_processor
- attr_reader :process_controller
-
- def expand_path(path)
- File.expand_path(path, @cwd)
- end
-
- # Most Shell commands are defined via CommandProcessor
-
- #
- # Dir related methods
- #
- # Shell#cwd/dir/getwd/pwd
- # Shell#chdir/cd
- # Shell#pushdir/pushd
- # Shell#popdir/popd
- # Shell#mkdir
- # Shell#rmdir
-
- attr_reader :cwd
- alias dir cwd
- alias getwd cwd
- alias pwd cwd
-
- attr_reader :dir_stack
- alias dirs dir_stack
-
- # If called as iterator, it restores the current directory when the
- # block ends.
- def chdir(path = nil, verbose = @verbose)
- check_point
-
- if iterator?
- notify("chdir(with block) #{path}") if verbose
- cwd_old = @cwd
- begin
- chdir(path, nil)
- yield
- ensure
- chdir(cwd_old, nil)
- end
- else
- notify("chdir #{path}") if verbose
- path = "~" unless path
- @cwd = expand_path(path)
- notify "current dir: #{@cwd}"
- rehash
- Void.new(self)
- end
- end
- alias cd chdir
-
- def pushdir(path = nil, verbose = @verbose)
- check_point
-
- if iterator?
- notify("pushdir(with block) #{path}") if verbose
- pushdir(path, nil)
- begin
- yield
- ensure
- popdir
- end
- elsif path
- notify("pushdir #{path}") if verbose
- @dir_stack.push @cwd
- chdir(path, nil)
- notify "dir stack: [#{@dir_stack.join ', '}]"
- self
- else
- notify("pushdir") if verbose
- if pop = @dir_stack.pop
- @dir_stack.push @cwd
- chdir pop
- notify "dir stack: [#{@dir_stack.join ', '}]"
- self
- else
- Shell.Fail DirStackEmpty
- end
- end
- Void.new(self)
- end
- alias pushd pushdir
-
- def popdir
- check_point
-
- notify("popdir")
- if pop = @dir_stack.pop
- chdir pop
- notify "dir stack: [#{@dir_stack.join ', '}]"
- self
- else
- Shell.Fail DirStackEmpty
- end
- Void.new(self)
- end
- alias popd popdir
-
- #
- # process management
- #
- def jobs
- @process_controller.jobs
- end
-
- def kill(sig, command)
- @process_controller.kill_job(sig, command)
- end
-
- #
- # command definitions
- #
- def Shell.def_system_command(command, path = command)
- CommandProcessor.def_system_command(command, path)
- end
-
- def Shell.undef_system_command(command)
- CommandProcessor.undef_system_command(command)
- end
-
- def Shell.alias_command(ali, command, *opts, &block)
- CommandProcessor.alias_command(ali, command, *opts, &block)
- end
-
- def Shell.unalias_command(ali)
- CommandProcessor.unalias_command(ali)
- end
-
- def Shell.install_system_commands(pre = "sys_")
- CommandProcessor.install_system_commands(pre)
- end
-
- #
- def inspect
- if debug.kind_of?(Integer) && debug > 2
- super
- else
- to_s
- end
- end
-
- def self.notify(*opts, &block)
- Shell::debug_output_synchronize do
- if opts[-1].kind_of?(String)
- yorn = verbose?
- else
- yorn = opts.pop
- end
- return unless yorn
-
- if @debug_display_thread_id
- if @debug_display_process_id
- prefix = "shell(##{Process.pid}:#{Thread.current.to_s.sub("Thread", "Th")}): "
- else
- prefix = "shell(#{Thread.current.to_s.sub("Thread", "Th")}): "
- end
- else
- prefix = "shell: "
- end
- _head = true
- STDERR.print opts.collect{|mes|
- mes = mes.dup
- yield mes if iterator?
- if _head
- _head = false
-# "shell" " + mes
- prefix + mes
- else
- " "* prefix.size + mes
- end
- }.join("\n")+"\n"
- end
- end
-
- CommandProcessor.initialize
- CommandProcessor.run_config
-end
diff --git a/ruby_1_9_3/lib/shell/builtin-command.rb b/ruby_1_9_3/lib/shell/builtin-command.rb
deleted file mode 100644
index b1ca5c38f6..0000000000
--- a/ruby_1_9_3/lib/shell/builtin-command.rb
+++ /dev/null
@@ -1,160 +0,0 @@
-#
-# shell/builtin-command.rb -
-# $Release Version: 0.7 $
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-require "shell/filter"
-
-class Shell
- class BuiltInCommand<Filter
- def wait?
- false
- end
- def active?
- true
- end
- end
-
- class Void < BuiltInCommand
- def initialize(sh, *opts)
- super sh
- end
-
- def each(rs = nil)
- # do nothing
- end
- end
-
- class Echo < BuiltInCommand
- def initialize(sh, *strings)
- super sh
- @strings = strings
- end
-
- def each(rs = nil)
- rs = @shell.record_separator unless rs
- for str in @strings
- yield str + rs
- end
- end
- end
-
- class Cat < BuiltInCommand
- def initialize(sh, *filenames)
- super sh
- @cat_files = filenames
- end
-
- def each(rs = nil)
- if @cat_files.empty?
- super
- else
- for src in @cat_files
- @shell.foreach(src, rs){|l| yield l}
- end
- end
- end
- end
-
- class Glob < BuiltInCommand
- def initialize(sh, pattern)
- super sh
-
- @pattern = pattern
- end
-
- def each(rs = nil)
- if @pattern[0] == ?/
- @files = Dir[@pattern]
- else
- prefix = @shell.pwd+"/"
- @files = Dir[prefix+@pattern].collect{|p| p.sub(prefix, "")}
- end
- rs = @shell.record_separator unless rs
- for f in @files
- yield f+rs
- end
- end
- end
-
-# class Sort < Cat
-# def initialize(sh, *filenames)
-# super
-# end
-#
-# def each(rs = nil)
-# ary = []
-# super{|l| ary.push l}
-# for l in ary.sort!
-# yield l
-# end
-# end
-# end
-
- class AppendIO < BuiltInCommand
- def initialize(sh, io, filter)
- super sh
- @input = filter
- @io = io
- end
-
- def input=(filter)
- @input.input=filter
- for l in @input
- @io << l
- end
- end
-
- end
-
- class AppendFile < AppendIO
- def initialize(sh, to_filename, filter)
- @file_name = to_filename
- io = sh.open(to_filename, "a")
- super(sh, io, filter)
- end
-
- def input=(filter)
- begin
- super
- ensure
- @io.close
- end
- end
- end
-
- class Tee < BuiltInCommand
- def initialize(sh, filename)
- super sh
- @to_filename = filename
- end
-
- def each(rs = nil)
- to = @shell.open(@to_filename, "w")
- begin
- super{|l| to << l; yield l}
- ensure
- to.close
- end
- end
- end
-
- class Concat < BuiltInCommand
- def initialize(sh, *jobs)
- super(sh)
- @jobs = jobs
- end
-
- def each(rs = nil)
- while job = @jobs.shift
- job.each{|l| yield l}
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/shell/command-processor.rb b/ruby_1_9_3/lib/shell/command-processor.rb
deleted file mode 100644
index ae157eba5c..0000000000
--- a/ruby_1_9_3/lib/shell/command-processor.rb
+++ /dev/null
@@ -1,593 +0,0 @@
-#
-# shell/command-controller.rb -
-# $Release Version: 0.7 $
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-require "e2mmap"
-require "thread"
-
-require "shell/error"
-require "shell/filter"
-require "shell/system-command"
-require "shell/builtin-command"
-
-class Shell
- class CommandProcessor
-# include Error
-
- #
- # initialize of Shell and related classes.
- #
- m = [:initialize, :expand_path]
- if Object.methods.first.kind_of?(String)
- NoDelegateMethods = m.collect{|x| x.id2name}
- else
- NoDelegateMethods = m
- end
-
- def self.initialize
-
- install_builtin_commands
-
- # define CommandProcessor#methods to Shell#methods and Filter#methods
- for m in CommandProcessor.instance_methods(false) - NoDelegateMethods
- add_delegate_command_to_shell(m)
- end
-
- def self.method_added(id)
- add_delegate_command_to_shell(id)
- end
- end
-
- #
- # include run file.
- #
- def self.run_config
- begin
- load File.expand_path("~/.rb_shell") if ENV.key?("HOME")
- rescue LoadError, Errno::ENOENT
- rescue
- print "load error: #{rc}\n"
- print $!.class, ": ", $!, "\n"
- for err in $@[0, $@.size - 2]
- print "\t", err, "\n"
- end
- end
- end
-
- def initialize(shell)
- @shell = shell
- @system_commands = {}
- end
-
- #
- # CommandProcessor#expand_path(path)
- # path: String
- # return: String
- # returns the absolute path for <path>
- #
- def expand_path(path)
- @shell.expand_path(path)
- end
-
- #
- # File related commands
- # Shell#foreach
- # Shell#open
- # Shell#unlink
- # Shell#test
- #
- # -
- #
- # CommandProcessor#foreach(path, rs)
- # path: String
- # rs: String - record separator
- # iterator
- # Same as:
- # File#foreach (when path is file)
- # Dir#foreach (when path is directory)
- # path is relative to pwd
- #
- def foreach(path = nil, *rs)
- path = "." unless path
- path = expand_path(path)
-
- if File.directory?(path)
- Dir.foreach(path){|fn| yield fn}
- else
- IO.foreach(path, *rs){|l| yield l}
- end
- end
-
- #
- # CommandProcessor#open(path, mode)
- # path: String
- # mode: String
- # return: File or Dir
- # Same as:
- # File#open (when path is file)
- # Dir#open (when path is directory)
- # mode has an effect only when path is a file
- #
- def open(path, mode = nil, perm = 0666, &b)
- path = expand_path(path)
- if File.directory?(path)
- Dir.open(path, &b)
- else
- if @shell.umask
- f = File.open(path, mode, perm)
- File.chmod(perm & ~@shell.umask, path)
- if block_given?
- f.each(&b)
- end
- f
- else
- f = File.open(path, mode, perm, &b)
- end
- end
- end
- # public :open
-
- #
- # CommandProcessor#unlink(path)
- # same as:
- # Dir#unlink (when path is directory)
- # File#unlink (when path is file)
- #
- def unlink(path)
- @shell.check_point
-
- path = expand_path(path)
- if File.directory?(path)
- Dir.unlink(path)
- else
- IO.unlink(path)
- end
- Void.new(@shell)
- end
-
- #
- # CommandProcessor#test(command, file1, file2)
- # CommandProcessor#[command, file1, file2]
- # command: char or String or Symbol
- # file1: String
- # file2: String(optional)
- # return: Boolean
- # same as:
- # test() (when command is char or length 1 string or symbol)
- # FileTest.command (others)
- # example:
- # sh[?e, "foo"]
- # sh[:e, "foo"]
- # sh["e", "foo"]
- # sh[:exists?, "foo"]
- # sh["exists?", "foo"]
- #
- alias top_level_test test
- def test(command, file1, file2=nil)
- file1 = expand_path(file1)
- file2 = expand_path(file2) if file2
- command = command.id2name if command.kind_of?(Symbol)
-
- case command
- when Integer
- if file2
- top_level_test(command, file1, file2)
- else
- top_level_test(command, file1)
- end
- when String
- if command.size == 1
- if file2
- top_level_test(command, file1, file2)
- else
- top_level_test(command, file1)
- end
- else
- if file2
- FileTest.send(command, file1, file2)
- else
- FileTest.send(command, file1)
- end
- end
- end
- end
- alias [] test
-
- #
- # Dir related methods
- #
- # Shell#mkdir
- # Shell#rmdir
- #
- #--
- #
- # CommandProcessor#mkdir(*path)
- # path: String
- # same as Dir.mkdir()
- #
- def mkdir(*path)
- @shell.check_point
- notify("mkdir #{path.join(' ')}")
-
- perm = nil
- if path.last.kind_of?(Integer)
- perm = path.pop
- end
- for dir in path
- d = expand_path(dir)
- if perm
- Dir.mkdir(d, perm)
- else
- Dir.mkdir(d)
- end
- File.chmod(d, 0666 & ~@shell.umask) if @shell.umask
- end
- Void.new(@shell)
- end
-
- #
- # CommandProcessor#rmdir(*path)
- # path: String
- # same as Dir.rmdir()
- #
- def rmdir(*path)
- @shell.check_point
- notify("rmdir #{path.join(' ')}")
-
- for dir in path
- Dir.rmdir(expand_path(dir))
- end
- Void.new(@shell)
- end
-
- #
- # CommandProcessor#system(command, *opts)
- # command: String
- # opts: String
- # return: SystemCommand
- # Same as system() function
- # example:
- # print sh.system("ls", "-l")
- # sh.system("ls", "-l") | sh.head > STDOUT
- #
- def system(command, *opts)
- if opts.empty?
- if command =~ /\*|\?|\{|\}|\[|\]|<|>|\(|\)|~|&|\||\\|\$|;|'|`|"|\n/
- return SystemCommand.new(@shell, find_system_command("sh"), "-c", command)
- else
- command, *opts = command.split(/\s+/)
- end
- end
- SystemCommand.new(@shell, find_system_command(command), *opts)
- end
-
- #
- # ProcessCommand#rehash
- # clear command hash table.
- #
- def rehash
- @system_commands = {}
- end
-
- #
- # ProcessCommand#transact
- #
- def check_point
- @shell.process_controller.wait_all_jobs_execution
- end
- alias finish_all_jobs check_point
-
- def transact(&block)
- begin
- @shell.instance_eval(&block)
- ensure
- check_point
- end
- end
-
- #
- # internal commands
- #
- def out(dev = STDOUT, &block)
- dev.print transact(&block)
- end
-
- def echo(*strings)
- Echo.new(@shell, *strings)
- end
-
- def cat(*filenames)
- Cat.new(@shell, *filenames)
- end
-
- # def sort(*filenames)
- # Sort.new(self, *filenames)
- # end
-
- def glob(pattern)
- Glob.new(@shell, pattern)
- end
-
- def append(to, filter)
- case to
- when String
- AppendFile.new(@shell, to, filter)
- when IO
- AppendIO.new(@shell, to, filter)
- else
- Shell.Fail Error::CantApplyMethod, "append", to.class
- end
- end
-
- def tee(file)
- Tee.new(@shell, file)
- end
-
- def concat(*jobs)
- Concat.new(@shell, *jobs)
- end
-
- # %pwd, %cwd -> @pwd
- def notify(*opts, &block)
- Shell.notify(*opts) {|mes|
- yield mes if iterator?
-
- mes.gsub!("%pwd", "#{@cwd}")
- mes.gsub!("%cwd", "#{@cwd}")
- }
- end
-
- #
- # private functions
- #
- def find_system_command(command)
- return command if /^\// =~ command
- case path = @system_commands[command]
- when String
- if exists?(path)
- return path
- else
- Shell.Fail Error::CommandNotFound, command
- end
- when false
- Shell.Fail Error::CommandNotFound, command
- end
-
- for p in @shell.system_path
- path = join(p, command)
- if FileTest.exist?(path)
- @system_commands[command] = path
- return path
- end
- end
- @system_commands[command] = false
- Shell.Fail Error::CommandNotFound, command
- end
-
- #
- # CommandProcessor.def_system_command(command, path)
- # command: String
- # path: String
- # define 'command()' method as method.
- #
- def self.def_system_command(command, path = command)
- begin
- eval((d = %Q[def #{command}(*opts)
- SystemCommand.new(@shell, '#{path}', *opts)
- end]), nil, __FILE__, __LINE__ - 1)
- rescue SyntaxError
- Shell.notify "warn: Can't define #{command} path: #{path}."
- end
- Shell.notify "Define #{command} path: #{path}.", Shell.debug?
- Shell.notify("Definition of #{command}: ", d,
- Shell.debug.kind_of?(Integer) && Shell.debug > 1)
- end
-
- def self.undef_system_command(command)
- command = command.id2name if command.kind_of?(Symbol)
- remove_method(command)
- Shell.module_eval{remove_method(command)}
- Filter.module_eval{remove_method(command)}
- self
- end
-
- # define command alias
- # ex)
- # def_alias_command("ls_c", "ls", "-C", "-F")
- # def_alias_command("ls_c", "ls"){|*opts| ["-C", "-F", *opts]}
- #
- @alias_map = {}
- def self.alias_map
- @alias_map
- end
- def self.alias_command(ali, command, *opts, &block)
- ali = ali.id2name if ali.kind_of?(Symbol)
- command = command.id2name if command.kind_of?(Symbol)
- begin
- if iterator?
- @alias_map[ali.intern] = proc
-
- eval((d = %Q[def #{ali}(*opts)
- @shell.__send__(:#{command},
- *(CommandProcessor.alias_map[:#{ali}].call *opts))
- end]), nil, __FILE__, __LINE__ - 1)
-
- else
- args = opts.collect{|opt| '"' + opt + '"'}.join(",")
- eval((d = %Q[def #{ali}(*opts)
- @shell.__send__(:#{command}, #{args}, *opts)
- end]), nil, __FILE__, __LINE__ - 1)
- end
- rescue SyntaxError
- Shell.notify "warn: Can't alias #{ali} command: #{command}."
- Shell.notify("Definition of #{ali}: ", d)
- raise
- end
- Shell.notify "Define #{ali} command: #{command}.", Shell.debug?
- Shell.notify("Definition of #{ali}: ", d,
- Shell.debug.kind_of?(Integer) && Shell.debug > 1)
- self
- end
-
- def self.unalias_command(ali)
- ali = ali.id2name if ali.kind_of?(Symbol)
- @alias_map.delete ali.intern
- undef_system_command(ali)
- end
-
- #
- # CommandProcessor.def_builtin_commands(delegation_class, command_specs)
- # delegation_class: Class or Module
- # command_specs: [[command_name, [argument,...]],...]
- # command_name: String
- # arguments: String
- # FILENAME?? -> expand_path(filename??)
- # *FILENAME?? -> filename??.collect{|f|expand_path(f)}.join(", ")
- # define command_name(argument,...) as
- # delegation_class.command_name(argument,...)
- #
- def self.def_builtin_commands(delegation_class, command_specs)
- for meth, args in command_specs
- arg_str = args.collect{|arg| arg.downcase}.join(", ")
- call_arg_str = args.collect{
- |arg|
- case arg
- when /^(FILENAME.*)$/
- format("expand_path(%s)", $1.downcase)
- when /^(\*FILENAME.*)$/
- # \*FILENAME* -> filenames.collect{|fn| expand_path(fn)}.join(", ")
- $1.downcase + '.collect{|fn| expand_path(fn)}'
- else
- arg
- end
- }.join(", ")
- d = %Q[def #{meth}(#{arg_str})
- #{delegation_class}.#{meth}(#{call_arg_str})
- end]
- Shell.notify "Define #{meth}(#{arg_str})", Shell.debug?
- Shell.notify("Definition of #{meth}: ", d,
- Shell.debug.kind_of?(Integer) && Shell.debug > 1)
- eval d
- end
- end
-
- #
- # CommandProcessor.install_system_commands(pre)
- # pre: String - command name prefix
- # defines every command which belongs in default_system_path via
- # CommandProcessor.command(). It doesn't define already defined
- # methods twice. By default, "pre_" is prefixes to each method
- # name. Characters that may not be used in a method name are
- # all converted to '_'. Definition errors are just ignored.
- #
- def self.install_system_commands(pre = "sys_")
- defined_meth = {}
- for m in Shell.methods
- defined_meth[m] = true
- end
- sh = Shell.new
- for path in Shell.default_system_path
- next unless sh.directory? path
- sh.cd path
- sh.foreach do
- |cn|
- if !defined_meth[pre + cn] && sh.file?(cn) && sh.executable?(cn)
- command = (pre + cn).gsub(/\W/, "_").sub(/^([0-9])/, '_\1')
- begin
- def_system_command(command, sh.expand_path(cn))
- rescue
- Shell.notify "warn: Can't define #{command} path: #{cn}"
- end
- defined_meth[command] = command
- end
- end
- end
- end
-
- #----------------------------------------------------------------------
- #
- # class initializing methods -
- #
- #----------------------------------------------------------------------
- def self.add_delegate_command_to_shell(id)
- id = id.intern if id.kind_of?(String)
- name = id.id2name
- if Shell.method_defined?(id)
- Shell.notify "warn: override definition of Shell##{name}."
- Shell.notify "warn: alias Shell##{name} to Shell##{name}_org.\n"
- Shell.module_eval "alias #{name}_org #{name}"
- end
- Shell.notify "method added: Shell##{name}.", Shell.debug?
- Shell.module_eval(%Q[def #{name}(*args, &block)
- begin
- @command_processor.__send__(:#{name}, *args, &block)
- rescue Exception
- $@.delete_if{|s| /:in `__getobj__'$/ =~ s} #`
- $@.delete_if{|s| /^\\(eval\\):/ =~ s}
- raise
- end
- end], __FILE__, __LINE__)
-
- if Shell::Filter.method_defined?(id)
- Shell.notify "warn: override definition of Shell::Filter##{name}."
- Shell.notify "warn: alias Shell##{name} to Shell::Filter##{name}_org."
- Filter.module_eval "alias #{name}_org #{name}"
- end
- Shell.notify "method added: Shell::Filter##{name}.", Shell.debug?
- Filter.module_eval(%Q[def #{name}(*args, &block)
- begin
- self | @shell.__send__(:#{name}, *args, &block)
- rescue Exception
- $@.delete_if{|s| /:in `__getobj__'$/ =~ s} #`
- $@.delete_if{|s| /^\\(eval\\):/ =~ s}
- raise
- end
- end], __FILE__, __LINE__)
- end
-
- #
- # define default builtin commands
- #
- def self.install_builtin_commands
- # method related File.
- # (exclude open/foreach/unlink)
- normal_delegation_file_methods = [
- ["atime", ["FILENAME"]],
- ["basename", ["fn", "*opts"]],
- ["chmod", ["mode", "*FILENAMES"]],
- ["chown", ["owner", "group", "*FILENAME"]],
- ["ctime", ["FILENAMES"]],
- ["delete", ["*FILENAMES"]],
- ["dirname", ["FILENAME"]],
- ["ftype", ["FILENAME"]],
- ["join", ["*items"]],
- ["link", ["FILENAME_O", "FILENAME_N"]],
- ["lstat", ["FILENAME"]],
- ["mtime", ["FILENAME"]],
- ["readlink", ["FILENAME"]],
- ["rename", ["FILENAME_FROM", "FILENAME_TO"]],
- # ["size", ["FILENAME"]],
- ["split", ["pathname"]],
- ["stat", ["FILENAME"]],
- ["symlink", ["FILENAME_O", "FILENAME_N"]],
- ["truncate", ["FILENAME", "length"]],
- ["utime", ["atime", "mtime", "*FILENAMES"]]]
-
- def_builtin_commands(File, normal_delegation_file_methods)
- alias_method :rm, :delete
-
- # method related FileTest
- def_builtin_commands(FileTest,
- FileTest.singleton_methods(false).collect{|m| [m, ["FILENAME"]]})
-
- end
-
- end
-end
diff --git a/ruby_1_9_3/lib/shell/error.rb b/ruby_1_9_3/lib/shell/error.rb
deleted file mode 100644
index 2701338b5a..0000000000
--- a/ruby_1_9_3/lib/shell/error.rb
+++ /dev/null
@@ -1,25 +0,0 @@
-#
-# shell/error.rb -
-# $Release Version: 0.7 $
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-require "e2mmap"
-
-class Shell
- module Error
- extend Exception2MessageMapper
- def_e2message TypeError, "wrong argument type %s (expected %s)"
-
- def_exception :DirStackEmpty, "Directory stack empty."
- def_exception :CantDefine, "Can't define method(%s, %s)."
- def_exception :CantApplyMethod, "This method(%s) does not apply to this type(%s)."
- def_exception :CommandNotFound, "Command not found(%s)."
- end
-end
-
diff --git a/ruby_1_9_3/lib/shell/filter.rb b/ruby_1_9_3/lib/shell/filter.rb
deleted file mode 100644
index df41b420ea..0000000000
--- a/ruby_1_9_3/lib/shell/filter.rb
+++ /dev/null
@@ -1,109 +0,0 @@
-#
-# shell/filter.rb -
-# $Release Version: 0.7 $
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-class Shell
- #
- # Filter
- # A method to require
- # each()
- #
- class Filter
- include Enumerable
-
- def initialize(sh)
- @shell = sh # parent shell
- @input = nil # input filter
- end
-
- attr_reader :input
-
- def input=(filter)
- @input = filter
- end
-
- def each(rs = nil)
- rs = @shell.record_separator unless rs
- if @input
- @input.each(rs){|l| yield l}
- end
- end
-
- def < (src)
- case src
- when String
- cat = Cat.new(@shell, src)
- cat | self
- when IO
- self.input = src
- self
- else
- Shell.Fail Error::CantApplyMethod, "<", to.class
- end
- end
-
- def > (to)
- case to
- when String
- dst = @shell.open(to, "w")
- begin
- each(){|l| dst << l}
- ensure
- dst.close
- end
- when IO
- each(){|l| to << l}
- else
- Shell.Fail Error::CantApplyMethod, ">", to.class
- end
- self
- end
-
- def >> (to)
- begin
- Shell.cd(@shell.pwd).append(to, self)
- rescue CantApplyMethod
- Shell.Fail Error::CantApplyMethod, ">>", to.class
- end
- end
-
- def | (filter)
- filter.input = self
- if active?
- @shell.process_controller.start_job filter
- end
- filter
- end
-
- def + (filter)
- Join.new(@shell, self, filter)
- end
-
- def to_a
- ary = []
- each(){|l| ary.push l}
- ary
- end
-
- def to_s
- str = ""
- each(){|l| str.concat l}
- str
- end
-
- def inspect
- if @shell.debug.kind_of?(Integer) && @shell.debug > 2
- super
- else
- to_s
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/shell/process-controller.rb b/ruby_1_9_3/lib/shell/process-controller.rb
deleted file mode 100644
index 30f2229d39..0000000000
--- a/ruby_1_9_3/lib/shell/process-controller.rb
+++ /dev/null
@@ -1,319 +0,0 @@
-#
-# shell/process-controller.rb -
-# $Release Version: 0.7 $
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-require "forwardable"
-
-require "thread"
-require "sync"
-
-class Shell
- class ProcessController
-
- @ProcessControllers = {}
- @ProcessControllersMonitor = Mutex.new
- @ProcessControllersCV = ConditionVariable.new
-
- @BlockOutputMonitor = Mutex.new
- @BlockOutputCV = ConditionVariable.new
-
- class << self
- extend Forwardable
-
- def_delegator("@ProcessControllersMonitor",
- "synchronize", "process_controllers_exclusive")
-
- def active_process_controllers
- process_controllers_exclusive do
- @ProcessControllers.dup
- end
- end
-
- def activate(pc)
- process_controllers_exclusive do
- @ProcessControllers[pc] ||= 0
- @ProcessControllers[pc] += 1
- end
- end
-
- def inactivate(pc)
- process_controllers_exclusive do
- if @ProcessControllers[pc]
- if (@ProcessControllers[pc] -= 1) == 0
- @ProcessControllers.delete(pc)
- @ProcessControllersCV.signal
- end
- end
- end
- end
-
- def each_active_object
- process_controllers_exclusive do
- for ref in @ProcessControllers.keys
- yield ref
- end
- end
- end
-
- def block_output_synchronize(&b)
- @BlockOutputMonitor.synchronize(&b)
- end
-
- def wait_to_finish_all_process_controllers
- process_controllers_exclusive do
- while !@ProcessControllers.empty?
- Shell::notify("Process finishing, but active shell exists",
- "You can use Shell#transact or Shell#check_point for more safe execution.")
- if Shell.debug?
- for pc in @ProcessControllers.keys
- Shell::notify(" Not finished jobs in "+pc.shell.to_s)
- for com in pc.jobs
- com.notify(" Jobs: %id")
- end
- end
- end
- @ProcessControllersCV.wait(@ProcessControllersMonitor)
- end
- end
- end
- end
-
- # for shell-command complete finish at this process exit.
- USING_AT_EXIT_WHEN_PROCESS_EXIT = true
- at_exit do
- wait_to_finish_all_process_controllers unless $@
- end
-
- def initialize(shell)
- @shell = shell
- @waiting_jobs = []
- @active_jobs = []
- @jobs_sync = Sync.new
-
- @job_monitor = Mutex.new
- @job_condition = ConditionVariable.new
- end
-
- attr_reader :shell
-
- def jobs
- jobs = []
- @jobs_sync.synchronize(:SH) do
- jobs.concat @waiting_jobs
- jobs.concat @active_jobs
- end
- jobs
- end
-
- def active_jobs
- @active_jobs
- end
-
- def waiting_jobs
- @waiting_jobs
- end
-
- def jobs_exist?
- @jobs_sync.synchronize(:SH) do
- @active_jobs.empty? or @waiting_jobs.empty?
- end
- end
-
- def active_jobs_exist?
- @jobs_sync.synchronize(:SH) do
- @active_jobs.empty?
- end
- end
-
- def waiting_jobs_exist?
- @jobs_sync.synchronize(:SH) do
- @waiting_jobs.empty?
- end
- end
-
- # schedule a command
- def add_schedule(command)
- @jobs_sync.synchronize(:EX) do
- ProcessController.activate(self)
- if @active_jobs.empty?
- start_job command
- else
- @waiting_jobs.push(command)
- end
- end
- end
-
- # start a job
- def start_job(command = nil)
- @jobs_sync.synchronize(:EX) do
- if command
- return if command.active?
- @waiting_jobs.delete command
- else
- command = @waiting_jobs.shift
-# command.notify "job(%id) pre-start.", @shell.debug?
-
- return unless command
- end
- @active_jobs.push command
- command.start
-# command.notify "job(%id) post-start.", @shell.debug?
-
- # start all jobs that input from the job
- for job in @waiting_jobs.dup
- start_job(job) if job.input == command
- end
-# command.notify "job(%id) post2-start.", @shell.debug?
- end
- end
-
- def waiting_job?(job)
- @jobs_sync.synchronize(:SH) do
- @waiting_jobs.include?(job)
- end
- end
-
- def active_job?(job)
- @jobs_sync.synchronize(:SH) do
- @active_jobs.include?(job)
- end
- end
-
- # terminate a job
- def terminate_job(command)
- @jobs_sync.synchronize(:EX) do
- @active_jobs.delete command
- ProcessController.inactivate(self)
- if @active_jobs.empty?
- command.notify("start_job in terminate_job(%id)", Shell::debug?)
- start_job
- end
- end
- end
-
- # kill a job
- def kill_job(sig, command)
- @jobs_sync.synchronize(:EX) do
- if @waiting_jobs.delete command
- ProcessController.inactivate(self)
- return
- elsif @active_jobs.include?(command)
- begin
- r = command.kill(sig)
- ProcessController.inactivate(self)
- rescue
- print "Shell: Warn: $!\n" if @shell.verbose?
- return nil
- end
- @active_jobs.delete command
- r
- end
- end
- end
-
- # wait for all jobs to terminate
- def wait_all_jobs_execution
- @job_monitor.synchronize do
- begin
- while !jobs.empty?
- @job_condition.wait(@job_monitor)
- for job in jobs
- job.notify("waiting job(%id)", Shell::debug?)
- end
- end
- ensure
- redo unless jobs.empty?
- end
- end
- end
-
- # simple fork
- def sfork(command, &block)
- pipe_me_in, pipe_peer_out = IO.pipe
- pipe_peer_in, pipe_me_out = IO.pipe
-
-
- pid = nil
- pid_mutex = Mutex.new
- pid_cv = ConditionVariable.new
-
- Thread.start do
- ProcessController.block_output_synchronize do
- STDOUT.flush
- ProcessController.each_active_object do |pc|
- for jobs in pc.active_jobs
- jobs.flush
- end
- end
-
- pid = fork {
- Thread.list.each do |th|
-# th.kill unless [Thread.main, Thread.current].include?(th)
- th.kill unless Thread.current == th
- end
-
- STDIN.reopen(pipe_peer_in)
- STDOUT.reopen(pipe_peer_out)
-
- ObjectSpace.each_object(IO) do |io|
- if ![STDIN, STDOUT, STDERR].include?(io)
- io.close unless io.closed?
- end
- end
-
- yield
- }
- end
- pid_cv.signal
-
- pipe_peer_in.close
- pipe_peer_out.close
- command.notify "job(%name:##{pid}) start", @shell.debug?
-
- begin
- _pid = nil
- command.notify("job(%id) start to waiting finish.", @shell.debug?)
- _pid = Process.waitpid(pid, nil)
- rescue Errno::ECHILD
- command.notify "warn: job(%id) was done already waitpid."
- _pid = true
- # rescue
- # STDERR.puts $!
- ensure
- command.notify("Job(%id): Wait to finish when Process finished.", @shell.debug?)
- # when the process ends, wait until the command terminates
- if USING_AT_EXIT_WHEN_PROCESS_EXIT or _pid
- else
- command.notify("notice: Process finishing...",
- "wait for Job[%id] to finish.",
- "You can use Shell#transact or Shell#check_point for more safe execution.")
- redo
- end
-
-# command.notify "job(%id) pre-pre-finish.", @shell.debug?
- @job_monitor.synchronize do
-# command.notify "job(%id) pre-finish.", @shell.debug?
- terminate_job(command)
-# command.notify "job(%id) pre-finish2.", @shell.debug?
- @job_condition.signal
- command.notify "job(%id) finish.", @shell.debug?
- end
- end
- end
-
- pid_mutex.synchronize do
- while !pid
- pid_cv.wait(pid_mutex)
- end
- end
-
- return pid, pipe_me_in, pipe_me_out
- end
- end
-end
diff --git a/ruby_1_9_3/lib/shell/system-command.rb b/ruby_1_9_3/lib/shell/system-command.rb
deleted file mode 100644
index 50d994bb20..0000000000
--- a/ruby_1_9_3/lib/shell/system-command.rb
+++ /dev/null
@@ -1,159 +0,0 @@
-#
-# shell/system-command.rb -
-# $Release Version: 0.7 $
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-require "shell/filter"
-
-class Shell
- class SystemCommand < Filter
- def initialize(sh, command, *opts)
- if t = opts.find{|opt| !opt.kind_of?(String) && opt.class}
- Shell.Fail Error::TypeError, t.class, "String"
- end
- super(sh)
- @command = command
- @opts = opts
-
- @input_queue = Queue.new
- @pid = nil
-
- sh.process_controller.add_schedule(self)
- end
-
- attr_reader :command
- alias name command
-
- def wait?
- @shell.process_controller.waiting_job?(self)
- end
-
- def active?
- @shell.process_controller.active_job?(self)
- end
-
- def input=(inp)
- super
- if active?
- start_export
- end
- end
-
- def start
- notify([@command, *@opts].join(" "))
-
- @pid, @pipe_in, @pipe_out = @shell.process_controller.sfork(self) {
- Dir.chdir @shell.pwd
- $0 = @command
- exec(@command, *@opts)
- }
- if @input
- start_export
- end
- start_import
- end
-
- def flush
- @pipe_out.flush if @pipe_out and !@pipe_out.closed?
- end
-
- def terminate
- begin
- @pipe_in.close
- rescue IOError
- end
- begin
- @pipe_out.close
- rescue IOError
- end
- end
-
- def kill(sig)
- if @pid
- Process.kill(sig, @pid)
- end
- end
-
- def start_import
- notify "Job(%id) start imp-pipe.", @shell.debug?
- rs = @shell.record_separator unless rs
- _eop = true
- Thread.start {
- begin
- while l = @pipe_in.gets
- @input_queue.push l
- end
- _eop = false
- rescue Errno::EPIPE
- _eop = false
- ensure
- if !ProcessController::USING_AT_EXIT_WHEN_PROCESS_EXIT and _eop
- notify("warn: Process finishing...",
- "wait for Job[%id] to finish pipe importing.",
- "You can use Shell#transact or Shell#check_point for more safe execution.")
- redo
- end
- notify "job(%id}) close imp-pipe.", @shell.debug?
- @input_queue.push :EOF
- @pipe_in.close
- end
- }
- end
-
- def start_export
- notify "job(%id) start exp-pipe.", @shell.debug?
- _eop = true
- Thread.start{
- begin
- @input.each do |l|
- ProcessController::block_output_synchronize do
- @pipe_out.print l
- end
- end
- _eop = false
- rescue Errno::EPIPE, Errno::EIO
- _eop = false
- ensure
- if !ProcessController::USING_AT_EXIT_WHEN_PROCESS_EXIT and _eop
- notify("shell: warn: Process finishing...",
- "wait for Job(%id) to finish pipe exporting.",
- "You can use Shell#transact or Shell#check_point for more safe execution.")
- redo
- end
- notify "job(%id) close exp-pipe.", @shell.debug?
- @pipe_out.close
- end
- }
- end
-
- alias super_each each
- def each(rs = nil)
- while (l = @input_queue.pop) != :EOF
- yield l
- end
- end
-
- # ex)
- # if you wish to output:
- # "shell: job(#{@command}:#{@pid}) close pipe-out."
- # then
- # mes: "job(%id) close pipe-out."
- # yorn: Boolean(@shell.debug? or @shell.verbose?)
- def notify(*opts, &block)
- @shell.notify(*opts) do |mes|
- yield mes if iterator?
-
- mes.gsub!("%id", "#{@command}:##{@pid}")
- mes.gsub!("%name", "#{@command}")
- mes.gsub!("%pid", "#{@pid}")
- mes
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/shell/version.rb b/ruby_1_9_3/lib/shell/version.rb
deleted file mode 100644
index cbdb0e5e96..0000000000
--- a/ruby_1_9_3/lib/shell/version.rb
+++ /dev/null
@@ -1,15 +0,0 @@
-#
-# version.rb - shell version definition file
-# $Release Version: 0.7$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ruby-lang.org)
-#
-# --
-#
-#
-#
-
-class Shell
- @RELEASE_VERSION = "0.7"
- @LAST_UPDATE_DATE = "07/03/20"
-end
diff --git a/ruby_1_9_3/lib/shellwords.rb b/ruby_1_9_3/lib/shellwords.rb
deleted file mode 100644
index abc4e80ad4..0000000000
--- a/ruby_1_9_3/lib/shellwords.rb
+++ /dev/null
@@ -1,151 +0,0 @@
-#
-# shellwords.rb: Manipulates strings a la UNIX Bourne shell
-#
-
-#
-# This module manipulates strings according to the word parsing rules
-# of the UNIX Bourne shell.
-#
-# The shellwords() function was originally a port of shellwords.pl,
-# but modified to conform to POSIX / SUSv3 (IEEE Std 1003.1-2001).
-#
-# Authors:
-# - Wakou Aoyama
-# - Akinori MUSHA <knu@iDaemons.org>
-#
-# Contact:
-# - Akinori MUSHA <knu@iDaemons.org> (current maintainer)
-#
-module Shellwords
- # Splits a string into an array of tokens in the same way the UNIX
- # Bourne shell does.
- #
- # argv = Shellwords.split('here are "two words"')
- # argv #=> ["here", "are", "two words"]
- #
- # String#shellsplit is a shorthand for this function.
- #
- # argv = 'here are "two words"'.shellsplit
- # argv #=> ["here", "are", "two words"]
- def shellsplit(line)
- words = []
- field = ''
- line.scan(/\G\s*(?>([^\s\\\'\"]+)|'([^\']*)'|"((?:[^\"\\]|\\.)*)"|(\\.?)|(\S))(\s|\z)?/m) do
- |word, sq, dq, esc, garbage, sep|
- raise ArgumentError, "Unmatched double quote: #{line.inspect}" if garbage
- field << (word || sq || (dq || esc).gsub(/\\(.)/, '\\1'))
- if sep
- words << field
- field = ''
- end
- end
- words
- end
-
- alias shellwords shellsplit
-
- module_function :shellsplit, :shellwords
-
- class << self
- alias split shellsplit
- end
-
- # Escapes a string so that it can be safely used in a Bourne shell
- # command line.
- #
- # Note that a resulted string should be used unquoted and is not
- # intended for use in double quotes nor in single quotes.
- #
- # open("| grep #{Shellwords.escape(pattern)} file") { |pipe|
- # # ...
- # }
- #
- # String#shellescape is a shorthand for this function.
- #
- # open("| grep #{pattern.shellescape} file") { |pipe|
- # # ...
- # }
- #
- # It is caller's responsibility to encode the string in the right
- # encoding for the shell environment where this string is used.
- # Multibyte characters are treated as multibyte characters, not
- # bytes.
- def shellescape(str)
- # An empty argument will be skipped, so return empty quotes.
- return "''" if str.empty?
-
- str = str.dup
-
- # Treat multibyte characters as is. It is caller's responsibility
- # to encode the string in the right encoding for the shell
- # environment.
- str.gsub!(/([^A-Za-z0-9_\-.,:\/@\n])/, "\\\\\\1")
-
- # A LF cannot be escaped with a backslash because a backslash + LF
- # combo is regarded as line continuation and simply ignored.
- str.gsub!(/\n/, "'\n'")
-
- return str
- end
-
- module_function :shellescape
-
- class << self
- alias escape shellescape
- end
-
- # Builds a command line string from an argument list +array+ joining
- # all elements escaped for Bourne shell and separated by a space.
- #
- # open('|' + Shellwords.join(['grep', pattern, *files])) { |pipe|
- # # ...
- # }
- #
- # Array#shelljoin is a shorthand for this function.
- #
- # open('|' + ['grep', pattern, *files].shelljoin) { |pipe|
- # # ...
- # }
- #
- def shelljoin(array)
- array.map { |arg| shellescape(arg) }.join(' ')
- end
-
- module_function :shelljoin
-
- class << self
- alias join shelljoin
- end
-end
-
-class String
- # call-seq:
- # str.shellsplit => array
- #
- # Splits +str+ into an array of tokens in the same way the UNIX
- # Bourne shell does. See Shellwords::shellsplit for details.
- def shellsplit
- Shellwords.split(self)
- end
-
- # call-seq:
- # str.shellescape => string
- #
- # Escapes +str+ so that it can be safely used in a Bourne shell
- # command line. See Shellwords::shellescape for details.
- def shellescape
- Shellwords.escape(self)
- end
-end
-
-class Array
- # call-seq:
- # array.shelljoin => string
- #
- # Builds a command line string from an argument list +array+ joining
- # all elements escaped for Bourne shell and separated by a space.
- # See Shellwords::shelljoin for details.
- def shelljoin
- Shellwords.join(self)
- end
-end
diff --git a/ruby_1_9_3/lib/singleton.rb b/ruby_1_9_3/lib/singleton.rb
deleted file mode 100644
index be1f7ff6ca..0000000000
--- a/ruby_1_9_3/lib/singleton.rb
+++ /dev/null
@@ -1,172 +0,0 @@
-require 'thread'
-
-# The Singleton module implements the Singleton pattern.
-#
-# == Usage
-#
-# To use Singleton, include the module in your class.
-#
-# class Klass
-# include Singleton
-# # ...
-# end
-#
-# This ensures that only one instance of Klass can be created.
-#
-# a,b = Klass.instance, Klass.instance
-#
-# a == b
-# # => true
-#
-# Klass.new
-# # => NoMethodError - new is private ...
-#
-# The instance is created at upon the first call of Klass.instance().
-#
-# class OtherKlass
-# include Singleton
-# # ...
-# end
-#
-# ObjectSpace.each_object(OtherKlass){}
-# # => 0
-#
-# OtherKlass.instance
-# ObjectSpace.each_object(OtherKlass){}
-# # => 1
-#
-#
-# This behavior is preserved under inheritance and cloning.
-#
-# == Implementation
-#
-# This above is achieved by:
-#
-# * Making Klass.new and Klass.allocate private.
-#
-# * Overriding Klass.inherited(sub_klass) and Klass.clone() to ensure that the
-# Singleton properties are kept when inherited and cloned.
-#
-# * Providing the Klass.instance() method that returns the same object each
-# time it is called.
-#
-# * Overriding Klass._load(str) to call Klass.instance().
-#
-# * Overriding Klass#clone and Klass#dup to raise TypeErrors to prevent
-# cloning or duping.
-#
-# == Singleton and Marshal
-#
-# By default Singleton's #_dump(depth) returns the empty string. Marshalling by
-# default will strip state information, e.g. instance variables and taint
-# state, from the instance. Classes using Singleton can provide custom
-# _load(str) and _dump(depth) methods to retain some of the previous state of
-# the instance.
-#
-# require 'singleton'
-#
-# class Example
-# include Singleton
-# attr_accessor :keep, :strip
-# def _dump(depth)
-# # this strips the @strip information from the instance
-# Marshal.dump(@keep, depth)
-# end
-#
-# def self._load(str)
-# instance.keep = Marshal.load(str)
-# instance
-# end
-# end
-#
-# a = Example.instance
-# a.keep = "keep this"
-# a.strip = "get rid of this"
-# a.taint
-#
-# stored_state = Marshal.dump(a)
-#
-# a.keep = nil
-# a.strip = nil
-# b = Marshal.load(stored_state)
-# p a == b # => true
-# p a.keep # => "keep this"
-# p a.strip # => nil
-#
-module Singleton
- # Raises a TypeError to prevent cloning.
- def clone
- raise TypeError, "can't clone instance of singleton #{self.class}"
- end
-
- # Raises a TypeError to prevent duping.
- def dup
- raise TypeError, "can't dup instance of singleton #{self.class}"
- end
-
- # By default, do not retain any state when marshalling.
- def _dump(depth = -1)
- ''
- end
-
- module SingletonClassMethods # :nodoc:
-
- def clone # :nodoc:
- Singleton.__init__(super)
- end
-
- # By default calls instance(). Override to retain singleton state.
- def _load(str)
- instance
- end
-
- private
-
- def inherited(sub_klass)
- super
- Singleton.__init__(sub_klass)
- end
- end
-
- class << Singleton # :nodoc:
- def __init__(klass) # :nodoc:
- klass.instance_eval {
- @singleton__instance__ = nil
- @singleton__mutex__ = Mutex.new
- }
- def klass.instance # :nodoc:
- return @singleton__instance__ if @singleton__instance__
- @singleton__mutex__.synchronize {
- return @singleton__instance__ if @singleton__instance__
- @singleton__instance__ = new()
- }
- @singleton__instance__
- end
- klass
- end
-
- private
-
- # extending an object with Singleton is a bad idea
- undef_method :extend_object
-
- def append_features(mod)
- # help out people counting on transitive mixins
- unless mod.instance_of?(Class)
- raise TypeError, "Inclusion of the OO-Singleton module in module #{mod}"
- end
- super
- end
-
- def included(klass)
- super
- klass.private_class_method :new, :allocate
- klass.extend SingletonClassMethods
- Singleton.__init__(klass)
- end
- end
-
- ##
- # :singleton-method: _load
- # By default calls instance(). Override to retain singleton state.
-end
diff --git a/ruby_1_9_3/lib/sync.rb b/ruby_1_9_3/lib/sync.rb
deleted file mode 100644
index bae05a4a99..0000000000
--- a/ruby_1_9_3/lib/sync.rb
+++ /dev/null
@@ -1,321 +0,0 @@
-#
-# sync.rb - 2 phase lock with counter
-# $Release Version: 1.0$
-# $Revision$
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-#
-# --
-# Sync_m, Synchronizer_m
-# Usage:
-# obj.extend(Sync_m)
-# or
-# class Foo
-# include Sync_m
-# :
-# end
-#
-# Sync_m#sync_mode
-# Sync_m#sync_locked?, locked?
-# Sync_m#sync_shared?, shared?
-# Sync_m#sync_exclusive?, sync_exclusive?
-# Sync_m#sync_try_lock, try_lock
-# Sync_m#sync_lock, lock
-# Sync_m#sync_unlock, unlock
-#
-# Sync, Synchronizer:
-# Usage:
-# sync = Sync.new
-#
-# Sync#mode
-# Sync#locked?
-# Sync#shared?
-# Sync#exclusive?
-# Sync#try_lock(mode) -- mode = :EX, :SH, :UN
-# Sync#lock(mode) -- mode = :EX, :SH, :UN
-# Sync#unlock
-# Sync#synchronize(mode) {...}
-#
-#
-
-unless defined? Thread
- raise "Thread not available for this ruby interpreter"
-end
-
-##
-# A module that provides a two-phase lock with a counter.
-
-module Sync_m
- RCS_ID='-$Id$-'
-
- # lock mode
- UN = :UN
- SH = :SH
- EX = :EX
-
- # exceptions
- class Err < StandardError
- def Err.Fail(*opt)
- fail self, sprintf(self::Message, *opt)
- end
-
- class UnknownLocker < Err
- Message = "Thread(%s) not locked."
- def UnknownLocker.Fail(th)
- super(th.inspect)
- end
- end
-
- class LockModeFailer < Err
- Message = "Unknown lock mode(%s)"
- def LockModeFailer.Fail(mode)
- if mode.id2name
- mode = id2name
- end
- super(mode)
- end
- end
- end
-
- def Sync_m.define_aliases(cl)
- cl.module_eval %q{
- alias locked? sync_locked?
- alias shared? sync_shared?
- alias exclusive? sync_exclusive?
- alias lock sync_lock
- alias unlock sync_unlock
- alias try_lock sync_try_lock
- alias synchronize sync_synchronize
- }
- end
-
- def Sync_m.append_features(cl)
- super
- # do nothing for Modules
- # make aliases for Classes.
- define_aliases(cl) unless cl.instance_of?(Module)
- self
- end
-
- def Sync_m.extend_object(obj)
- super
- obj.sync_extend
- end
-
- def sync_extend
- unless (defined? locked? and
- defined? shared? and
- defined? exclusive? and
- defined? lock and
- defined? unlock and
- defined? try_lock and
- defined? synchronize)
- Sync_m.define_aliases(singleton_class)
- end
- sync_initialize
- end
-
- # accessing
- def sync_locked?
- sync_mode != UN
- end
-
- def sync_shared?
- sync_mode == SH
- end
-
- def sync_exclusive?
- sync_mode == EX
- end
-
- # locking methods.
- def sync_try_lock(mode = EX)
- return unlock if mode == UN
- @sync_mutex.synchronize do
- sync_try_lock_sub(mode)
- end
- end
-
- def sync_lock(m = EX)
- return unlock if m == UN
-
- while true
- @sync_mutex.synchronize do
- if sync_try_lock_sub(m)
- return self
- else
- if sync_sh_locker[Thread.current]
- sync_upgrade_waiting.push [Thread.current, sync_sh_locker[Thread.current]]
- sync_sh_locker.delete(Thread.current)
- else
- sync_waiting.push Thread.current
- end
- @sync_mutex.sleep
- end
- end
- end
- self
- end
-
- def sync_unlock(m = EX)
- wakeup_threads = []
- @sync_mutex.synchronize do
- if sync_mode == UN
- Err::UnknownLocker.Fail(Thread.current)
- end
-
- m = sync_mode if m == EX and sync_mode == SH
-
- runnable = false
- case m
- when UN
- Err::UnknownLocker.Fail(Thread.current)
-
- when EX
- if sync_ex_locker == Thread.current
- if (self.sync_ex_count = sync_ex_count - 1) == 0
- self.sync_ex_locker = nil
- if sync_sh_locker.include?(Thread.current)
- self.sync_mode = SH
- else
- self.sync_mode = UN
- end
- runnable = true
- end
- else
- Err::UnknownLocker.Fail(Thread.current)
- end
-
- when SH
- if (count = sync_sh_locker[Thread.current]).nil?
- Err::UnknownLocker.Fail(Thread.current)
- else
- if (sync_sh_locker[Thread.current] = count - 1) == 0
- sync_sh_locker.delete(Thread.current)
- if sync_sh_locker.empty? and sync_ex_count == 0
- self.sync_mode = UN
- runnable = true
- end
- end
- end
- end
-
- if runnable
- if sync_upgrade_waiting.size > 0
- th, count = sync_upgrade_waiting.shift
- sync_sh_locker[th] = count
- th.wakeup
- wakeup_threads.push th
- else
- wait = sync_waiting
- self.sync_waiting = []
- for th in wait
- th.wakeup
- wakeup_threads.push th
- end
- end
- end
- end
- for th in wakeup_threads
- th.run
- end
- self
- end
-
- def sync_synchronize(mode = EX)
- sync_lock(mode)
- begin
- yield
- ensure
- sync_unlock
- end
- end
-
- attr_accessor :sync_mode
-
- attr_accessor :sync_waiting
- attr_accessor :sync_upgrade_waiting
- attr_accessor :sync_sh_locker
- attr_accessor :sync_ex_locker
- attr_accessor :sync_ex_count
-
- def sync_inspect
- sync_iv = instance_variables.select{|iv| /^@sync_/ =~ iv.id2name}.collect{|iv| iv.id2name + '=' + instance_eval(iv.id2name).inspect}.join(",")
- print "<#{self.class}.extend Sync_m: #{inspect}, <Sync_m: #{sync_iv}>"
- end
-
- private
-
- def sync_initialize
- @sync_mode = UN
- @sync_waiting = []
- @sync_upgrade_waiting = []
- @sync_sh_locker = Hash.new
- @sync_ex_locker = nil
- @sync_ex_count = 0
-
- @sync_mutex = Mutex.new
- end
-
- def initialize(*args)
- super
- sync_initialize
- end
-
- def sync_try_lock_sub(m)
- case m
- when SH
- case sync_mode
- when UN
- self.sync_mode = m
- sync_sh_locker[Thread.current] = 1
- ret = true
- when SH
- count = 0 unless count = sync_sh_locker[Thread.current]
- sync_sh_locker[Thread.current] = count + 1
- ret = true
- when EX
- # in EX mode, lock will upgrade to EX lock
- if sync_ex_locker == Thread.current
- self.sync_ex_count = sync_ex_count + 1
- ret = true
- else
- ret = false
- end
- end
- when EX
- if sync_mode == UN or
- sync_mode == SH && sync_sh_locker.size == 1 && sync_sh_locker.include?(Thread.current)
- self.sync_mode = m
- self.sync_ex_locker = Thread.current
- self.sync_ex_count = 1
- ret = true
- elsif sync_mode == EX && sync_ex_locker == Thread.current
- self.sync_ex_count = sync_ex_count + 1
- ret = true
- else
- ret = false
- end
- else
- Err::LockModeFailer.Fail mode
- end
- return ret
- end
-end
-
-##
-# An alias for Sync_m from sync.rb
-
-Synchronizer_m = Sync_m
-
-##
-# A class that providesa two-phase lock with a counter. See Sync_m for
-# details.
-
-class Sync
- include Sync_m
-end
-
-##
-# An alias for Sync from sync.rb. See Sync_m for details.
-
-Synchronizer = Sync
diff --git a/ruby_1_9_3/lib/tempfile.rb b/ruby_1_9_3/lib/tempfile.rb
deleted file mode 100644
index b34251ebb6..0000000000
--- a/ruby_1_9_3/lib/tempfile.rb
+++ /dev/null
@@ -1,359 +0,0 @@
-#
-# tempfile - manipulates temporary files
-#
-# $Id$
-#
-
-require 'delegate'
-require 'tmpdir'
-require 'thread'
-
-# A utility class for managing temporary files. When you create a Tempfile
-# object, it will create a temporary file with a unique filename. A Tempfile
-# objects behaves just like a File object, and you can perform all the usual
-# file operations on it: reading data, writing data, changing its permissions,
-# etc. So although this class does not explicitly document all instance methods
-# supported by File, you can in fact call any File instance method on a
-# Tempfile object.
-#
-# == Synopsis
-#
-# require 'tempfile'
-#
-# file = Tempfile.new('foo')
-# file.path # => A unique filename in the OS's temp directory,
-# # e.g.: "/tmp/foo.24722.0"
-# # This filename contains 'foo' in its basename.
-# file.write("hello world")
-# file.rewind
-# file.read # => "hello world"
-# file.close
-# file.unlink # deletes the temp file
-#
-# == Good practices
-#
-# === Explicit close
-#
-# When a Tempfile object is garbage collected, or when the Ruby interpreter
-# exits, its associated temporary file is automatically deleted. This means
-# that's it's unnecessary to explicitly delete a Tempfile after use, though
-# it's good practice to do so: not explicitly deleting unused Tempfiles can
-# potentially leave behind large amounts of tempfiles on the filesystem
-# until they're garbage collected. The existence of these temp files can make
-# it harder to determine a new Tempfile filename.
-#
-# Therefore, one should always call #unlink or close in an ensure block, like
-# this:
-#
-# file = Tempfile.new('foo')
-# begin
-# ...do something with file...
-# ensure
-# file.close
-# file.unlink # deletes the temp file
-# end
-#
-# === Unlink after creation
-#
-# On POSIX systems, it's possible to unlink a file right after creating it,
-# and before closing it. This removes the filesystem entry without closing
-# the file handle, so it ensures that only the processes that already had
-# the file handle open can access the file's contents. It's strongly
-# recommended that you do this if you do not want any other processes to
-# be able to read from or write to the Tempfile, and you do not need to
-# know the Tempfile's filename either.
-#
-# For example, a practical use case for unlink-after-creation would be this:
-# you need a large byte buffer that's too large to comfortably fit in RAM,
-# e.g. when you're writing a web server and you want to buffer the client's
-# file upload data.
-#
-# Please refer to #unlink for more information and a code example.
-#
-# == Minor notes
-#
-# Tempfile's filename picking method is both thread-safe and inter-process-safe:
-# it guarantees that no other threads or processes will pick the same filename.
-#
-# Tempfile itself however may not be entirely thread-safe. If you access the
-# same Tempfile object from multiple threads then you should protect it with a
-# mutex.
-class Tempfile < DelegateClass(File)
- MAX_TRY = 10 # :nodoc:
- include Dir::Tmpname
-
- # call-seq:
- # new(basename, [tmpdir = Dir.tmpdir], [options])
- #
- # Creates a temporary file with permissions 0600 (= only readable and
- # writable by the owner) and opens it with mode "w+".
- #
- # The +basename+ parameter is used to determine the name of the
- # temporary file. You can either pass a String or an Array with
- # 2 String elements. In the former form, the temporary file's base
- # name will begin with the given string. In the latter form,
- # the temporary file's base name will begin with the array's first
- # element, and end with the second element. For example:
- #
- # file = Tempfile.new('hello')
- # file.path # => something like: "/tmp/hello2843-8392-92849382--0"
- #
- # # Use the Array form to enforce an extension in the filename:
- # file = Tempfile.new(['hello', '.jpg'])
- # file.path # => something like: "/tmp/hello2843-8392-92849382--0.jpg"
- #
- # The temporary file will be placed in the directory as specified
- # by the +tmpdir+ parameter. By default, this is +Dir.tmpdir+.
- # When $SAFE > 0 and the given +tmpdir+ is tainted, it uses
- # '/tmp' as the temporary directory. Please note that ENV values
- # are tainted by default, and +Dir.tmpdir+'s return value might
- # come from environment variables (e.g. <tt>$TMPDIR</tt>).
- #
- # file = Tempfile.new('hello', '/home/aisaka')
- # file.path # => something like: "/home/aisaka/hello2843-8392-92849382--0"
- #
- # You can also pass an options hash. Under the hood, Tempfile creates
- # the temporary file using +File.open+. These options will be passed to
- # +File.open+. This is mostly useful for specifying encoding
- # options, e.g.:
- #
- # Tempfile.new('hello', '/home/aisaka', :encoding => 'ascii-8bit')
- #
- # # You can also omit the 'tmpdir' parameter:
- # Tempfile.new('hello', :encoding => 'ascii-8bit')
- #
- # === Exceptions
- #
- # If Tempfile.new cannot find a unique filename within a limited
- # number of tries, then it will raise an exception.
- def initialize(basename, *rest)
- @data = []
- @clean_proc = Remover.new(@data)
- ObjectSpace.define_finalizer(self, @clean_proc)
-
- create(basename, *rest) do |tmpname, n, opts|
- mode = File::RDWR|File::CREAT|File::EXCL
- perm = 0600
- if opts
- mode |= opts.delete(:mode) || 0
- opts[:perm] = perm
- perm = nil
- else
- opts = perm
- end
- self.class.locking(tmpname) do
- @data[1] = @tmpfile = File.open(tmpname, mode, opts)
- @data[0] = @tmpname = tmpname
- end
- @mode = mode & ~(File::CREAT|File::EXCL)
- perm or opts.freeze
- @opts = opts
- end
-
- super(@tmpfile)
- end
-
- # Opens or reopens the file with mode "r+".
- def open
- @tmpfile.close if @tmpfile
- @tmpfile = File.open(@tmpname, @mode, @opts)
- @data[1] = @tmpfile
- __setobj__(@tmpfile)
- end
-
- def _close # :nodoc:
- begin
- @tmpfile.close if @tmpfile
- ensure
- @tmpfile = nil
- @data[1] = nil if @data
- end
- end
- protected :_close
-
- # Closes the file. If +unlink_now+ is true, then the file will be unlinked
- # (deleted) after closing. Of course, you can choose to later call #unlink
- # if you do not unlink it now.
- #
- # If you don't explicitly unlink the temporary file, the removal
- # will be delayed until the object is finalized.
- def close(unlink_now=false)
- if unlink_now
- close!
- else
- _close
- end
- end
-
- # Closes and unlinks (deletes) the file. Has the same effect as called
- # <tt>close(true)</tt>.
- def close!
- _close
- unlink
- ObjectSpace.undefine_finalizer(self)
- end
-
- # Unlinks (deletes) the file from the filesystem. One should always unlink
- # the file after using it, as is explained in the "Explicit close" good
- # practice section in the Tempfile overview:
- #
- # file = Tempfile.new('foo')
- # begin
- # ...do something with file...
- # ensure
- # file.close
- # file.unlink # deletes the temp file
- # end
- #
- # === Unlink-before-close
- #
- # On POSIX systems it's possible to unlink a file before closing it. This
- # practice is explained in detail in the Tempfile overview (section
- # "Unlink after creation"); please refer there for more information.
- #
- # However, unlink-before-close may not be supported on non-POSIX operating
- # systems. Microsoft Windows is the most notable case: unlinking a non-closed
- # file will result in an error, which this method will silently ignore. If
- # you want to practice unlink-before-close whenever possible, then you should
- # write code like this:
- #
- # file = Tempfile.new('foo')
- # file.unlink # On Windows this silently fails.
- # begin
- # ... do something with file ...
- # ensure
- # file.close! # Closes the file handle. If the file wasn't unlinked
- # # because #unlink failed, then this method will attempt
- # # to do so again.
- # end
- def unlink
- return unless @tmpname
- begin
- File.unlink(@tmpname)
- rescue Errno::ENOENT
- rescue Errno::EACCES
- # may not be able to unlink on Windows; just ignore
- return
- end
- # remove tmpname from remover
- @data[0] = @data[1] = nil
- @tmpname = nil
- end
- alias delete unlink
-
- # Returns the full path name of the temporary file.
- # This will be nil if #unlink has been called.
- def path
- @tmpname
- end
-
- # Returns the size of the temporary file. As a side effect, the IO
- # buffer is flushed before determining the size.
- def size
- if @tmpfile
- @tmpfile.flush
- @tmpfile.stat.size
- elsif @tmpname
- File.size(@tmpname)
- else
- 0
- end
- end
- alias length size
-
- # :stopdoc:
- class Remover
- def initialize(data)
- @pid = $$
- @data = data
- end
-
- def call(*args)
- return if @pid != $$
-
- path, tmpfile = *@data
-
- STDERR.print "removing ", path, "..." if $DEBUG
-
- tmpfile.close if tmpfile
-
- if path
- begin
- File.unlink(path)
- rescue Errno::ENOENT
- end
- end
-
- STDERR.print "done\n" if $DEBUG
- end
- end
- # :startdoc:
-
- class << self
- # Creates a new Tempfile.
- #
- # If no block is given, this is a synonym for Tempfile.new.
- #
- # If a block is given, then a Tempfile object will be constructed,
- # and the block is run with said object as argument. The Tempfile
- # oject will be automatically closed after the block terminates.
- # The call returns the value of the block.
- #
- # In any case, all arguments (+*args+) will be passed to Tempfile.new.
- #
- # Tempfile.open('foo', '/home/temp') do |f|
- # ... do something with f ...
- # end
- #
- # # Equivalent:
- # f = Tempfile.open('foo', '/home/temp')
- # begin
- # ... do something with f ...
- # ensure
- # f.close
- # end
- def open(*args)
- tempfile = new(*args)
-
- if block_given?
- begin
- yield(tempfile)
- ensure
- tempfile.close
- end
- else
- tempfile
- end
- end
-
- # :stopdoc:
-
- # yields with locking for +tmpname+ and returns the result of the
- # block.
- def locking(tmpname)
- lock = tmpname + '.lock'
- mkdir(lock)
- yield
- ensure
- rmdir(lock) if lock
- end
-
- def mkdir(*args)
- Dir.mkdir(*args)
- end
-
- def rmdir(*args)
- Dir.rmdir(*args)
- end
- end
-end
-
-if __FILE__ == $0
-# $DEBUG = true
- f = Tempfile.new("foo")
- f.print("foo\n")
- f.close
- f.open
- p f.gets # => "foo\n"
- f.close!
-end
diff --git a/ruby_1_9_3/lib/test/unit.rb b/ruby_1_9_3/lib/test/unit.rb
deleted file mode 100644
index 09708d14df..0000000000
--- a/ruby_1_9_3/lib/test/unit.rb
+++ /dev/null
@@ -1,640 +0,0 @@
-# test/unit compatibility layer using minitest.
-
-require 'minitest/unit'
-require 'test/unit/assertions'
-require 'test/unit/testcase'
-require 'optparse'
-
-module Test
- module Unit
- TEST_UNIT_IMPLEMENTATION = 'test/unit compatibility layer using minitest'
-
- module RunCount
- @@run_count = 0
-
- def self.have_run?
- @@run_count.nonzero?
- end
-
- def run(*)
- @@run_count += 1
- super
- end
-
- def run_once
- return if have_run?
- return if $! # don't run if there was an exception
- yield
- end
- module_function :run_once
- end
-
- module Options
- def initialize(*, &block)
- @init_hook = block
- @options = nil
- super(&nil)
- end
-
- def option_parser
- @option_parser ||= OptionParser.new
- end
-
- def process_args(args = [])
- return @options if @options
- orig_args = args.dup
- options = {}
- opts = option_parser
- setup_options(opts, options)
- opts.parse!(args)
- orig_args -= args
- args = @init_hook.call(args, options) if @init_hook
- non_options(args, options)
- @help = orig_args.map { |s| s =~ /[\s|&<>$()]/ ? s.inspect : s }.join " "
- @options = options
- if @options[:parallel]
- @files = args
- @args = orig_args
- end
- options
- end
-
- private
- def setup_options(opts, options)
- opts.separator 'minitest options:'
- opts.version = MiniTest::Unit::VERSION
-
- opts.on '-h', '--help', 'Display this help.' do
- puts opts
- exit
- end
-
- opts.on '-s', '--seed SEED', Integer, "Sets random seed" do |m|
- options[:seed] = m
- end
-
- opts.on '-v', '--verbose', "Verbose. Show progress processing files." do
- options[:verbose] = true
- self.verbose = options[:verbose]
- end
-
- opts.on '-n', '--name PATTERN', "Filter test names on pattern." do |a|
- options[:filter] = a
- end
-
- opts.on '--jobs-status [TYPE]', [:normal, :replace],
- "Show status of jobs every file; Disabled when --jobs isn't specified." do |type|
- options[:job_status] = type || :normal
- end
-
- opts.on '-j N', '--jobs N', "Allow run tests with N jobs at once" do |a|
- if /^t/ =~ a
- options[:testing] = true # For testing
- options[:parallel] = a[1..-1].to_i
- else
- options[:parallel] = a.to_i
- end
- end
-
- opts.on '--no-retry', "Don't retry running testcase when --jobs specified" do
- options[:no_retry] = true
- end
-
- opts.on '--ruby VAL', "Path to ruby; It'll have used at -j option" do |a|
- options[:ruby] = a.split(/ /).reject(&:empty?)
- end
-
- opts.on '-q', '--hide-skip', 'Hide skipped tests' do
- options[:hide_skip] = true
- end
- end
-
- def non_options(files, options)
- begin
- require "rbconfig"
- rescue LoadError
- warn "#{caller(1)[0]}: warning: Parallel running disabled because can't get path to ruby; run specify with --ruby argument"
- options[:parallel] = nil
- else
- options[:ruby] ||= RbConfig.ruby
- end
-
- true
- end
- end
-
- module GlobOption
- include Options
-
- @@testfile_prefix = "test"
-
- def setup_options(parser, options)
- super
- parser.on '-b', '--basedir=DIR', 'Base directory of test suites.' do |dir|
- options[:base_directory] = dir
- end
- parser.on '-x', '--exclude PATTERN', 'Exclude test files on pattern.' do |pattern|
- (options[:reject] ||= []) << pattern
- end
- end
-
- def non_options(files, options)
- paths = [options.delete(:base_directory), nil].uniq
- if reject = options.delete(:reject)
- reject_pat = Regexp.union(reject.map {|r| /#{r}/ })
- end
- files.map! {|f|
- f = f.tr(File::ALT_SEPARATOR, File::SEPARATOR) if File::ALT_SEPARATOR
- ((paths if /\A\.\.?(?:\z|\/)/ !~ f) || [nil]).any? do |prefix|
- if prefix
- path = f.empty? ? prefix : "#{prefix}/#{f}"
- else
- next if f.empty?
- path = f
- end
- if !(match = Dir["#{path}/**/#{@@testfile_prefix}_*.rb"]).empty?
- if reject
- match.reject! {|n|
- n[(prefix.length+1)..-1] if prefix
- reject_pat =~ n
- }
- end
- break match
- elsif !reject or reject_pat !~ f and File.exist? path
- break path
- end
- end or
- raise ArgumentError, "file not found: #{f}"
- }
- files.flatten!
- super(files, options)
- end
- end
-
- module LoadPathOption
- include Options
-
- def setup_options(parser, options)
- super
- parser.on '-Idirectory', 'Add library load path' do |dirs|
- dirs.split(':').each { |d| $LOAD_PATH.unshift d }
- end
- end
- end
-
- module GCStressOption
- def setup_options(parser, options)
- super
- parser.on '--[no-]gc-stress', 'Set GC.stress as true' do |flag|
- options[:gc_stress] = flag
- end
- end
-
- def non_options(files, options)
- if options.delete(:gc_stress)
- MiniTest::Unit::TestCase.class_eval do
- oldrun = instance_method(:run)
- define_method(:run) do |runner|
- begin
- gc_stress, GC.stress = GC.stress, true
- oldrun.bind(self).call(runner)
- ensure
- GC.stress = gc_stress
- end
- end
- end
- end
- super
- end
- end
-
- module RequireFiles
- def non_options(files, options)
- return false if !super
- result = false
- files.each {|f|
- d = File.dirname(path = File.expand_path(f))
- unless $:.include? d
- $: << d
- end
- begin
- require path unless options[:parallel]
- result = true
- rescue LoadError
- puts "#{f}: #{$!}"
- end
- }
- result
- end
- end
-
- class Runner < MiniTest::Unit
- include Test::Unit::Options
- include Test::Unit::GlobOption
- include Test::Unit::LoadPathOption
- include Test::Unit::GCStressOption
- include Test::Unit::RunCount
-
- class Worker
- def self.launch(ruby,args=[])
- io = IO.popen([*ruby,
- "#{File.dirname(__FILE__)}/unit/parallel.rb",
- *args], "rb+")
- new(io, io.pid, :waiting)
- end
-
- def initialize(io, pid, status)
- @io = io
- @pid = pid
- @status = status
- @file = nil
- @real_file = nil
- @loadpath = []
- @hooks = {}
- end
-
- def puts(*args)
- @io.puts(*args)
- end
-
- def run(task,type)
- @file = File.basename(task).gsub(/\.rb/,"")
- @real_file = task
- begin
- puts "loadpath #{[Marshal.dump($:-@loadpath)].pack("m").gsub("\n","")}"
- @loadpath = $:.dup
- puts "run #{task} #{type}"
- @status = :prepare
- rescue Errno::EPIPE
- died
- rescue IOError
- raise unless ["stream closed","closed stream"].include? $!.message
- died
- end
- end
-
- def hook(id,&block)
- @hooks[id] ||= []
- @hooks[id] << block
- self
- end
-
- def read
- res = (@status == :quit) ? @io.read : @io.gets
- res && res.chomp
- end
-
- def close
- @io.close
- self
- end
-
- def died(*additional)
- @status = :quit
- @io.close
-
- call_hook(:dead,*additional)
- end
-
- def to_s
- if @file
- "#{@pid}=#{@file}"
- else
- "#{@pid}:#{@status.to_s.ljust(7)}"
- end
- end
-
- attr_reader :io, :pid
- attr_accessor :status, :file, :real_file, :loadpath
-
- private
-
- def call_hook(id,*additional)
- @hooks[id] ||= []
- @hooks[id].each{|hook| hook[self,additional] }
- self
- end
-
- end
-
- class << self; undef autorun; end
-
- @@stop_auto_run = false
- def self.autorun
- at_exit {
- Test::Unit::RunCount.run_once {
- exit(Test::Unit::Runner.new.run(ARGV) || true)
- } unless @@stop_auto_run
- } unless @@installed_at_exit
- @@installed_at_exit = true
- end
-
- def after_worker_down(worker, e=nil, c=false)
- return unless @options[:parallel]
- return if @interrupt
- if e
- b = e.backtrace
- warn "#{b.shift}: #{e.message} (#{e.class})"
- STDERR.print b.map{|s| "\tfrom #{s}"}.join("\n")
- end
- @need_quit = true
- warn ""
- warn "Some worker was crashed. It seems ruby interpreter's bug"
- warn "or, a bug of test/unit/parallel.rb. try again without -j"
- warn "option."
- warn ""
- STDERR.flush
- exit c
- end
-
- def jobs_status
- return unless @options[:job_status]
- puts "" unless @options[:verbose]
- status_line = @workers.map(&:to_s).join(" ")
- if @options[:job_status] == :replace and $stdout.tty?
- @terminal_width ||=
- begin
- require 'io/console'
- $stdout.winsize[1]
- rescue LoadError, NoMethodError
- ENV["COLUMNS"].to_i.nonzero? || 80
- end
- @jstr_size ||= 0
- del_jobs_status
- $stdout.flush
- print status_line[0...@terminal_width]
- $stdout.flush
- @jstr_size = [status_line.size, @terminal_width].min
- else
- puts status_line
- end
- end
-
- def del_jobs_status
- return unless @options[:job_status] == :replace && @jstr_size.nonzero?
- print "\r"+" "*@jstr_size+"\r"
- end
-
- def after_worker_quit(worker)
- return unless @options[:parallel]
- return if @interrupt
- @workers.delete(worker)
- @dead_workers << worker
- @ios = @workers.map(&:io)
- end
-
- def _run_parallel suites, type, result
- if @options[:parallel] < 1
- warn "Error: parameter of -j option should be greater than 0."
- return
- end
-
- begin
- # Require needed things for parallel running
- require 'thread'
- require 'timeout'
- @tasks = @files.dup # Array of filenames.
- @need_quit = false
- @dead_workers = [] # Array of dead workers.
- @warnings = []
- shutting_down = false
- rep = [] # FIXME: more good naming
-
- # Array of workers.
- @workers = @options[:parallel].times.map {
- worker = Worker.launch(@options[:ruby],@args)
- worker.hook(:dead) do |w,info|
- after_worker_quit w
- after_worker_down w, *info unless info.empty?
- end
- worker
- }
-
- # Thread: watchdog
- watchdog = Thread.new do
- while stat = Process.wait2
- break if @interrupt # Break when interrupt
- pid, stat = stat
- w = (@workers + @dead_workers).find{|x| pid == x.pid }.dup
- next unless w
- unless w.status == :quit
- # Worker down
- w.died(nil, !stat.signaled? && stat.exitstatus)
- end
- end
- end
-
- @workers_hash = Hash[@workers.map {|w| [w.io,w] }] # out-IO => worker
- @ios = @workers.map{|w| w.io } # Array of worker IOs
-
- while _io = IO.select(@ios)[0]
- break unless _io.each do |io|
- break if @need_quit
- worker = @workers_hash[io]
- case worker.read
- when /^okay$/
- worker.status = :running
- jobs_status
- when /^ready$/
- worker.status = :ready
- if @tasks.empty?
- break unless @workers.find{|x| x.status == :running }
- else
- worker.run(@tasks.shift, type)
- end
-
- jobs_status
- when /^done (.+?)$/
- r = Marshal.load($1.unpack("m")[0])
- result << r[0..1] unless r[0..1] == [nil,nil]
- rep << {file: worker.real_file,
- report: r[2], result: r[3], testcase: r[5]}
- $:.push(*r[4]).uniq!
- when /^p (.+?)$/
- del_jobs_status
- print $1.unpack("m")[0]
- jobs_status if @options[:job_status] == :replace
- when /^after (.+?)$/
- @warnings << Marshal.load($1.unpack("m")[0])
- when /^bye (.+?)$/
- after_worker_down worker, Marshal.load($1.unpack("m")[0])
- when /^bye$/
- if shutting_down
- after_worker_quit worker
- else
- after_worker_down worker
- end
- end
- break if @need_quit
- end
- end
- rescue Interrupt => e
- @interrupt = e
- return result
- ensure
- shutting_down = true
-
- watchdog.kill if watchdog
- if @interrupt
- @ios.select!{|x| @workers_hash[x].status == :running }
- while !@ios.empty? && (__io = IO.select(@ios,[],[],10))
- _io = __io[0]
- _io.each do |io|
- worker = @workers_hash[io]
- case worker.read
- when /^done (.+?)$/
- r = Marshal.load($1.unpack("m")[0])
- result << r[0..1] unless r[0..1] == [nil,nil]
- rep << {file: worker.real_file,
- report: r[2], result: r[3], testcase: r[5]}
- $:.push(*r[4]).uniq!
- @ios.delete(io)
- end
- end
- end
- end
- @workers.each do |worker|
- begin
- timeout(1) do
- worker.puts "quit"
- end
- rescue Errno::EPIPE
- rescue Timeout::Error
- end
- worker.close
- end
- begin
- timeout(0.2*@workers.size) do
- Process.waitall
- end
- rescue Timeout::Error
- @workers.each do |worker|
- begin
- Process.kill(:KILL,worker.pid)
- rescue Errno::ESRCH; end
- end
- end
-
- if @interrupt || @options[:no_retry] || @need_quit
- rep.each do |r|
- report.push(*r[:report])
- end
- @errors += rep.map{|x| x[:result][0] }.inject(:+)
- @failures += rep.map{|x| x[:result][1] }.inject(:+)
- @skips += rep.map{|x| x[:result][2] }.inject(:+)
- else
- puts ""
- puts "Retrying..."
- puts ""
- rep.each do |r|
- if r[:testcase] && r[:file] && !r[:report].empty?
- require r[:file]
- _run_suite(eval(r[:testcase]),type)
- else
- report.push(*r[:report])
- @errors += r[:result][0]
- @failures += r[:result][1]
- @skips += r[:result][2]
- end
- end
- end
- if @warnings
- warn ""
- ary = []
- @warnings.reject! do |w|
- r = ary.include?(w[1].message)
- ary << w[1].message
- r
- end
- @warnings.each do |w|
- warn "#{w[0]}: #{w[1].message} (#{w[1].class})"
- end
- warn ""
- end
- end
- end
-
- def _run_suites suites, type
- @interrupt = nil
- result = []
- if @options[:parallel]
- _run_parallel suites, type, result
- else
- suites.each {|suite|
- begin
- result << _run_suite(suite, type)
- rescue Interrupt => e
- @interrupt = e
- break
- end
- }
- end
- report.reject!{|r| r.start_with? "Skipped:" } if @options[:hide_skip]
- result
- end
-
- # Overriding of MiniTest::Unit#puke
- def puke klass, meth, e
- # TODO:
- # this overriding is for minitest feature that skip messages are
- # hidden when not verbose (-v), note this is temporally.
- e = case e
- when MiniTest::Skip then
- @skips += 1
- "Skipped:\n#{meth}(#{klass}) [#{location e}]:\n#{e.message}\n"
- when MiniTest::Assertion then
- @failures += 1
- "Failure:\n#{meth}(#{klass}) [#{location e}]:\n#{e.message}\n"
- else
- @errors += 1
- bt = MiniTest::filter_backtrace(e.backtrace).join "\n "
- "Error:\n#{meth}(#{klass}):\n#{e.class}: #{e.message}\n #{bt}\n"
- end
- @report << e
- e[0, 1]
- end
-
- def status(*args)
- result = super
- raise @interrupt if @interrupt
- result
- end
- end
-
- class AutoRunner
- class Runner < Test::Unit::Runner
- include Test::Unit::RequireFiles
- end
-
- attr_accessor :to_run, :options
-
- def initialize(force_standalone = false, default_dir = nil, argv = ARGV)
- @runner = Runner.new do |files, options|
- options[:base_directory] ||= default_dir
- files << default_dir if files.empty? and default_dir
- @to_run = files
- yield self if block_given?
- files
- end
- Runner.runner = @runner
- @options = @runner.option_parser
- @argv = argv
- end
-
- def process_args(*args)
- @runner.process_args(*args)
- !@to_run.empty?
- end
-
- def run
- @runner.run(@argv) || true
- end
-
- def self.run(*args)
- new(*args).run
- end
- end
- end
-end
-
-Test::Unit::Runner.autorun
diff --git a/ruby_1_9_3/lib/test/unit/assertions.rb b/ruby_1_9_3/lib/test/unit/assertions.rb
deleted file mode 100644
index 39a3c85600..0000000000
--- a/ruby_1_9_3/lib/test/unit/assertions.rb
+++ /dev/null
@@ -1,324 +0,0 @@
-require 'minitest/unit'
-require 'pp'
-
-module Test
- module Unit
- module Assertions
- include MiniTest::Assertions
-
- def mu_pp(obj) #:nodoc:
- obj.pretty_inspect.chomp
- end
-
- MINI_DIR = File.join(File.dirname(File.dirname(File.expand_path(__FILE__))), "minitest") #:nodoc:
-
- UNASSIGNED = Object.new # :nodoc:
-
- # :call-seq:
- # assert( test, failure_message = UNASSIGNED )
- #
- #Tests if +test+ is true.
- #
- #+msg+ may be a String or a Proc. If +msg+ is a String, it will be used
- #as the failure message. Otherwise, the result of calling +msg+ will be
- #used as the message if the assertion fails.
- #
- #If no +msg+ is given, a default message will be used.
- #
- # assert(false, "This was expected to be true")
- def assert(test, msg = UNASSIGNED)
- case msg
- when UNASSIGNED
- msg = nil
- when String, Proc
- else
- bt = caller.reject { |s| s.rindex(MINI_DIR, 0) }
- raise ArgumentError, "assertion message must be String or Proc, but #{msg.class} was given.", bt
- end
- super
- end
-
- # :call-seq:
- # assert_block( failure_message = nil )
- #
- #Tests the result of the given block. If the block does not return true,
- #the assertion will fail. The optional +failure_message+ argument is the same as in
- #Assertions#assert.
- #
- # assert_block do
- # [1, 2, 3].any? { |num| num < 1 }
- # end
- def assert_block(*msgs)
- assert yield, *msgs
- end
-
- # :call-seq:
- # assert_raise( *args, &block )
- #
- #Tests if the given block raises an exception. Acceptable exception
- #types maye be given as optional arguments. If the last argument is a
- #String, it will be used as the error message.
- #
- # assert_raise do #Fails, no Exceptions are raised
- # end
- #
- # assert_raise NameError do
- # puts x #Raises NameError, so assertion succeeds
- # end
- def assert_raise(*args, &b)
- assert_raises(*args, &b)
- end
-
- # :call-seq:
- # assert_nothing_raised( *args, &block )
- #
- #If any exceptions are given as arguments, the assertion will
- #fail if one of those exceptions are raised. Otherwise, the test fails
- #if any exceptions are raised.
- #
- #The final argument may be a failure message.
- #
- # assert_nothing_raised RuntimeError do
- # raise Exception #Assertion passes, Exception is not a RuntimeError
- # end
- #
- # assert_nothing_raised do
- # raise Exception #Assertion fails
- # end
- def assert_nothing_raised(*args)
- self._assertions += 1
- if Module === args.last
- msg = nil
- else
- msg = args.pop
- end
- begin
- line = __LINE__; yield
- rescue MiniTest::Skip
- raise
- rescue Exception => e
- bt = e.backtrace
- as = e.instance_of?(MiniTest::Assertion)
- if as
- ans = /\A#{Regexp.quote(__FILE__)}:#{line}:in /o
- bt.reject! {|ln| ans =~ ln}
- end
- if ((args.empty? && !as) ||
- args.any? {|a| a.instance_of?(Module) ? e.is_a?(a) : e.class == a })
- msg = message(msg) { "Exception raised:\n<#{mu_pp(e)}>" }
- raise MiniTest::Assertion, msg.call, bt
- else
- raise
- end
- end
- nil
- end
-
- # :call-seq:
- # assert_nothing_thrown( failure_message = nil, &block )
- #
- #Fails if the given block uses a call to Kernel#throw.
- #
- #An optional failure message may be provided as the final argument.
- #
- # assert_nothing_thrown "Something was thrown!" do
- # throw :problem?
- # end
- def assert_nothing_thrown(msg=nil)
- begin
- yield
- rescue ArgumentError => error
- raise error if /\Auncaught throw (.+)\z/m !~ error.message
- msg = message(msg) { "<#{$1}> was thrown when nothing was expected" }
- flunk(msg)
- end
- assert(true, "Expected nothing to be thrown")
- end
-
- # :call-seq:
- # assert_equal( expected, actual, failure_message = nil )
- #
- #Tests if +expected+ is equal to +actual+.
- #
- #An optional failure message may be provided as the final argument.
- def assert_equal(exp, act, msg = nil)
- msg = message(msg) {
- exp_str = mu_pp(exp)
- act_str = mu_pp(act)
- exp_comment = ''
- act_comment = ''
- if exp_str == act_str
- if (exp.is_a?(String) && act.is_a?(String)) ||
- (exp.is_a?(Regexp) && act.is_a?(Regexp))
- exp_comment = " (#{exp.encoding})"
- act_comment = " (#{act.encoding})"
- elsif exp.is_a?(Float) && act.is_a?(Float)
- exp_str = "%\#.#{Float::DIG+2}g" % exp
- act_str = "%\#.#{Float::DIG+2}g" % act
- elsif exp.is_a?(Time) && act.is_a?(Time)
- if exp.subsec * 1000_000_000 == exp.nsec
- exp_comment = " (#{exp.nsec}[ns])"
- else
- exp_comment = " (subsec=#{exp.subsec})"
- end
- if act.subsec * 1000_000_000 == act.nsec
- act_comment = " (#{act.nsec}[ns])"
- else
- act_comment = " (subsec=#{act.subsec})"
- end
- elsif exp.class != act.class
- # a subclass of Range, for example.
- exp_comment = " (#{exp.class})"
- act_comment = " (#{act.class})"
- end
- elsif !Encoding.compatible?(exp_str, act_str)
- if exp.is_a?(String) && act.is_a?(String)
- exp_str = exp.dump
- act_str = act.dump
- exp_comment = " (#{exp.encoding})"
- act_comment = " (#{act.encoding})"
- else
- exp_str = exp_str.dump
- act_str = act_str.dump
- end
- end
- "<#{exp_str}>#{exp_comment} expected but was\n<#{act_str}>#{act_comment}"
- }
- assert(exp == act, msg)
- end
-
- # :call-seq:
- # assert_not_nil( expression, failure_message = nil )
- #
- #Tests if +expression+ is not nil.
- #
- #An optional failure message may be provided as the final argument.
- def assert_not_nil(exp, msg=nil)
- msg = message(msg) { "<#{mu_pp(exp)}> expected to not be nil" }
- assert(!exp.nil?, msg)
- end
-
- # :call-seq:
- # assert_not_equal( expected, actual, failure_message = nil )
- #
- #Tests if +expected+ is not equal to +actual+.
- #
- #An optional failure message may be provided as the final argument.
- def assert_not_equal(exp, act, msg=nil)
- msg = message(msg) { "<#{mu_pp(exp)}> expected to be != to\n<#{mu_pp(act)}>" }
- assert(exp != act, msg)
- end
-
- # :call-seq:
- # assert_no_match( regexp, string, failure_message = nil )
- #
- #Tests if the given Regexp does not match a given String.
- #
- #An optional failure message may be provided as the final argument.
- def assert_no_match(regexp, string, msg=nil)
- assert_instance_of(Regexp, regexp, "The first argument to assert_no_match should be a Regexp.")
- self._assertions -= 1
- msg = message(msg) { "<#{mu_pp(regexp)}> expected to not match\n<#{mu_pp(string)}>" }
- assert(regexp !~ string, msg)
- end
-
- # :call-seq:
- # assert_not_same( expected, actual, failure_message = nil )
- #
- #Tests if +expected+ is not the same object as +actual+.
- #This test uses Object#equal? to test equality.
- #
- #An optional failure message may be provided as the final argument.
- #
- # assert_not_same("x", "x") #Succeeds
- def assert_not_same(expected, actual, message="")
- msg = message(msg) { build_message(message, <<EOT, expected, expected.__id__, actual, actual.__id__) }
-<?>
-with id <?> expected to not be equal\\? to
-<?>
-with id <?>.
-EOT
- assert(!actual.equal?(expected), msg)
- end
-
- # :call-seq:
- # assert_respond_to( object, method, failure_message = nil )
- #
- #Tests if the given Object responds to +method+.
- #
- #An optional failure message may be provided as the final argument.
- #
- # assert_respond_to("hello", :reverse) #Succeeds
- # assert_respond_to("hello", :does_not_exist) #Fails
- def assert_respond_to obj, meth, msg = nil
- #get rid of overcounting
- super if !caller[0].rindex(MINI_DIR, 0) || !obj.respond_to?(meth)
- end
-
- # :call-seq:
- # assert_send( +send_array+, failure_message = nil )
- #
- # 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], :member?, 1]) # -> pass
- # assert_send([[1, 2], :member?, 4]) # -> fail
- def assert_send send_ary, m = nil
- recv, msg, *args = send_ary
- m = message(m) {
- if args.empty?
- argsstr = ""
- else
- (argsstr = mu_pp(args)).sub!(/\A\[(.*)\]\z/m, '(\1)')
- end
- "Expected #{mu_pp(recv)}.#{msg}#{argsstr} to return true"
- }
- assert recv.__send__(msg, *args), m
- end
-
- # :call-seq:
- # assert_not_send( +send_array+, failure_message = nil )
- #
- # Passes if the method send doesn't return a true value.
- #
- # +send_array+ is composed of:
- # * A receiver
- # * A method
- # * Arguments to the method
- #
- # Example:
- # assert_not_send([[1, 2], :member?, 1]) # -> fail
- # assert_not_send([[1, 2], :member?, 4]) # -> pass
- def assert_not_send send_ary, m = nil
- recv, msg, *args = send_ary
- m = message(m) {
- if args.empty?
- argsstr = ""
- else
- (argsstr = mu_pp(args)).sub!(/\A\[(.*)\]\z/m, '(\1)')
- end
- "Expected #{mu_pp(recv)}.#{msg}#{argsstr} to return false"
- }
- assert !recv.__send__(msg, *args), m
- end
-
- ms = instance_methods(true).map {|sym| sym.to_s }
- ms.grep(/\Arefute_/) do |m|
- mname = ('assert_not_' << m.to_s[/.*?_(.*)/, 1])
- alias_method(mname, m) unless ms.include? mname
- end
- alias assert_include assert_includes
- alias assert_not_include assert_not_includes
-
- def build_message(head, template=nil, *arguments) #:nodoc:
- template &&= template.chomp
- template.gsub(/\G((?:[^\\]|\\.)*?)(\\)?\?/) { $1 + ($2 ? "?" : mu_pp(arguments.shift)) }
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/test/unit/parallel.rb b/ruby_1_9_3/lib/test/unit/parallel.rb
deleted file mode 100644
index bb95a54f78..0000000000
--- a/ruby_1_9_3/lib/test/unit/parallel.rb
+++ /dev/null
@@ -1,161 +0,0 @@
-require 'test/unit'
-
-module Test
- module Unit
- class Worker < Runner
- class << self
- undef autorun
- end
-
- alias orig_run_suite _run_suite
- undef _run_suite
- undef _run_suites
- undef run
-
- def increment_io(orig)
- *rest, io = 32.times.inject([orig.dup]){|ios, | ios << ios.last.dup }
- rest.each(&:close)
- io
- end
-
- def _run_suites(suites, type)
- suites.map do |suite|
- _run_suite(suite, type)
- end
- end
-
- def _run_suite(suite, type)
- r = report.dup
- orig_testout = MiniTest::Unit.output
- i,o = IO.pipe
-
- MiniTest::Unit.output = o
- orig_stdin, orig_stdout = $stdin, $stdout
-
- th = Thread.new do
- begin
- while buf = (self.verbose ? i.gets : i.read(5))
- @stdout.puts "p #{[buf].pack("m").gsub("\n","")}"
- end
- rescue IOError
- rescue Errno::EPIPE
- end
- end
-
- e, f, s = @errors, @failures, @skips
-
- begin
- result = orig_run_suite(suite, type)
- rescue Interrupt
- @need_exit = true
- result = [nil,nil]
- end
-
- MiniTest::Unit.output = orig_testout
- $stdin = orig_stdin
- $stdout = orig_stdout
-
- o.close
- begin
- th.join
- rescue IOError
- raise unless ["stream closed","closed stream"].include? $!.message
- end
- i.close
-
- result << (report - r)
- result << [@errors-e,@failures-f,@skips-s]
- result << ($: - @old_loadpath)
- result << suite.name
-
- begin
- @stdout.puts "done #{[Marshal.dump(result)].pack("m").gsub("\n","")}"
- rescue Errno::EPIPE; end
- return result
- ensure
- MiniTest::Unit.output = orig_stdout
- $stdin = orig_stdin
- $stdout = orig_stdout
- o.close if o && !o.closed?
- i.close if i && !i.closed?
- end
-
- def run(args = [])
- process_args args
- @@stop_auto_run = true
- @opts = @options.dup
- @need_exit = false
-
- @old_loadpath = []
- begin
- @stdout = increment_io(STDOUT)
- @stdin = increment_io(STDIN)
- @stdout.sync = true
- @stdout.puts "ready"
- while buf = @stdin.gets
- case buf.chomp
- when /^loadpath (.+?)$/
- @old_loadpath = $:.dup
- $:.push(*Marshal.load($1.unpack("m")[0].force_encoding("ASCII-8BIT"))).uniq!
- when /^run (.+?) (.+?)$/
- @stdout.puts "okay"
-
- @options = @opts.dup
- suites = MiniTest::Unit::TestCase.test_suites
-
- begin
- require $1
- rescue LoadError
- @stdout.puts "after #{[Marshal.dump([$1, $!])].pack("m").gsub("\n","")}"
- @stdout.puts "ready"
- next
- end
- _run_suites MiniTest::Unit::TestCase.test_suites-suites, $2.to_sym
-
- if @need_exit
- begin
- @stdout.puts "bye"
- rescue Errno::EPIPE; end
- exit
- else
- @stdout.puts "ready"
- end
- when /^quit$/
- begin
- @stdout.puts "bye"
- rescue Errno::EPIPE; end
- exit
- end
- end
- rescue Errno::EPIPE
- rescue Exception => e
- begin
- @stdout.puts "bye #{[Marshal.dump(e)].pack("m").gsub("\n","")}"
- rescue Errno::EPIPE;end
- exit
- ensure
- @stdin.close
- @stdout.close
- end
- end
- end
- end
-end
-
-if $0 == __FILE__
- module Test
- module Unit
- class TestCase < MiniTest::Unit::TestCase
- def on_parallel_worker?
- true
- end
- end
- end
- end
- require 'rubygems'
- class Gem::TestCase < MiniTest::Unit::TestCase
- @@project_dir = File.expand_path('../../../..', __FILE__)
- end
-
- Test::Unit::Worker.new.run(ARGV)
-end
diff --git a/ruby_1_9_3/lib/test/unit/testcase.rb b/ruby_1_9_3/lib/test/unit/testcase.rb
deleted file mode 100644
index 02f0f97987..0000000000
--- a/ruby_1_9_3/lib/test/unit/testcase.rb
+++ /dev/null
@@ -1,25 +0,0 @@
-require 'test/unit/assertions'
-
-module Test
- module Unit
- # remove silly TestCase class
- remove_const(:TestCase) if defined?(self::TestCase)
-
- class TestCase < MiniTest::Unit::TestCase
- include Assertions
-
- def on_parallel_worker?
- false
- end
-
- def run runner
- @options = runner.options
- super runner
- end
-
- def self.test_order
- :sorted
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/thread.rb b/ruby_1_9_3/lib/thread.rb
deleted file mode 100644
index 58c4f6b9e6..0000000000
--- a/ruby_1_9_3/lib/thread.rb
+++ /dev/null
@@ -1,361 +0,0 @@
-#
-# thread.rb - thread support classes
-# by Yukihiro Matsumoto <matz@netlab.co.jp>
-#
-# Copyright (C) 2001 Yukihiro Matsumoto
-# Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
-# Copyright (C) 2000 Information-technology Promotion Agency, Japan
-#
-
-unless defined? Thread
- raise "Thread not available for this ruby interpreter"
-end
-
-unless defined? ThreadError
- class ThreadError < StandardError
- end
-end
-
-if $DEBUG
- Thread.abort_on_exception = true
-end
-
-#
-# ConditionVariable objects augment class Mutex. Using condition variables,
-# it is possible to suspend while in the middle of a critical section until a
-# resource becomes available.
-#
-# Example:
-#
-# require 'thread'
-#
-# mutex = Mutex.new
-# resource = ConditionVariable.new
-#
-# a = Thread.new {
-# mutex.synchronize {
-# # Thread 'a' now needs the resource
-# resource.wait(mutex)
-# # 'a' can now have the resource
-# }
-# }
-#
-# b = Thread.new {
-# mutex.synchronize {
-# # Thread 'b' has finished using the resource
-# resource.signal
-# }
-# }
-#
-class ConditionVariable
- #
- # Creates a new ConditionVariable
- #
- def initialize
- @waiters = []
- @waiters_mutex = Mutex.new
- end
-
- #
- # Releases the lock held in +mutex+ and waits; reacquires the lock on wakeup.
- #
- # If +timeout+ is given, this method returns after +timeout+ seconds passed,
- # even if no other thread doesn't signal.
- #
- def wait(mutex, timeout=nil)
- begin
- # TODO: mutex should not be used
- @waiters_mutex.synchronize do
- @waiters.push(Thread.current)
- end
- mutex.sleep timeout
- ensure
- @waiters_mutex.synchronize do
- @waiters.delete(Thread.current)
- end
- end
- self
- end
-
- #
- # Wakes up the first thread in line waiting for this lock.
- #
- def signal
- begin
- t = @waiters_mutex.synchronize { @waiters.shift }
- t.run if t
- rescue ThreadError
- retry
- end
- self
- end
-
- #
- # Wakes up all threads waiting for this lock.
- #
- def broadcast
- # TODO: incomplete
- waiters0 = nil
- @waiters_mutex.synchronize do
- waiters0 = @waiters.dup
- @waiters.clear
- end
- for t in waiters0
- begin
- t.run
- rescue ThreadError
- end
- end
- self
- end
-end
-
-#
-# This class provides a way to synchronize communication between threads.
-#
-# Example:
-#
-# require 'thread'
-#
-# queue = Queue.new
-#
-# producer = Thread.new do
-# 5.times do |i|
-# sleep rand(i) # simulate expense
-# queue << i
-# puts "#{i} produced"
-# end
-# end
-#
-# consumer = Thread.new do
-# 5.times do |i|
-# value = queue.pop
-# sleep rand(i/2) # simulate expense
-# puts "consumed #{value}"
-# end
-# end
-#
-# consumer.join
-#
-class Queue
- #
- # Creates a new queue.
- #
- def initialize
- @que = []
- @waiting = []
- @que.taint # enable tainted communication
- @waiting.taint
- self.taint
- @mutex = Mutex.new
- end
-
- #
- # Pushes +obj+ to the queue.
- #
- def push(obj)
- @mutex.synchronize{
- @que.push obj
- begin
- t = @waiting.shift
- t.wakeup if t
- rescue ThreadError
- retry
- end
- }
- end
-
- #
- # Alias of push
- #
- alias << push
-
- #
- # Alias of push
- #
- alias enq push
-
- #
- # Retrieves data from the queue. If the queue is empty, the calling thread is
- # suspended until data is pushed onto the queue. If +non_block+ is true, the
- # thread isn't suspended, and an exception is raised.
- #
- def pop(non_block=false)
- @mutex.synchronize{
- while true
- if @que.empty?
- raise ThreadError, "queue empty" if non_block
- @waiting.push Thread.current
- @mutex.sleep
- else
- return @que.shift
- end
- end
- }
- end
-
- #
- # Alias of pop
- #
- alias shift pop
-
- #
- # Alias of pop
- #
- alias deq pop
-
- #
- # Returns +true+ if the queue is empty.
- #
- def empty?
- @que.empty?
- end
-
- #
- # Removes all objects from the queue.
- #
- def clear
- @que.clear
- end
-
- #
- # Returns the length of the queue.
- #
- def length
- @que.length
- end
-
- #
- # Alias of length.
- #
- alias size length
-
- #
- # Returns the number of threads waiting on the queue.
- #
- def num_waiting
- @waiting.size
- end
-end
-
-#
-# This class represents queues of specified size capacity. The push operation
-# may be blocked if the capacity is full.
-#
-# See Queue for an example of how a SizedQueue works.
-#
-class SizedQueue < Queue
- #
- # Creates a fixed-length queue with a maximum size of +max+.
- #
- def initialize(max)
- raise ArgumentError, "queue size must be positive" unless max > 0
- @max = max
- @queue_wait = []
- @queue_wait.taint # enable tainted comunication
- super()
- end
-
- #
- # Returns the maximum size of the queue.
- #
- def max
- @max
- end
-
- #
- # Sets the maximum size of the queue.
- #
- def max=(max)
- diff = nil
- @mutex.synchronize {
- if max <= @max
- @max = max
- else
- diff = max - @max
- @max = max
- end
- }
- if diff
- diff.times do
- begin
- t = @queue_wait.shift
- t.run if t
- rescue ThreadError
- retry
- end
- end
- end
- max
- end
-
- #
- # Pushes +obj+ to the queue. If there is no space left in the queue, waits
- # until space becomes available.
- #
- def push(obj)
- @mutex.synchronize{
- while true
- break if @que.length < @max
- @queue_wait.push Thread.current
- @mutex.sleep
- end
-
- @que.push obj
- begin
- t = @waiting.shift
- t.wakeup if t
- rescue ThreadError
- retry
- end
- }
- end
-
- #
- # Alias of push
- #
- alias << push
-
- #
- # Alias of push
- #
- alias enq push
-
- #
- # Retrieves data from the queue and runs a waiting thread, if any.
- #
- def pop(*args)
- retval = super
- @mutex.synchronize {
- if @que.length < @max
- begin
- t = @queue_wait.shift
- t.wakeup if t
- rescue ThreadError
- retry
- end
- end
- }
- retval
- end
-
- #
- # Alias of pop
- #
- alias shift pop
-
- #
- # Alias of pop
- #
- alias deq pop
-
- #
- # Returns the number of threads waiting on the queue.
- #
- def num_waiting
- @waiting.size + @queue_wait.size
- end
-end
-
-# Documentation comments:
-# - How do you make RDoc inherit documentation from superclass?
diff --git a/ruby_1_9_3/lib/thwait.rb b/ruby_1_9_3/lib/thwait.rb
deleted file mode 100644
index f5876236e4..0000000000
--- a/ruby_1_9_3/lib/thwait.rb
+++ /dev/null
@@ -1,142 +0,0 @@
-#
-# thwait.rb - thread synchronization class
-# $Release Version: 0.9 $
-# $Revision: 1.3 $
-# by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd.)
-
-require "thread.rb"
-require "e2mmap.rb"
-
-#
-# This class watches for termination of multiple threads. Basic functionality
-# (wait until specified threads have terminated) can be accessed through the
-# class method ThreadsWait::all_waits. Finer control can be gained using
-# instance methods.
-#
-# Example:
-#
-# ThreadsWait.all_wait(thr1, thr2, ...) do |t|
-# STDERR.puts "Thread #{t} has terminated."
-# end
-#
-#
-# th = ThreadsWait.new(thread1,...)
-# th.next_wait # next one to be done
-#
-#
-class ThreadsWait
- RCS_ID='-$Id: thwait.rb,v 1.3 1998/06/26 03:19:34 keiju Exp keiju $-'
-
- extend Exception2MessageMapper
- def_exception("ErrNoWaitingThread", "No threads for waiting.")
- def_exception("ErrNoFinishedThread", "No finished threads.")
-
- #
- # Waits until all specified threads have terminated. If a block is provided,
- # it is executed for each thread as they terminate.
- #
- def ThreadsWait.all_waits(*threads) # :yield: thread
- tw = ThreadsWait.new(*threads)
- if block_given?
- tw.all_waits do |th|
- yield th
- end
- else
- tw.all_waits
- end
- end
-
- #
- # Creates a ThreadsWait object, specifying the threads to wait on.
- # Non-blocking.
- #
- def initialize(*threads)
- @threads = []
- @wait_queue = Queue.new
- join_nowait(*threads) unless threads.empty?
- end
-
- # Returns the array of threads that have not terminated yet.
- attr :threads
-
- #
- # Returns +true+ if there are no threads in the pool still running.
- #
- def empty?
- @threads.empty?
- end
-
- #
- # Returns +true+ if any thread has terminated and is ready to be collected.
- #
- def finished?
- !@wait_queue.empty?
- end
-
- #
- # Waits for specified threads to terminate, and returns when one of
- # the threads terminated.
- #
- def join(*threads)
- join_nowait(*threads)
- next_wait
- end
-
- #
- # Specifies the threads that this object will wait for, but does not actually
- # wait.
- #
- def join_nowait(*threads)
- threads.flatten!
- @threads.concat threads
- for th in threads
- Thread.start(th) do |t|
- begin
- t.join
- ensure
- @wait_queue.push t
- end
- end
- end
- end
-
- #
- # Waits until any of the specified threads has terminated, and returns the one
- # that does.
- #
- # If there is no thread to wait, raises +ErrNoWaitingThread+. If +nonblock+
- # is true, and there is no terminated thread, raises +ErrNoFinishedThread+.
- #
- def next_wait(nonblock = nil)
- ThreadsWait.fail ErrNoWaitingThread if @threads.empty?
- begin
- @threads.delete(th = @wait_queue.pop(nonblock))
- th
- rescue ThreadError
- ThreadsWait.fail ErrNoFinishedThread
- end
- end
-
- #
- # Waits until all of the specified threads are terminated. If a block is
- # supplied for the method, it is executed for each thread termination.
- #
- # Raises exceptions in the same manner as +next_wait+.
- #
- def all_waits
- until @threads.empty?
- th = next_wait
- yield th if block_given?
- end
- end
-end
-
-##
-# An alias for ThreadsWait from thwait.rb
-
-ThWait = ThreadsWait
-
-# Documentation comments:
-# - Source of documentation is evenly split between Nutshell, existing
-# comments, and my own rephrasing.
-# - I'm not particularly confident that the comments are all exactly correct.
diff --git a/ruby_1_9_3/lib/time.rb b/ruby_1_9_3/lib/time.rb
deleted file mode 100644
index 1663af8e76..0000000000
--- a/ruby_1_9_3/lib/time.rb
+++ /dev/null
@@ -1,541 +0,0 @@
-
-#
-# == Introduction
-#
-# This library extends the Time class:
-# * conversion between date string and time object.
-# * date-time defined by RFC 2822
-# * HTTP-date defined by RFC 2616
-# * dateTime defined by XML Schema Part 2: Datatypes (ISO 8601)
-# * various formats handled by Date._parse (string to time only)
-#
-# == Design Issues
-#
-# === Specialized interface
-#
-# This library provides methods dedicated to special purposes:
-# * RFC 2822, RFC 2616 and XML Schema.
-# * They makes usual life easier.
-#
-# === Doesn't depend on strftime
-#
-# This library doesn't use +Time#strftime+. Especially #rfc2822 doesn't depend
-# on +strftime+ because:
-#
-# * %a and %b are locale sensitive
-#
-# Since they are locale sensitive, they may be replaced to
-# invalid weekday/month name in some locales.
-# Since ruby-1.6 doesn't invoke setlocale by default,
-# the problem doesn't arise until some external library invokes setlocale.
-# Ruby/GTK is the example of such library.
-#
-# * %z is not portable
-#
-# %z is required to generate zone in date-time of RFC 2822
-# but it is not portable.
-#
-# Note that +Time#strftime+ doesn't use +strftime()+ function in libc since Ruby 1.9.
-# This means +Time#strftime+ is locale-insensitive since Ruby 1.9.
-# The above statements are not valid now.
-#
-
-require 'date'
-
-#
-# Implements the extensions to the Time class that are described in the
-# documentation for the time.rb library.
-#
-class Time
- class << Time
-
- ZoneOffset = {
- 'UTC' => 0,
- # ISO 8601
- 'Z' => 0,
- # RFC 822
- 'UT' => 0, 'GMT' => 0,
- 'EST' => -5, 'EDT' => -4,
- 'CST' => -6, 'CDT' => -5,
- 'MST' => -7, 'MDT' => -6,
- 'PST' => -8, 'PDT' => -7,
- # Following definition of military zones is original one.
- # See RFC 1123 and RFC 2822 for the error in RFC 822.
- 'A' => +1, 'B' => +2, 'C' => +3, 'D' => +4, 'E' => +5, 'F' => +6,
- 'G' => +7, 'H' => +8, 'I' => +9, 'K' => +10, 'L' => +11, 'M' => +12,
- 'N' => -1, 'O' => -2, 'P' => -3, 'Q' => -4, 'R' => -5, 'S' => -6,
- 'T' => -7, 'U' => -8, 'V' => -9, 'W' => -10, 'X' => -11, 'Y' => -12,
- }
- def zone_offset(zone, year=self.now.year)
- off = nil
- zone = zone.upcase
- if /\A([+-])(\d\d):?(\d\d)\z/ =~ zone
- off = ($1 == '-' ? -1 : 1) * ($2.to_i * 60 + $3.to_i) * 60
- elsif /\A[+-]\d\d\z/ =~ zone
- off = zone.to_i * 3600
- elsif ZoneOffset.include?(zone)
- off = ZoneOffset[zone] * 3600
- elsif ((t = self.local(year, 1, 1)).zone.upcase == zone rescue false)
- off = t.utc_offset
- elsif ((t = self.local(year, 7, 1)).zone.upcase == zone rescue false)
- off = t.utc_offset
- end
- off
- end
-
- def zone_utc?(zone)
- # * +0000
- # In RFC 2822, +0000 indicate a time zone at Universal Time.
- # Europe/London is "a time zone at Universal Time" in Winter.
- # Europe/Lisbon is "a time zone at Universal Time" in Winter.
- # Atlantic/Reykjavik is "a time zone at Universal Time".
- # Africa/Dakar is "a time zone at Universal Time".
- # So +0000 is a local time such as Europe/London, etc.
- # * GMT
- # GMT is used as a time zone abbreviation in Europe/London,
- # Africa/Dakar, etc.
- # So it is a local time.
- #
- # * -0000, -00:00
- # In RFC 2822, -0000 the date-time contains no information about the
- # local time zone.
- # In RFC 3339, -00:00 is used for the time in UTC is known,
- # but the offset to local time is unknown.
- # They are not appropriate for specific time zone such as
- # Europe/London because time zone neutral,
- # So -00:00 and -0000 are treated as UTC.
- if /\A(?:-00:00|-0000|-00|UTC|Z|UT)\z/i =~ zone
- true
- else
- false
- end
- end
- private :zone_utc?
-
- LeapYearMonthDays = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
- CommonYearMonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
- def month_days(y, m)
- if ((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)
- LeapYearMonthDays[m-1]
- else
- CommonYearMonthDays[m-1]
- end
- end
- private :month_days
-
- def apply_offset(year, mon, day, hour, min, sec, off)
- if off < 0
- off = -off
- off, o = off.divmod(60)
- if o != 0 then sec += o; o, sec = sec.divmod(60); off += o end
- off, o = off.divmod(60)
- if o != 0 then min += o; o, min = min.divmod(60); off += o end
- off, o = off.divmod(24)
- if o != 0 then hour += o; o, hour = hour.divmod(24); off += o end
- if off != 0
- day += off
- if month_days(year, mon) < day
- mon += 1
- if 12 < mon
- mon = 1
- year += 1
- end
- day = 1
- end
- end
- elsif 0 < off
- off, o = off.divmod(60)
- if o != 0 then sec -= o; o, sec = sec.divmod(60); off -= o end
- off, o = off.divmod(60)
- if o != 0 then min -= o; o, min = min.divmod(60); off -= o end
- off, o = off.divmod(24)
- if o != 0 then hour -= o; o, hour = hour.divmod(24); off -= o end
- if off != 0 then
- day -= off
- if day < 1
- mon -= 1
- if mon < 1
- year -= 1
- mon = 12
- end
- day = month_days(year, mon)
- end
- end
- end
- return year, mon, day, hour, min, sec
- end
- private :apply_offset
-
- def make_time(year, mon, day, hour, min, sec, sec_fraction, zone, now)
- usec = nil
- usec = sec_fraction * 1000000 if sec_fraction
- if now
- begin
- break if year; year = now.year
- break if mon; mon = now.mon
- break if day; day = now.day
- break if hour; hour = now.hour
- break if min; min = now.min
- break if sec; sec = now.sec
- break if sec_fraction; usec = now.tv_usec
- end until true
- end
-
- year ||= 1970
- mon ||= 1
- day ||= 1
- hour ||= 0
- min ||= 0
- sec ||= 0
- usec ||= 0
-
- off = nil
- off = zone_offset(zone, year) if zone
-
- if off
- year, mon, day, hour, min, sec =
- apply_offset(year, mon, day, hour, min, sec, off)
- t = self.utc(year, mon, day, hour, min, sec, usec)
- t.localtime if !zone_utc?(zone)
- t
- else
- self.local(year, mon, day, hour, min, sec, usec)
- end
- end
- private :make_time
-
- #
- # Parses +date+ using Date._parse and converts it to a Time object.
- #
- # If a block is given, the year described in +date+ is converted by the
- # block. For example:
- #
- # Time.parse(...) {|y| 0 <= y && y < 100 ? (y >= 69 ? y + 1900 : y + 2000) : y}
- #
- # If the upper components of the given time are broken or missing, they are
- # supplied with those of +now+. For the lower components, the minimum
- # values (1 or 0) are assumed if broken or missing. For example:
- #
- # # Suppose it is "Thu Nov 29 14:33:20 GMT 2001" now and
- # # your timezone is GMT:
- # now = Time.parse("Thu Nov 29 14:33:20 GMT 2001")
- # Time.parse("16:30", now) #=> 2001-11-29 16:30:00 +0900
- # Time.parse("7/23", now) #=> 2001-07-23 00:00:00 +0900
- # Time.parse("Aug 31", now) #=> 2001-08-31 00:00:00 +0900
- # Time.parse("Aug 2000", now) #=> 2000-08-01 00:00:00 +0900
- #
- # Since there are numerous conflicts among locally defined timezone
- # abbreviations all over the world, this method is not made to
- # understand all of them. For example, the abbreviation "CST" is
- # used variously as:
- #
- # -06:00 in America/Chicago,
- # -05:00 in America/Havana,
- # +08:00 in Asia/Harbin,
- # +09:30 in Australia/Darwin,
- # +10:30 in Australia/Adelaide,
- # etc.
- #
- # Based on the fact, this method only understands the timezone
- # abbreviations described in RFC 822 and the system timezone, in the
- # order named. (i.e. a definition in RFC 822 overrides the system
- # timezone definition.) The system timezone is taken from
- # <tt>Time.local(year, 1, 1).zone</tt> and
- # <tt>Time.local(year, 7, 1).zone</tt>.
- # If the extracted timezone abbreviation does not match any of them,
- # it is ignored and the given time is regarded as a local time.
- #
- # ArgumentError is raised if Date._parse cannot extract information from
- # +date+ or Time class cannot represent specified date.
- #
- # This method can be used as fail-safe for other parsing methods as:
- #
- # Time.rfc2822(date) rescue Time.parse(date)
- # Time.httpdate(date) rescue Time.parse(date)
- # Time.xmlschema(date) rescue Time.parse(date)
- #
- # A failure for Time.parse should be checked, though.
- #
- # time library should be required to use this method as follows.
- #
- # require 'time'
- #
- def parse(date, now=self.now)
- comp = !block_given?
- d = Date._parse(date, comp)
- if !d[:year] && !d[:mon] && !d[:mday] && !d[:hour] && !d[:min] && !d[:sec] && !d[:sec_fraction]
- raise ArgumentError, "no time information in #{date.inspect}"
- end
- year = d[:year]
- year = yield(year) if year && !comp
- make_time(year, d[:mon], d[:mday], d[:hour], d[:min], d[:sec], d[:sec_fraction], d[:zone], now)
- end
-
- #
- # Parses +date+ using Date._strptime and converts it to a Time object.
- #
- # If a block is given, the year described in +date+ is converted by the
- # block. For example:
- #
- # Time.strptime(...) {|y| y < 100 ? (y >= 69 ? y + 1900 : y + 2000) : y}
- def strptime(date, format, now=self.now)
- d = Date._strptime(date, format)
- raise ArgumentError, "invalid strptime format - `#{format}'" unless d
- if seconds = d[:seconds]
- Time.at(seconds)
- else
- year = d[:year]
- year = yield(year) if year && block_given?
- make_time(year, d[:mon], d[:mday], d[:hour], d[:min], d[:sec], d[:sec_fraction], d[:zone], now)
- end
- end
-
- MonthValue = {
- 'JAN' => 1, 'FEB' => 2, 'MAR' => 3, 'APR' => 4, 'MAY' => 5, 'JUN' => 6,
- 'JUL' => 7, 'AUG' => 8, 'SEP' => 9, 'OCT' =>10, 'NOV' =>11, 'DEC' =>12
- }
-
- #
- # Parses +date+ as date-time defined by RFC 2822 and converts it to a Time
- # object. The format is identical to the date format defined by RFC 822 and
- # updated by RFC 1123.
- #
- # ArgumentError is raised if +date+ is not compliant with RFC 2822
- # or Time class cannot represent specified date.
- #
- # See #rfc2822 for more information on this format.
- #
- # time library should be required to use this method as follows.
- #
- # require 'time'
- #
- def rfc2822(date)
- if /\A\s*
- (?:(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s*,\s*)?
- (\d{1,2})\s+
- (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+
- (\d{2,})\s+
- (\d{2})\s*
- :\s*(\d{2})\s*
- (?::\s*(\d{2}))?\s+
- ([+-]\d{4}|
- UT|GMT|EST|EDT|CST|CDT|MST|MDT|PST|PDT|[A-IK-Z])/ix =~ date
- # Since RFC 2822 permit comments, the regexp has no right anchor.
- day = $1.to_i
- mon = MonthValue[$2.upcase]
- year = $3.to_i
- hour = $4.to_i
- min = $5.to_i
- sec = $6 ? $6.to_i : 0
- zone = $7
-
- # following year completion is compliant with RFC 2822.
- year = if year < 50
- 2000 + year
- elsif year < 1000
- 1900 + year
- else
- year
- end
-
- year, mon, day, hour, min, sec =
- apply_offset(year, mon, day, hour, min, sec, zone_offset(zone))
- t = self.utc(year, mon, day, hour, min, sec)
- t.localtime if !zone_utc?(zone)
- t
- else
- raise ArgumentError.new("not RFC 2822 compliant date: #{date.inspect}")
- end
- end
- alias rfc822 rfc2822
-
- #
- # Parses +date+ as HTTP-date defined by RFC 2616 and converts it to a Time
- # object.
- #
- # ArgumentError is raised if +date+ is not compliant with RFC 2616 or Time
- # class cannot represent specified date.
- #
- # See #httpdate for more information on this format.
- #
- # time library should be required to use this method as follows.
- #
- # require 'time'
- #
- def httpdate(date)
- if /\A\s*
- (?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),\x20
- (\d{2})\x20
- (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\x20
- (\d{4})\x20
- (\d{2}):(\d{2}):(\d{2})\x20
- GMT
- \s*\z/ix =~ date
- self.rfc2822(date)
- elsif /\A\s*
- (?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday),\x20
- (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d)\x20
- (\d\d):(\d\d):(\d\d)\x20
- GMT
- \s*\z/ix =~ date
- year = $3.to_i
- if year < 50
- year += 2000
- else
- year += 1900
- end
- self.utc(year, $2, $1.to_i, $4.to_i, $5.to_i, $6.to_i)
- elsif /\A\s*
- (?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\x20
- (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\x20
- (\d\d|\x20\d)\x20
- (\d\d):(\d\d):(\d\d)\x20
- (\d{4})
- \s*\z/ix =~ date
- self.utc($6.to_i, MonthValue[$1.upcase], $2.to_i,
- $3.to_i, $4.to_i, $5.to_i)
- else
- raise ArgumentError.new("not RFC 2616 compliant date: #{date.inspect}")
- end
- end
-
- #
- # Parses +date+ as dateTime defined by XML Schema and converts it to a Time
- # object. The format is restricted version of the format defined by ISO
- # 8601.
- #
- # ArgumentError is raised if +date+ is not compliant with the format or Time
- # class cannot represent specified date.
- #
- # See #xmlschema for more information on this format.
- #
- # time library should be required to use this method as follows.
- #
- # require 'time'
- #
- def xmlschema(date)
- if /\A\s*
- (-?\d+)-(\d\d)-(\d\d)
- T
- (\d\d):(\d\d):(\d\d)
- (\.\d+)?
- (Z|[+-]\d\d:\d\d)?
- \s*\z/ix =~ date
- year = $1.to_i
- mon = $2.to_i
- day = $3.to_i
- hour = $4.to_i
- min = $5.to_i
- sec = $6.to_i
- usec = 0
- if $7
- usec = Rational($7) * 1000000
- end
- if $8
- zone = $8
- year, mon, day, hour, min, sec =
- apply_offset(year, mon, day, hour, min, sec, zone_offset(zone))
- self.utc(year, mon, day, hour, min, sec, usec)
- else
- self.local(year, mon, day, hour, min, sec, usec)
- end
- else
- raise ArgumentError.new("invalid date: #{date.inspect}")
- end
- end
- alias iso8601 xmlschema
- end # class << self
-
- #
- # Returns a string which represents the time as date-time defined by RFC 2822:
- #
- # day-of-week, DD month-name CCYY hh:mm:ss zone
- #
- # where zone is [+-]hhmm.
- #
- # If +self+ is a UTC time, -0000 is used as zone.
- #
- # time library should be required to use this method as follows.
- #
- # require 'time'
- #
- def rfc2822
- sprintf('%s, %02d %s %0*d %02d:%02d:%02d ',
- RFC2822_DAY_NAME[wday],
- day, RFC2822_MONTH_NAME[mon-1], year < 0 ? 5 : 4, year,
- hour, min, sec) +
- if utc?
- '-0000'
- else
- off = utc_offset
- sign = off < 0 ? '-' : '+'
- sprintf('%s%02d%02d', sign, *(off.abs / 60).divmod(60))
- end
- end
- alias rfc822 rfc2822
-
- RFC2822_DAY_NAME = [
- 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'
- ]
- RFC2822_MONTH_NAME = [
- 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
- 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
- ]
-
- #
- # Returns a string which represents the time as rfc1123-date of HTTP-date
- # defined by RFC 2616:
- #
- # day-of-week, DD month-name CCYY hh:mm:ss GMT
- #
- # Note that the result is always UTC (GMT).
- #
- # time library should be required to use this method as follows.
- #
- # require 'time'
- #
- def httpdate
- t = dup.utc
- sprintf('%s, %02d %s %0*d %02d:%02d:%02d GMT',
- RFC2822_DAY_NAME[t.wday],
- t.day, RFC2822_MONTH_NAME[t.mon-1], t.year < 0 ? 5 : 4, t.year,
- t.hour, t.min, t.sec)
- end
-
- #
- # Returns a string which represents the time as dateTime defined by XML
- # Schema:
- #
- # CCYY-MM-DDThh:mm:ssTZD
- # CCYY-MM-DDThh:mm:ss.sssTZD
- #
- # where TZD is Z or [+-]hh:mm.
- #
- # If self is a UTC time, Z is used as TZD. [+-]hh:mm is used otherwise.
- #
- # +fractional_seconds+ specifies a number of digits of fractional seconds.
- # Its default value is 0.
- #
- # time library should be required to use this method as follows.
- #
- # require 'time'
- #
- def xmlschema(fraction_digits=0)
- sprintf('%0*d-%02d-%02dT%02d:%02d:%02d',
- year < 0 ? 5 : 4, year, mon, day, hour, min, sec) +
- if fraction_digits <= 0
- ''
- else
- '.' + sprintf('%0*d', fraction_digits, (subsec * 10**fraction_digits).floor)
- end +
- if utc?
- 'Z'
- else
- off = utc_offset
- sign = off < 0 ? '-' : '+'
- sprintf('%s%02d:%02d', sign, *(off.abs / 60).divmod(60))
- end
- end
- alias iso8601 xmlschema
-end
-
diff --git a/ruby_1_9_3/lib/timeout.rb b/ruby_1_9_3/lib/timeout.rb
deleted file mode 100644
index 16a168d205..0000000000
--- a/ruby_1_9_3/lib/timeout.rb
+++ /dev/null
@@ -1,105 +0,0 @@
-# Timeout long-running blocks
-#
-# == Synopsis
-#
-# require 'timeout'
-# status = Timeout::timeout(5) {
-# # Something that should be interrupted if it takes more than 5 seconds...
-# }
-#
-# == Description
-#
-# Timeout provides a way to auto-terminate a potentially long-running
-# operation if it hasn't finished in a fixed amount of time.
-#
-# Previous versions didn't use a module for namespacing, however
-# #timeout is provided for backwards compatibility. You
-# should prefer Timeout#timeout instead.
-#
-# == Copyright
-#
-# Copyright:: (C) 2000 Network Applied Communication Laboratory, Inc.
-# Copyright:: (C) 2000 Information-technology Promotion Agency, Japan
-
-module Timeout
- # Raised by Timeout#timeout when the block times out.
- class Error < RuntimeError
- end
- class ExitException < ::Exception # :nodoc:
- end
-
- # :stopdoc:
- THIS_FILE = /\A#{Regexp.quote(__FILE__)}:/o
- CALLER_OFFSET = ((c = caller[0]) && THIS_FILE =~ c) ? 1 : 0
- # :startdoc:
-
- # Perform an operation in a block, raising an error if it takes longer than
- # +sec+ seconds to complete.
- #
- # +sec+:: Number of seconds to wait for the block to terminate. Any number
- # may be used, including Floats to specify fractional seconds. A
- # value of 0 or +nil+ will execute the block without any timeout.
- # +klass+:: Exception Class to raise if the block fails to terminate
- # in +sec+ seconds. Omitting will use the default, Timeout::Error
- #
- # The block will be executed on another thread and will be given one
- # argument: +sec+.
- #
- # Returns the result of the block *if* the block completed before
- # +sec+ seconds, otherwise throws an exception, based on the value of +klass+.
- #
- # Note that this is both a method of module Timeout, so you can <tt>include
- # Timeout</tt> into your classes so they have a #timeout method, as well as
- # a module method, so you can call it directly as Timeout.timeout().
- def timeout(sec, klass = nil) #:yield: +sec+
- return yield(sec) if sec == nil or sec.zero?
- exception = klass || Class.new(ExitException)
- begin
- begin
- x = Thread.current
- y = Thread.start {
- begin
- sleep sec
- rescue => e
- x.raise e
- else
- x.raise exception, "execution expired"
- end
- }
- return yield(sec)
- ensure
- if y
- y.kill
- y.join # make sure y is dead.
- end
- end
- rescue exception => e
- rej = /\A#{Regexp.quote(__FILE__)}:#{__LINE__-4}\z/o
- (bt = e.backtrace).reject! {|m| rej =~ m}
- level = -caller(CALLER_OFFSET).size
- while THIS_FILE =~ bt[level]
- bt.delete_at(level)
- level += 1
- end
- raise if klass # if exception class is specified, it
- # would be expected outside.
- raise Error, e.message, e.backtrace
- end
- end
-
- module_function :timeout
-end
-
-# Identical to:
-#
-# Timeout::timeout(n, e, &block).
-#
-# This method is deprecated and provided only for backwards compatibility.
-# You should use Timeout#timeout instead.
-def timeout(n, e = nil, &block)
- Timeout::timeout(n, e, &block)
-end
-
-# Another name for Timeout::Error, defined for backwards compatibility with
-# earlier versions of timeout.rb.
-TimeoutError = Timeout::Error
diff --git a/ruby_1_9_3/lib/tmpdir.rb b/ruby_1_9_3/lib/tmpdir.rb
deleted file mode 100644
index d7f68272e8..0000000000
--- a/ruby_1_9_3/lib/tmpdir.rb
+++ /dev/null
@@ -1,143 +0,0 @@
-#
-# tmpdir - retrieve temporary directory path
-#
-# $Id$
-#
-
-require 'fileutils'
-begin
- require 'etc.so'
-rescue LoadError
-end
-
-class Dir
-
- @@systmpdir ||= defined?(Etc.systmpdir) ? Etc.systmpdir : '/tmp'
-
- ##
- # Returns the operating system's temporary file path.
-
- def Dir::tmpdir
- tmp = '.'
- if $SAFE > 0
- tmp = @@systmpdir
- else
- for dir in [ENV['TMPDIR'], ENV['TMP'], ENV['TEMP'], @@systmpdir, '/tmp']
- if dir and stat = File.stat(dir) and stat.directory? and stat.writable?
- tmp = dir
- break
- end rescue nil
- end
- File.expand_path(tmp)
- end
- end
-
- # Dir.mktmpdir creates a temporary directory.
- #
- # The directory is created with 0700 permission.
- #
- # The prefix and suffix of the name of the directory is specified by
- # the optional first argument, <i>prefix_suffix</i>.
- # - If it is not specified or nil, "d" is used as the prefix and no suffix is used.
- # - If it is a string, it is used as the prefix and no suffix is used.
- # - If it is an array, first element is used as the prefix and second element is used as a suffix.
- #
- # Dir.mktmpdir {|dir| dir is ".../d..." }
- # Dir.mktmpdir("foo") {|dir| dir is ".../foo..." }
- # Dir.mktmpdir(["foo", "bar"]) {|dir| dir is ".../foo...bar" }
- #
- # The directory is created under Dir.tmpdir or
- # the optional second argument <i>tmpdir</i> if non-nil value is given.
- #
- # Dir.mktmpdir {|dir| dir is "#{Dir.tmpdir}/d..." }
- # Dir.mktmpdir(nil, "/var/tmp") {|dir| dir is "/var/tmp/d..." }
- #
- # If a block is given,
- # it is yielded with the path of the directory.
- # The directory and its contents are removed
- # using FileUtils.remove_entry_secure before Dir.mktmpdir returns.
- # The value of the block is returned.
- #
- # Dir.mktmpdir {|dir|
- # # use the directory...
- # open("#{dir}/foo", "w") { ... }
- # }
- #
- # If a block is not given,
- # The path of the directory is returned.
- # In this case, Dir.mktmpdir doesn't remove the directory.
- #
- # dir = Dir.mktmpdir
- # begin
- # # use the directory...
- # open("#{dir}/foo", "w") { ... }
- # ensure
- # # remove the directory.
- # FileUtils.remove_entry_secure dir
- # end
- #
- def Dir.mktmpdir(prefix_suffix=nil, *rest)
- path = Tmpname.create(prefix_suffix || "d", *rest) {|n| mkdir(n, 0700)}
- if block_given?
- begin
- yield path
- ensure
- FileUtils.remove_entry_secure path
- end
- else
- path
- end
- end
-
- module Tmpname # :nodoc:
- module_function
-
- def tmpdir
- Dir.tmpdir
- end
-
- def make_tmpname(prefix_suffix, n)
- case prefix_suffix
- when String
- prefix = prefix_suffix
- suffix = ""
- when Array
- prefix = prefix_suffix[0]
- suffix = prefix_suffix[1]
- else
- raise ArgumentError, "unexpected prefix_suffix: #{prefix_suffix.inspect}"
- end
- t = Time.now.strftime("%Y%m%d")
- path = "#{prefix}#{t}-#{$$}-#{rand(0x100000000).to_s(36)}"
- path << "-#{n}" if n
- path << suffix
- end
-
- def create(basename, *rest)
- if opts = Hash.try_convert(rest[-1])
- opts = opts.dup if rest.pop.equal?(opts)
- max_try = opts.delete(:max_try)
- opts = [opts]
- else
- opts = []
- end
- tmpdir, = *rest
- if $SAFE > 0 and tmpdir.tainted?
- tmpdir = '/tmp'
- else
- tmpdir ||= tmpdir()
- end
- n = nil
- begin
- path = File.expand_path(make_tmpname(basename, n), tmpdir)
- yield(path, n, *opts)
- rescue Errno::EEXIST
- n ||= 0
- n += 1
- retry if !max_try or n < max_try
- raise "cannot generate temporary name using `#{basename}' under `#{tmpdir}'"
- end
- path
- end
- end
-end
diff --git a/ruby_1_9_3/lib/tracer.rb b/ruby_1_9_3/lib/tracer.rb
deleted file mode 100644
index 4b2429508d..0000000000
--- a/ruby_1_9_3/lib/tracer.rb
+++ /dev/null
@@ -1,298 +0,0 @@
-##
-# = Tracer
-#
-# Tracer outputs a source level execution trace of a Ruby program. It does
-# this by registering an event handler with <code>Kernel#set_trace_func</code>
-# for processing incoming events. It also provides methods for filtering
-# unwanted trace output (see Tracer.add_filter, Tracer.on, and Tracer.off).
-#
-# == Example
-#
-# Consider the following ruby script
-#
-# class A
-# def square(a)
-# return a*a
-# end
-# end
-#
-# a = A.new
-# a.square(5)
-#
-# Running the above script using <code>ruby -r tracer example.rb</code> will
-# output the following trace to STDOUT (Note you can also explicitly
-# <code>require 'tracer'</code>)
-#
-# #0:<internal:lib/rubygems/custom_require>:38:Kernel:<: -
-# #0:example.rb:3::-: class A
-# #0:example.rb:3::C: class A
-# #0:example.rb:4::-: def square(a)
-# #0:example.rb:7::E: end
-# #0:example.rb:9::-: a = A.new
-# #0:example.rb:10::-: a.square(5)
-# #0:example.rb:4:A:>: def square(a)
-# #0:example.rb:5:A:-: return a*a
-# #0:example.rb:6:A:<: end
-# | | | | |
-# | | | | ---------------------+ event
-# | | | ------------------------+ class
-# | | --------------------------+ line
-# | ------------------------------------+ filename
-# ---------------------------------------+ thread
-#
-# Symbol table used for displaying incoming events:
-#
-# <tt>}</tt>:: call a C-language routine
-# <tt>{</tt>:: return from a C-language routine
-# <tt>></tt>:: call a Ruby method
-# <tt>C</tt>:: start a class or module definition
-# <tt>E</tt>:: finish a class or module definition
-# <tt>-</tt>:: execute code on a new line
-# <tt>^</tt>:: raise an exception
-# <tt><</tt>:: return from a Ruby method
-#
-# == Copyright
-#
-# by Keiju ISHITSUKA(keiju@ishitsuka.com)
-#
-#--
-# $Release Version: 0.3$
-# $Revision: 1.12 $
-require "thread"
-
-#
-# tracer main class
-#
-class Tracer
- class << self
- # display additional debug information (defaults to false)
- attr_accessor :verbose
- alias verbose? verbose
-
- # output stream used to output trace (defaults to STDOUT)
- attr_accessor :stdout
-
- # mutex lock used by tracer for displaying trace output
- attr_reader :stdout_mutex
-
- # display process id in trace output (defaults to false)
- attr_accessor :display_process_id
- alias display_process_id? display_process_id
-
- # display thread id in trace output (defaults to true)
- attr_accessor :display_thread_id
- alias display_thread_id? display_thread_id
-
- # display C-routine calls in trace output (defaults to false)
- attr_accessor :display_c_call
- alias display_c_call? display_c_call
- end
-
- Tracer::stdout = STDOUT
- Tracer::verbose = false
- Tracer::display_process_id = false
- Tracer::display_thread_id = true
- Tracer::display_c_call = false
-
- @stdout_mutex = Mutex.new
-
- # Symbol table used for displaying trace information
- EVENT_SYMBOL = {
- "line" => "-",
- "call" => ">",
- "return" => "<",
- "class" => "C",
- "end" => "E",
- "raise" => "^",
- "c-call" => "}",
- "c-return" => "{",
- "unknown" => "?"
- }
-
- def initialize # :nodoc:
- @threads = Hash.new
- if defined? Thread.main
- @threads[Thread.main.object_id] = 0
- else
- @threads[Thread.current.object_id] = 0
- end
-
- @get_line_procs = {}
-
- @filters = []
- end
-
- def stdout # :nodoc:
- Tracer.stdout
- end
-
- def on # :nodoc:
- if block_given?
- on
- begin
- yield
- ensure
- off
- end
- else
- set_trace_func method(:trace_func).to_proc
- stdout.print "Trace on\n" if Tracer.verbose?
- end
- end
-
- def off # :nodoc:
- set_trace_func nil
- stdout.print "Trace off\n" if Tracer.verbose?
- end
-
- def add_filter(p = proc) # :nodoc:
- @filters.push p
- end
-
- def set_get_line_procs(file, p = proc) # :nodoc:
- @get_line_procs[file] = p
- end
-
- def get_line(file, line) # :nodoc:
- if p = @get_line_procs[file]
- return p.call(line)
- end
-
- unless list = SCRIPT_LINES__[file]
- begin
- f = File::open(file)
- begin
- SCRIPT_LINES__[file] = list = f.readlines
- ensure
- f.close
- end
- rescue
- SCRIPT_LINES__[file] = list = []
- end
- end
-
- if l = list[line - 1]
- l
- else
- "-\n"
- end
- end
-
- def get_thread_no # :nodoc:
- if no = @threads[Thread.current.object_id]
- no
- else
- @threads[Thread.current.object_id] = @threads.size
- end
- end
-
- def trace_func(event, file, line, id, binding, klass, *) # :nodoc:
- return if file == __FILE__
-
- for p in @filters
- return unless p.call event, file, line, id, binding, klass
- end
-
- return unless Tracer::display_c_call? or
- event != "c-call" && event != "c-return"
-
- Tracer::stdout_mutex.synchronize do
- if EVENT_SYMBOL[event]
- stdout.printf("<%d>", $$) if Tracer::display_process_id?
- stdout.printf("#%d:", get_thread_no) if Tracer::display_thread_id?
- if line == 0
- source = "?\n"
- else
- source = get_line(file, line)
- end
- printf("%s:%d:%s:%s: %s",
- file,
- line,
- klass || '',
- EVENT_SYMBOL[event],
- source)
- end
- end
-
- end
-
- # Reference to singleton instance of Tracer
- Single = new
-
- ##
- # Start tracing
- #
- # === Example
- #
- # Tracer.on
- # # code to trace here
- # Tracer.off
- #
- # You can also pass a block:
- #
- # Tracer.on {
- # # trace everything in this block
- # }
-
- def Tracer.on
- if block_given?
- Single.on{yield}
- else
- Single.on
- end
- end
-
- ##
- # Disable tracing
-
- def Tracer.off
- Single.off
- end
-
- ##
- # Register an event handler <code>p</code> which is called everytime a line
- # in +file_name+ is executed.
- #
- # Example:
- #
- # Tracer.set_get_line_procs("example.rb", lambda { |line|
- # puts "line number executed is #{line}"
- # })
-
- def Tracer.set_get_line_procs(file_name, p = proc)
- Single.set_get_line_procs(file_name, p)
- end
-
- ##
- # Used to filter unwanted trace output
- #
- # Example which only outputs lines of code executed within the Kernel class:
- #
- # Tracer.add_filter do |event, file, line, id, binding, klass, *rest|
- # "Kernel" == klass.to_s
- # end
-
- def Tracer.add_filter(p = proc)
- Single.add_filter(p)
- end
-end
-
-# :stopdoc:
-SCRIPT_LINES__ = {} unless defined? SCRIPT_LINES__
-
-if $0 == __FILE__
- # direct call
-
- $0 = ARGV[0]
- ARGV.shift
- Tracer.on
- require $0
-else
- # call Tracer.on only if required by -r command-line option
- count = caller.count {|bt| /\/rubygems\/custom_require.rb:/ !~ bt}
- if (defined?(Gem) and count == 0) or
- (!defined?(Gem) and count <= 1)
- Tracer.on
- end
-end
-# :startdoc:
diff --git a/ruby_1_9_3/lib/tsort.rb b/ruby_1_9_3/lib/tsort.rb
deleted file mode 100644
index d0f3cd4caa..0000000000
--- a/ruby_1_9_3/lib/tsort.rb
+++ /dev/null
@@ -1,242 +0,0 @@
-#--
-# tsort.rb - provides a module for topological sorting and strongly connected components.
-#++
-#
-
-#
-# TSort implements topological sorting using Tarjan's algorithm for
-# strongly connected components.
-#
-# TSort is designed to be able to be used with any object which can be
-# interpreted as a directed graph.
-#
-# TSort requires two methods to interpret an object as a graph,
-# tsort_each_node and tsort_each_child.
-#
-# * tsort_each_node is used to iterate for all nodes over a graph.
-# * tsort_each_child is used to iterate for child nodes of a given node.
-#
-# The equality of nodes are defined by eql? and hash since
-# TSort uses Hash internally.
-#
-# == A Simple Example
-#
-# The following example demonstrates how to mix the TSort module into an
-# existing class (in this case, Hash). Here, we're treating each key in
-# the hash as a node in the graph, and so we simply alias the required
-# #tsort_each_node method to Hash's #each_key method. For each key in the
-# hash, the associated value is an array of the node's child nodes. This
-# choice in turn leads to our implementation of the required #tsort_each_child
-# method, which fetches the array of child nodes and then iterates over that
-# array using the user-supplied block.
-#
-# require 'tsort'
-#
-# class Hash
-# include TSort
-# alias tsort_each_node each_key
-# def tsort_each_child(node, &block)
-# fetch(node).each(&block)
-# end
-# end
-#
-# {1=>[2, 3], 2=>[3], 3=>[], 4=>[]}.tsort
-# #=> [3, 2, 1, 4]
-#
-# {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}.strongly_connected_components
-# #=> [[4], [2, 3], [1]]
-#
-# == A More Realistic Example
-#
-# A very simple `make' like tool can be implemented as follows:
-#
-# require 'tsort'
-#
-# class Make
-# def initialize
-# @dep = {}
-# @dep.default = []
-# end
-#
-# def rule(outputs, inputs=[], &block)
-# triple = [outputs, inputs, block]
-# outputs.each {|f| @dep[f] = [triple]}
-# @dep[triple] = inputs
-# end
-#
-# def build(target)
-# each_strongly_connected_component_from(target) {|ns|
-# if ns.length != 1
-# fs = ns.delete_if {|n| Array === n}
-# raise TSort::Cyclic.new("cyclic dependencies: #{fs.join ', '}")
-# end
-# n = ns.first
-# if Array === n
-# outputs, inputs, block = n
-# inputs_time = inputs.map {|f| File.mtime f}.max
-# begin
-# outputs_time = outputs.map {|f| File.mtime f}.min
-# rescue Errno::ENOENT
-# outputs_time = nil
-# end
-# if outputs_time == nil ||
-# inputs_time != nil && outputs_time <= inputs_time
-# sleep 1 if inputs_time != nil && inputs_time.to_i == Time.now.to_i
-# block.call
-# end
-# end
-# }
-# end
-#
-# def tsort_each_child(node, &block)
-# @dep[node].each(&block)
-# end
-# include TSort
-# end
-#
-# def command(arg)
-# print arg, "\n"
-# system arg
-# end
-#
-# m = Make.new
-# m.rule(%w[t1]) { command 'date > t1' }
-# m.rule(%w[t2]) { command 'date > t2' }
-# m.rule(%w[t3]) { command 'date > t3' }
-# m.rule(%w[t4], %w[t1 t3]) { command 'cat t1 t3 > t4' }
-# m.rule(%w[t5], %w[t4 t2]) { command 'cat t4 t2 > t5' }
-# m.build('t5')
-#
-# == Bugs
-#
-# * 'tsort.rb' is wrong name because this library uses
-# Tarjan's algorithm for strongly connected components.
-# Although 'strongly_connected_components.rb' is correct but too long.
-#
-# == References
-#
-# R. E. Tarjan, "Depth First Search and Linear Graph Algorithms",
-# <em>SIAM Journal on Computing</em>, Vol. 1, No. 2, pp. 146-160, June 1972.
-#
-
-module TSort
- class Cyclic < StandardError
- end
-
- #
- # Returns a topologically sorted array of nodes.
- # The array is sorted from children to parents, i.e.
- # the first element has no child and the last node has no parent.
- #
- # If there is a cycle, TSort::Cyclic is raised.
- #
- def tsort
- result = []
- tsort_each {|element| result << element}
- result
- end
-
- #
- # The iterator version of the #tsort method.
- # <tt><em>obj</em>.tsort_each</tt> is similar to <tt><em>obj</em>.tsort.each</tt>, but
- # modification of _obj_ during the iteration may lead to unexpected results.
- #
- # #tsort_each returns +nil+.
- # If there is a cycle, TSort::Cyclic is raised.
- #
- def tsort_each # :yields: node
- each_strongly_connected_component {|component|
- if component.size == 1
- yield component.first
- else
- raise Cyclic.new("topological sort failed: #{component.inspect}")
- end
- }
- end
-
- #
- # Returns strongly connected components as an array of arrays of nodes.
- # The array is sorted from children to parents.
- # Each elements of the array represents a strongly connected component.
- #
- def strongly_connected_components
- result = []
- each_strongly_connected_component {|component| result << component}
- result
- end
-
- #
- # The iterator version of the #strongly_connected_components method.
- # <tt><em>obj</em>.each_strongly_connected_component</tt> is similar to
- # <tt><em>obj</em>.strongly_connected_components.each</tt>, but
- # modification of _obj_ during the iteration may lead to unexpected results.
- #
- #
- # #each_strongly_connected_component returns +nil+.
- #
- def each_strongly_connected_component # :yields: nodes
- id_map = {}
- stack = []
- tsort_each_node {|node|
- unless id_map.include? node
- each_strongly_connected_component_from(node, id_map, stack) {|c|
- yield c
- }
- end
- }
- nil
- end
-
- #
- # Iterates over strongly connected component in the subgraph reachable from
- # _node_.
- #
- # Return value is unspecified.
- #
- # #each_strongly_connected_component_from doesn't call #tsort_each_node.
- #
- def each_strongly_connected_component_from(node, id_map={}, stack=[]) # :yields: nodes
- minimum_id = node_id = id_map[node] = id_map.size
- stack_length = stack.length
- stack << node
-
- tsort_each_child(node) {|child|
- if id_map.include? child
- child_id = id_map[child]
- minimum_id = child_id if child_id && child_id < minimum_id
- else
- sub_minimum_id =
- each_strongly_connected_component_from(child, id_map, stack) {|c|
- yield c
- }
- minimum_id = sub_minimum_id if sub_minimum_id < minimum_id
- end
- }
-
- if node_id == minimum_id
- component = stack.slice!(stack_length .. -1)
- component.each {|n| id_map[n] = nil}
- yield component
- end
-
- minimum_id
- end
-
- #
- # Should be implemented by a extended class.
- #
- # #tsort_each_node is used to iterate for all nodes over a graph.
- #
- def tsort_each_node # :yields: node
- raise NotImplementedError.new
- end
-
- #
- # Should be implemented by a extended class.
- #
- # #tsort_each_child is used to iterate for child nodes of _node_.
- #
- def tsort_each_child(node) # :yields: child
- raise NotImplementedError.new
- end
-end
diff --git a/ruby_1_9_3/lib/ubygems.rb b/ruby_1_9_3/lib/ubygems.rb
deleted file mode 100644
index fec880f73b..0000000000
--- a/ruby_1_9_3/lib/ubygems.rb
+++ /dev/null
@@ -1,10 +0,0 @@
-# This file allows for the running of rubygems with a nice
-# command line look-and-feel: ruby -rubygems foo.rb
-#--
-# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
-# All rights reserved.
-# See LICENSE.txt for permissions.
-#++
-
-
-require 'rubygems'
diff --git a/ruby_1_9_3/lib/un.rb b/ruby_1_9_3/lib/un.rb
deleted file mode 100644
index 0a2e37277a..0000000000
--- a/ruby_1_9_3/lib/un.rb
+++ /dev/null
@@ -1,348 +0,0 @@
-#
-# = un.rb
-#
-# Copyright (c) 2003 WATANABE Hirofumi <eban@ruby-lang.org>
-#
-# This program is free software.
-# You can distribute/modify this program under the same terms of Ruby.
-#
-# == Utilities to replace common UNIX commands in Makefiles etc
-#
-# == SYNOPSIS
-#
-# ruby -run -e cp -- [OPTION] SOURCE DEST
-# ruby -run -e ln -- [OPTION] TARGET LINK_NAME
-# ruby -run -e mv -- [OPTION] SOURCE DEST
-# ruby -run -e rm -- [OPTION] FILE
-# ruby -run -e mkdir -- [OPTION] DIRS
-# ruby -run -e rmdir -- [OPTION] DIRS
-# ruby -run -e install -- [OPTION] SOURCE DEST
-# ruby -run -e chmod -- [OPTION] OCTAL-MODE FILE
-# ruby -run -e touch -- [OPTION] FILE
-# ruby -run -e wait_writable -- [OPTION] FILE
-# ruby -run -e mkmf -- [OPTION] EXTNAME [OPTION]
-# ruby -run -e httpd -- [OPTION] DocumentRoot
-# ruby -run -e help [COMMAND]
-
-require "fileutils"
-require "optparse"
-
-module FileUtils
-# @fileutils_label = ""
- @fileutils_output = $stdout
-end
-
-def setup(options = "", *long_options)
- opt_hash = {}
- argv = []
- OptionParser.new do |o|
- options.scan(/.:?/) do |s|
- opt_name = s.delete(":").intern
- o.on("-" + s.tr(":", " ")) do |val|
- opt_hash[opt_name] = val
- end
- end
- long_options.each do |s|
- opt_name, arg_name = s.split(/(?=[\s=])/, 2)
- opt_name.sub!(/\A--/, '')
- s = "--#{opt_name.gsub(/([A-Z]+|[a-z])([A-Z])/, '\1-\2').downcase}#{arg_name}"
- puts "#{opt_name}=>#{s}" if $DEBUG
- opt_name = opt_name.intern
- o.on(s) do |val|
- opt_hash[opt_name] = val
- end
- end
- o.on("-v") do opt_hash[:verbose] = true end
- o.order!(ARGV) do |x|
- if /[*?\[{]/ =~ x
- argv.concat(Dir[x])
- else
- argv << x
- end
- end
- end
- yield argv, opt_hash
-end
-
-##
-# Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY
-#
-# ruby -run -e cp -- [OPTION] SOURCE DEST
-#
-# -p preserve file attributes if possible
-# -r copy recursively
-# -v verbose
-#
-
-def cp
- setup("pr") do |argv, options|
- cmd = "cp"
- cmd += "_r" if options.delete :r
- options[:preserve] = true if options.delete :p
- dest = argv.pop
- argv = argv[0] if argv.size == 1
- FileUtils.send cmd, argv, dest, options
- end
-end
-
-##
-# Create a link to the specified TARGET with LINK_NAME.
-#
-# ruby -run -e ln -- [OPTION] TARGET LINK_NAME
-#
-# -s make symbolic links instead of hard links
-# -f remove existing destination files
-# -v verbose
-#
-
-def ln
- setup("sf") do |argv, options|
- cmd = "ln"
- cmd += "_s" if options.delete :s
- options[:force] = true if options.delete :f
- dest = argv.pop
- argv = argv[0] if argv.size == 1
- FileUtils.send cmd, argv, dest, options
- end
-end
-
-##
-# Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY.
-#
-# ruby -run -e mv -- [OPTION] SOURCE DEST
-#
-# -v verbose
-#
-
-def mv
- setup do |argv, options|
- dest = argv.pop
- argv = argv[0] if argv.size == 1
- FileUtils.mv argv, dest, options
- end
-end
-
-##
-# Remove the FILE
-#
-# ruby -run -e rm -- [OPTION] FILE
-#
-# -f ignore nonexistent files
-# -r remove the contents of directories recursively
-# -v verbose
-#
-
-def rm
- setup("fr") do |argv, options|
- cmd = "rm"
- cmd += "_r" if options.delete :r
- options[:force] = true if options.delete :f
- FileUtils.send cmd, argv, options
- end
-end
-
-##
-# Create the DIR, if they do not already exist.
-#
-# ruby -run -e mkdir -- [OPTION] DIR
-#
-# -p no error if existing, make parent directories as needed
-# -v verbose
-#
-
-def mkdir
- setup("p") do |argv, options|
- cmd = "mkdir"
- cmd += "_p" if options.delete :p
- FileUtils.send cmd, argv, options
- end
-end
-
-##
-# Remove the DIR.
-#
-# ruby -run -e rmdir -- [OPTION] DIR
-#
-# -p remove DIRECTORY and its ancestors.
-# -v verbose
-#
-
-def rmdir
- setup("p") do |argv, options|
- options[:parents] = true if options.delete :p
- FileUtils.rmdir argv, options
- end
-end
-
-##
-# Copy SOURCE to DEST.
-#
-# ruby -run -e install -- [OPTION] SOURCE DEST
-#
-# -p apply access/modification times of SOURCE files to
-# corresponding destination files
-# -m set permission mode (as in chmod), instead of 0755
-# -v verbose
-#
-
-def install
- setup("pm:") do |argv, options|
- options[:mode] = (mode = options.delete :m) ? mode.oct : 0755
- options[:preserve] = true if options.delete :p
- dest = argv.pop
- argv = argv[0] if argv.size == 1
- FileUtils.install argv, dest, options
- end
-end
-
-##
-# Change the mode of each FILE to OCTAL-MODE.
-#
-# ruby -run -e chmod -- [OPTION] OCTAL-MODE FILE
-#
-# -v verbose
-#
-
-def chmod
- setup do |argv, options|
- mode = argv.shift.oct
- FileUtils.chmod mode, argv, options
- end
-end
-
-##
-# Update the access and modification times of each FILE to the current time.
-#
-# ruby -run -e touch -- [OPTION] FILE
-#
-# -v verbose
-#
-
-def touch
- setup do |argv, options|
- FileUtils.touch argv, options
- end
-end
-
-##
-# Wait until the file becomes writable.
-#
-# ruby -run -e wait_writable -- [OPTION] FILE
-#
-# -n RETRY count to retry
-# -w SEC each wait time in seconds
-# -v verbose
-#
-
-def wait_writable
- setup("n:w:v") do |argv, options|
- verbose = options[:verbose]
- n = options[:n] and n = Integer(n)
- wait = (wait = options[:w]) ? Float(wait) : 0.2
- argv.each do |file|
- begin
- open(file, "r+b")
- rescue Errno::ENOENT
- break
- rescue Errno::EACCES => e
- raise if n and (n -= 1) <= 0
- puts e
- STDOUT.flush
- sleep wait
- retry
- end
- end
- end
-end
-
-##
-# Create makefile using mkmf.
-#
-# ruby -run -e mkmf -- [OPTION] EXTNAME [OPTION]
-#
-# -d ARGS run dir_config
-# -h ARGS run have_header
-# -l ARGS run have_library
-# -f ARGS run have_func
-# -v ARGS run have_var
-# -t ARGS run have_type
-# -m ARGS run have_macro
-# -c ARGS run have_const
-# --vendor install to vendor_ruby
-#
-
-def mkmf
- setup("d:h:l:f:v:t:m:c:", "vendor") do |argv, options|
- require 'mkmf'
- opt = options[:d] and opt.split(/:/).each {|n| dir_config(*n.split(/,/))}
- opt = options[:h] and opt.split(/:/).each {|n| have_header(*n.split(/,/))}
- opt = options[:l] and opt.split(/:/).each {|n| have_library(*n.split(/,/))}
- opt = options[:f] and opt.split(/:/).each {|n| have_func(*n.split(/,/))}
- opt = options[:v] and opt.split(/:/).each {|n| have_var(*n.split(/,/))}
- opt = options[:t] and opt.split(/:/).each {|n| have_type(*n.split(/,/))}
- opt = options[:m] and opt.split(/:/).each {|n| have_macro(*n.split(/,/))}
- opt = options[:c] and opt.split(/:/).each {|n| have_const(*n.split(/,/))}
- $configure_args["--vendor"] = true if options[:vendor]
- create_makefile(*argv)
- end
-end
-
-##
-# Run WEBrick HTTP server.
-#
-# ruby -run -e httpd -- [OPTION] DocumentRoot
-#
-# --bind-address=ADDR address to bind
-# --port=NUM listening port number
-# --max-clients=MAX max number of simultaneous clients
-# --temp-dir=DIR temporary directory
-# --do-not-reverse-lookup disable reverse lookup
-# --request-timeout=SECOND request timeout in seconds
-# --http-version=VERSION HTTP version
-# -v verbose
-#
-
-def httpd
- setup("", "BindAddress=ADDR", "Port=PORT", "MaxClients=NUM", "TempDir=DIR",
- "DoNotReverseLookup", "RequestTimeout=SECOND", "HTTPVersion=VERSION") do
- |argv, options|
- require 'webrick'
- opt = options[:RequestTimeout] and options[:RequestTimeout] = opt.to_i
- [:Port, :MaxClients].each do |name|
- opt = options[name] and (options[name] = Integer(opt)) rescue nil
- end
- unless argv.empty?
- options[:DocumentRoot] = argv.shift
- end
- s = WEBrick::HTTPServer.new(options)
- shut = proc {s.shutdown}
- Signal.trap("TERM", shut)
- Signal.trap("QUIT", shut) if Signal.list.has_key?("QUIT")
- if STDIN.tty?
- Signal.trap("HUP", shut) if Signal.list.has_key?("HUP")
- Signal.trap("INT", shut)
- end
- s.start
- end
-end
-
-##
-# Display help message.
-#
-# ruby -run -e help [COMMAND]
-#
-
-def help
- setup do |argv,|
- all = argv.empty?
- open(__FILE__) do |me|
- while me.gets("##\n")
- if help = me.gets("\n\n")
- if all or argv.delete help[/-e \w+/].sub(/-e /, "")
- print help.gsub(/^# ?/, "")
- end
- end
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/uri.rb b/ruby_1_9_3/lib/uri.rb
deleted file mode 100644
index 2e136eb682..0000000000
--- a/ruby_1_9_3/lib/uri.rb
+++ /dev/null
@@ -1,111 +0,0 @@
-# URI is a module providing classes to handle Uniform Resource Identifiers
-# (RFC2396[http://tools.ietf.org/html/rfc2396])
-#
-# == Features
-#
-# * Uniform handling of handling URIs
-# * Flexibility to introduce custom URI schemes
-# * Flexibility to have an alternate URI::Parser (or just different patterns
-# and regexp's)
-#
-# == Basic example
-#
-# require 'uri'
-#
-# uri = URI("http://foo.com/posts?id=30&limit=5#time=1305298413")
-# #=> #<URI::HTTP:0x00000000b14880
-# URL:http://foo.com/posts?id=30&limit=5#time=1305298413>
-# uri.scheme
-# #=> "http"
-# uri.host
-# #=> "foo.com"
-# uri.path
-# #=> "/posts"
-# uri.query
-# #=> "id=30&limit=5"
-# uri.fragment
-# #=> "time=1305298413"
-#
-# uri.to_s
-# #=> "http://foo.com/posts?id=30&limit=5#time=1305298413"
-#
-# == Adding custom URIs
-#
-# module URI
-# class RSYNC < Generic
-# DEFAULT_PORT = 873
-# end
-# @@schemes['RSYNC'] = RSYNC
-# end
-# #=> URI::RSYNC
-#
-# URI.scheme_list
-# #=> {"FTP"=>URI::FTP, "HTTP"=>URI::HTTP, "HTTPS"=>URI::HTTPS,
-# "LDAP"=>URI::LDAP, "LDAPS"=>URI::LDAPS, "MAILTO"=>URI::MailTo,
-# "RSYNC"=>URI::RSYNC}
-#
-# uri = URI("rsync://rsync.foo.com")
-# #=> #<URI::RSYNC:0x00000000f648c8 URL:rsync://rsync.foo.com>
-#
-# == RFC References
-#
-# A good place to view an RFC spec is http://www.ietf.org/rfc.html
-#
-# Here is a list of all related RFC's.
-# - RFC822[http://tools.ietf.org/html/rfc822]
-# - RFC1738[http://tools.ietf.org/html/rfc1738]
-# - RFC2255[http://tools.ietf.org/html/rfc2255]
-# - RFC2368[http://tools.ietf.org/html/rfc2368]
-# - RFC2373[http://tools.ietf.org/html/rfc2373]
-# - RFC2396[http://tools.ietf.org/html/rfc2396]
-# - RFC2732[http://tools.ietf.org/html/rfc2732]
-# - RFC3986[http://tools.ietf.org/html/rfc3986]
-#
-# == Class tree
-#
-# - URI::Generic (in uri/generic.rb)
-# - URI::FTP - (in uri/ftp.rb)
-# - URI::HTTP - (in uri/http.rb)
-# - URI::HTTPS - (in uri/https.rb)
-# - URI::LDAP - (in uri/ldap.rb)
-# - URI::LDAPS - (in uri/ldaps.rb)
-# - URI::MailTo - (in uri/mailto.rb)
-# - URI::Parser - (in uri/common.rb)
-# - URI::REGEXP - (in uri/common.rb)
-# - URI::REGEXP::PATTERN - (in uri/common.rb)
-# - URI::Util - (in uri/common.rb)
-# - URI::Escape - (in uri/common.rb)
-# - URI::Error - (in uri/common.rb)
-# - URI::InvalidURIError - (in uri/common.rb)
-# - URI::InvalidComponentError - (in uri/common.rb)
-# - URI::BadURIError - (in uri/common.rb)
-#
-# == Copyright Info
-#
-# Author:: Akira Yamada <akira@ruby-lang.org>
-# Documentation::
-# Akira Yamada <akira@ruby-lang.org>
-# Dmitry V. Sabanin <sdmitry@lrn.ru>
-# Vincent Batts <vbatts@hashbangbash.com>
-# License::
-# Copyright (c) 2001 akira yamada <akira@ruby-lang.org>
-# You can redistribute it and/or modify it under the same term as Ruby.
-# Revision:: $Id$
-#
-
-module URI
- # :stopdoc:
- VERSION_CODE = '000911'.freeze
- VERSION = VERSION_CODE.scan(/../).collect{|n| n.to_i}.join('.').freeze
- # :startdoc:
-
-end
-
-require 'uri/common'
-require 'uri/generic'
-require 'uri/ftp'
-require 'uri/http'
-require 'uri/https'
-require 'uri/ldap'
-require 'uri/ldaps'
-require 'uri/mailto'
diff --git a/ruby_1_9_3/lib/uri/common.rb b/ruby_1_9_3/lib/uri/common.rb
deleted file mode 100644
index 288bbe191e..0000000000
--- a/ruby_1_9_3/lib/uri/common.rb
+++ /dev/null
@@ -1,1001 +0,0 @@
-#--
-# = uri/common.rb
-#
-# Author:: Akira Yamada <akira@ruby-lang.org>
-# Revision:: $Id$
-# License::
-# You can redistribute it and/or modify it under the same term as Ruby.
-#
-# See URI for general documentation
-#
-
-module URI
- #
- # Includes URI::REGEXP::PATTERN
- #
- module REGEXP
- #
- # Patterns used to parse URI's
- #
- module PATTERN
- # :stopdoc:
-
- # RFC 2396 (URI Generic Syntax)
- # RFC 2732 (IPv6 Literal Addresses in URL's)
- # RFC 2373 (IPv6 Addressing Architecture)
-
- # alpha = lowalpha | upalpha
- ALPHA = "a-zA-Z"
- # alphanum = alpha | digit
- ALNUM = "#{ALPHA}\\d"
-
- # hex = digit | "A" | "B" | "C" | "D" | "E" | "F" |
- # "a" | "b" | "c" | "d" | "e" | "f"
- HEX = "a-fA-F\\d"
- # escaped = "%" hex hex
- ESCAPED = "%[#{HEX}]{2}"
- # mark = "-" | "_" | "." | "!" | "~" | "*" | "'" |
- # "(" | ")"
- # unreserved = alphanum | mark
- UNRESERVED = "\\-_.!~*'()#{ALNUM}"
- # reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
- # "$" | ","
- # reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
- # "$" | "," | "[" | "]" (RFC 2732)
- RESERVED = ";/?:@&=+$,\\[\\]"
-
- # domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum
- DOMLABEL = "(?:[#{ALNUM}](?:[-#{ALNUM}]*[#{ALNUM}])?)"
- # toplabel = alpha | alpha *( alphanum | "-" ) alphanum
- TOPLABEL = "(?:[#{ALPHA}](?:[-#{ALNUM}]*[#{ALNUM}])?)"
- # hostname = *( domainlabel "." ) toplabel [ "." ]
- HOSTNAME = "(?:#{DOMLABEL}\\.)*#{TOPLABEL}\\.?"
-
- # :startdoc:
- end # PATTERN
-
- # :startdoc:
- end # REGEXP
-
- # class that Parses String's into URI's
- #
- # It contains a Hash set of patterns and Regexp's that match and validate.
- #
- class Parser
- include REGEXP
-
- #
- # == Synopsis
- #
- # URI::Parser.new([opts])
- #
- # == Args
- #
- # The constructor accepts a hash as options for parser.
- # Keys of options are pattern names of URI components
- # and values of options are pattern strings.
- # The constructor generetes set of regexps for parsing URIs.
- #
- # You can use the following keys:
- #
- # * :ESCAPED (URI::PATTERN::ESCAPED in default)
- # * :UNRESERVED (URI::PATTERN::UNRESERVED in default)
- # * :DOMLABEL (URI::PATTERN::DOMLABEL in default)
- # * :TOPLABEL (URI::PATTERN::TOPLABEL in default)
- # * :HOSTNAME (URI::PATTERN::HOSTNAME in default)
- #
- # == Examples
- #
- # p = URI::Parser.new(:ESCAPED => "(?:%[a-fA-F0-9]{2}|%u[a-fA-F0-9]{4})")
- # u = p.parse("http://example.jp/%uABCD") #=> #<URI::HTTP:0xb78cf4f8 URL:http://example.jp/%uABCD>
- # URI.parse(u.to_s) #=> raises URI::InvalidURIError
- #
- # s = "http://examle.com/ABCD"
- # u1 = p.parse(s) #=> #<URI::HTTP:0xb78c3220 URL:http://example.com/ABCD>
- # u2 = URI.parse(s) #=> #<URI::HTTP:0xb78b6d54 URL:http://example.com/ABCD>
- # u1 == u2 #=> true
- # u1.eql?(u2) #=> false
- #
- def initialize(opts = {})
- @pattern = initialize_pattern(opts)
- @pattern.each_value {|v| v.freeze}
- @pattern.freeze
-
- @regexp = initialize_regexp(@pattern)
- @regexp.each_value {|v| v.freeze}
- @regexp.freeze
- end
-
- # The Hash of patterns.
- #
- # see also URI::Parser.initialize_pattern
- attr_reader :pattern
-
- # The Hash of Regexp
- #
- # see also URI::Parser.initialize_regexp
- attr_reader :regexp
-
- # Returns a split URI against regexp[:ABS_URI]
- def split(uri)
- case uri
- when ''
- # null uri
-
- when @regexp[:ABS_URI]
- scheme, opaque, userinfo, host, port,
- registry, path, query, fragment = $~[1..-1]
-
- # URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
-
- # absoluteURI = scheme ":" ( hier_part | opaque_part )
- # hier_part = ( net_path | abs_path ) [ "?" query ]
- # opaque_part = uric_no_slash *uric
-
- # abs_path = "/" path_segments
- # net_path = "//" authority [ abs_path ]
-
- # authority = server | reg_name
- # server = [ [ userinfo "@" ] hostport ]
-
- if !scheme
- raise InvalidURIError,
- "bad URI(absolute but no scheme): #{uri}"
- end
- if !opaque && (!path && (!host && !registry))
- raise InvalidURIError,
- "bad URI(absolute but no path): #{uri}"
- end
-
- when @regexp[:REL_URI]
- scheme = nil
- opaque = nil
-
- userinfo, host, port, registry,
- rel_segment, abs_path, query, fragment = $~[1..-1]
- if rel_segment && abs_path
- path = rel_segment + abs_path
- elsif rel_segment
- path = rel_segment
- elsif abs_path
- path = abs_path
- end
-
- # URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
-
- # relativeURI = ( net_path | abs_path | rel_path ) [ "?" query ]
-
- # net_path = "//" authority [ abs_path ]
- # abs_path = "/" path_segments
- # rel_path = rel_segment [ abs_path ]
-
- # authority = server | reg_name
- # server = [ [ userinfo "@" ] hostport ]
-
- else
- raise InvalidURIError, "bad URI(is not URI?): #{uri}"
- end
-
- path = '' if !path && !opaque # (see RFC2396 Section 5.2)
- ret = [
- scheme,
- userinfo, host, port, # X
- registry, # X
- path, # Y
- opaque, # Y
- query,
- fragment
- ]
- return ret
- end
-
- #
- # == Args
- #
- # +uri+::
- # String
- #
- # == Description
- #
- # parses +uri+ and constructs either matching URI scheme object
- # (FTP, HTTP, HTTPS, LDAP, LDAPS, or MailTo) or URI::Generic
- #
- # == Usage
- #
- # p = URI::Parser.new
- # p.parse("ldap://ldap.example.com/dc=example?user=john")
- # #=> #<URI::LDAP:0x00000000b9e7e8 URL:ldap://ldap.example.com/dc=example?user=john>
- #
- def parse(uri)
- scheme, userinfo, host, port,
- registry, path, opaque, query, fragment = self.split(uri)
-
- if scheme && URI.scheme_list.include?(scheme.upcase)
- URI.scheme_list[scheme.upcase].new(scheme, userinfo, host, port,
- registry, path, opaque, query,
- fragment, self)
- else
- Generic.new(scheme, userinfo, host, port,
- registry, path, opaque, query,
- fragment, self)
- end
- end
-
-
- #
- # == Args
- #
- # +uris+::
- # an Array of Strings
- #
- # == Description
- #
- # Attempts to parse and merge a set of URIs
- #
- def join(*uris)
- uris[0] = convert_to_uri(uris[0])
- uris.inject :merge
- end
-
- #
- # :call-seq:
- # extract( str )
- # extract( str, schemes )
- # extract( str, schemes ) {|item| block }
- #
- # == Args
- #
- # +str+::
- # String to search
- # +schemes+::
- # Patterns to apply to +str+
- #
- # == Description
- #
- # Attempts to parse and merge a set of URIs
- # If no +block+ given , then returns the result,
- # else it calls +block+ for each element in result.
- #
- # see also URI::Parser.make_regexp
- #
- def extract(str, schemes = nil, &block)
- if block_given?
- str.scan(make_regexp(schemes)) { yield $& }
- nil
- else
- result = []
- str.scan(make_regexp(schemes)) { result.push $& }
- result
- end
- end
-
- # returns Regexp that is default self.regexp[:ABS_URI_REF],
- # unless +schemes+ is provided. Then it is a Regexp.union with self.pattern[:X_ABS_URI]
- def make_regexp(schemes = nil)
- unless schemes
- @regexp[:ABS_URI_REF]
- else
- /(?=#{Regexp.union(*schemes)}:)#{@pattern[:X_ABS_URI]}/x
- end
- end
-
- #
- # :call-seq:
- # escape( str )
- # escape( str, unsafe )
- #
- # == Args
- #
- # +str+::
- # String to make safe
- # +unsafe+::
- # Regexp to apply. Defaults to self.regexp[:UNSAFE]
- #
- # == Description
- #
- # constructs a safe String from +str+, removing unsafe characters,
- # replacing them with codes.
- #
- def escape(str, unsafe = @regexp[:UNSAFE])
- unless unsafe.kind_of?(Regexp)
- # perhaps unsafe is String object
- unsafe = Regexp.new("[#{Regexp.quote(unsafe)}]", false)
- end
- str.gsub(unsafe) do
- us = $&
- tmp = ''
- us.each_byte do |uc|
- tmp << sprintf('%%%02X', uc)
- end
- tmp
- end.force_encoding(Encoding::US_ASCII)
- end
-
- #
- # :call-seq:
- # unescape( str )
- # unescape( str, unsafe )
- #
- # == Args
- #
- # +str+::
- # String to remove escapes from
- # +unsafe+::
- # Regexp to apply. Defaults to self.regexp[:ESCAPED]
- #
- # == Description
- #
- # Removes escapes from +str+
- #
- def unescape(str, escaped = @regexp[:ESCAPED])
- str.gsub(escaped) { [$&[1, 2].hex].pack('C') }.force_encoding(str.encoding)
- end
-
- @@to_s = Kernel.instance_method(:to_s)
- def inspect
- @@to_s.bind(self).call
- end
-
- private
-
- # Constructs the default Hash of patterns
- def initialize_pattern(opts = {})
- ret = {}
- ret[:ESCAPED] = escaped = (opts.delete(:ESCAPED) || PATTERN::ESCAPED)
- ret[:UNRESERVED] = unreserved = opts.delete(:UNRESERVED) || PATTERN::UNRESERVED
- ret[:RESERVED] = reserved = opts.delete(:RESERVED) || PATTERN::RESERVED
- ret[:DOMLABEL] = opts.delete(:DOMLABEL) || PATTERN::DOMLABEL
- ret[:TOPLABEL] = opts.delete(:TOPLABEL) || PATTERN::TOPLABEL
- ret[:HOSTNAME] = hostname = opts.delete(:HOSTNAME)
-
- # RFC 2396 (URI Generic Syntax)
- # RFC 2732 (IPv6 Literal Addresses in URL's)
- # RFC 2373 (IPv6 Addressing Architecture)
-
- # uric = reserved | unreserved | escaped
- ret[:URIC] = uric = "(?:[#{unreserved}#{reserved}]|#{escaped})"
- # uric_no_slash = unreserved | escaped | ";" | "?" | ":" | "@" |
- # "&" | "=" | "+" | "$" | ","
- ret[:URIC_NO_SLASH] = uric_no_slash = "(?:[#{unreserved};?:@&=+$,]|#{escaped})"
- # query = *uric
- ret[:QUERY] = query = "#{uric}*"
- # fragment = *uric
- ret[:FRAGMENT] = fragment = "#{uric}*"
-
- # hostname = *( domainlabel "." ) toplabel [ "." ]
- # reg-name = *( unreserved / pct-encoded / sub-delims ) # RFC3986
- unless hostname
- ret[:HOSTNAME] = hostname = "(?:[a-zA-Z0-9\\-.]|%\\h\\h)+"
- end
-
- # RFC 2373, APPENDIX B:
- # IPv6address = hexpart [ ":" IPv4address ]
- # IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT
- # hexpart = hexseq | hexseq "::" [ hexseq ] | "::" [ hexseq ]
- # hexseq = hex4 *( ":" hex4)
- # hex4 = 1*4HEXDIG
- #
- # XXX: This definition has a flaw. "::" + IPv4address must be
- # allowed too. Here is a replacement.
- #
- # IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT
- ret[:IPV4ADDR] = ipv4addr = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"
- # hex4 = 1*4HEXDIG
- hex4 = "[#{PATTERN::HEX}]{1,4}"
- # lastpart = hex4 | IPv4address
- lastpart = "(?:#{hex4}|#{ipv4addr})"
- # hexseq1 = *( hex4 ":" ) hex4
- hexseq1 = "(?:#{hex4}:)*#{hex4}"
- # hexseq2 = *( hex4 ":" ) lastpart
- hexseq2 = "(?:#{hex4}:)*#{lastpart}"
- # IPv6address = hexseq2 | [ hexseq1 ] "::" [ hexseq2 ]
- ret[:IPV6ADDR] = ipv6addr = "(?:#{hexseq2}|(?:#{hexseq1})?::(?:#{hexseq2})?)"
-
- # IPv6prefix = ( hexseq1 | [ hexseq1 ] "::" [ hexseq1 ] ) "/" 1*2DIGIT
- # unused
-
- # ipv6reference = "[" IPv6address "]" (RFC 2732)
- ret[:IPV6REF] = ipv6ref = "\\[#{ipv6addr}\\]"
-
- # host = hostname | IPv4address
- # host = hostname | IPv4address | IPv6reference (RFC 2732)
- ret[:HOST] = host = "(?:#{hostname}|#{ipv4addr}|#{ipv6ref})"
- # port = *digit
- port = '\d*'
- # hostport = host [ ":" port ]
- ret[:HOSTPORT] = hostport = "#{host}(?::#{port})?"
-
- # userinfo = *( unreserved | escaped |
- # ";" | ":" | "&" | "=" | "+" | "$" | "," )
- ret[:USERINFO] = userinfo = "(?:[#{unreserved};:&=+$,]|#{escaped})*"
-
- # pchar = unreserved | escaped |
- # ":" | "@" | "&" | "=" | "+" | "$" | ","
- pchar = "(?:[#{unreserved}:@&=+$,]|#{escaped})"
- # param = *pchar
- param = "#{pchar}*"
- # segment = *pchar *( ";" param )
- segment = "#{pchar}*(?:;#{param})*"
- # path_segments = segment *( "/" segment )
- ret[:PATH_SEGMENTS] = path_segments = "#{segment}(?:/#{segment})*"
-
- # server = [ [ userinfo "@" ] hostport ]
- server = "(?:#{userinfo}@)?#{hostport}"
- # reg_name = 1*( unreserved | escaped | "$" | "," |
- # ";" | ":" | "@" | "&" | "=" | "+" )
- ret[:REG_NAME] = reg_name = "(?:[#{unreserved}$,;:@&=+]|#{escaped})+"
- # authority = server | reg_name
- authority = "(?:#{server}|#{reg_name})"
-
- # rel_segment = 1*( unreserved | escaped |
- # ";" | "@" | "&" | "=" | "+" | "$" | "," )
- ret[:REL_SEGMENT] = rel_segment = "(?:[#{unreserved};@&=+$,]|#{escaped})+"
-
- # scheme = alpha *( alpha | digit | "+" | "-" | "." )
- ret[:SCHEME] = scheme = "[#{PATTERN::ALPHA}][\\-+.#{PATTERN::ALPHA}\\d]*"
-
- # abs_path = "/" path_segments
- ret[:ABS_PATH] = abs_path = "/#{path_segments}"
- # rel_path = rel_segment [ abs_path ]
- ret[:REL_PATH] = rel_path = "#{rel_segment}(?:#{abs_path})?"
- # net_path = "//" authority [ abs_path ]
- ret[:NET_PATH] = net_path = "//#{authority}(?:#{abs_path})?"
-
- # hier_part = ( net_path | abs_path ) [ "?" query ]
- ret[:HIER_PART] = hier_part = "(?:#{net_path}|#{abs_path})(?:\\?(?:#{query}))?"
- # opaque_part = uric_no_slash *uric
- ret[:OPAQUE_PART] = opaque_part = "#{uric_no_slash}#{uric}*"
-
- # absoluteURI = scheme ":" ( hier_part | opaque_part )
- ret[:ABS_URI] = abs_uri = "#{scheme}:(?:#{hier_part}|#{opaque_part})"
- # relativeURI = ( net_path | abs_path | rel_path ) [ "?" query ]
- ret[:REL_URI] = rel_uri = "(?:#{net_path}|#{abs_path}|#{rel_path})(?:\\?#{query})?"
-
- # URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
- ret[:URI_REF] = "(?:#{abs_uri}|#{rel_uri})?(?:##{fragment})?"
-
- ret[:X_ABS_URI] = "
- (#{scheme}): (?# 1: scheme)
- (?:
- (#{opaque_part}) (?# 2: opaque)
- |
- (?:(?:
- //(?:
- (?:(?:(#{userinfo})@)? (?# 3: userinfo)
- (?:(#{host})(?::(\\d*))?))? (?# 4: host, 5: port)
- |
- (#{reg_name}) (?# 6: registry)
- )
- |
- (?!//)) (?# XXX: '//' is the mark for hostport)
- (#{abs_path})? (?# 7: path)
- )(?:\\?(#{query}))? (?# 8: query)
- )
- (?:\\#(#{fragment}))? (?# 9: fragment)
- "
-
- ret[:X_REL_URI] = "
- (?:
- (?:
- //
- (?:
- (?:(#{userinfo})@)? (?# 1: userinfo)
- (#{host})?(?::(\\d*))? (?# 2: host, 3: port)
- |
- (#{reg_name}) (?# 4: registry)
- )
- )
- |
- (#{rel_segment}) (?# 5: rel_segment)
- )?
- (#{abs_path})? (?# 6: abs_path)
- (?:\\?(#{query}))? (?# 7: query)
- (?:\\#(#{fragment}))? (?# 8: fragment)
- "
-
- ret
- end
-
- # Constructs the default Hash of Regexp's
- def initialize_regexp(pattern)
- ret = {}
-
- # for URI::split
- ret[:ABS_URI] = Regexp.new('\A\s*' + pattern[:X_ABS_URI] + '\s*\z', Regexp::EXTENDED)
- ret[:REL_URI] = Regexp.new('\A\s*' + pattern[:X_REL_URI] + '\s*\z', Regexp::EXTENDED)
-
- # for URI::extract
- ret[:URI_REF] = Regexp.new(pattern[:URI_REF])
- ret[:ABS_URI_REF] = Regexp.new(pattern[:X_ABS_URI], Regexp::EXTENDED)
- ret[:REL_URI_REF] = Regexp.new(pattern[:X_REL_URI], Regexp::EXTENDED)
-
- # for URI::escape/unescape
- ret[:ESCAPED] = Regexp.new(pattern[:ESCAPED])
- ret[:UNSAFE] = Regexp.new("[^#{pattern[:UNRESERVED]}#{pattern[:RESERVED]}]")
-
- # for Generic#initialize
- ret[:SCHEME] = Regexp.new("\\A#{pattern[:SCHEME]}\\z")
- ret[:USERINFO] = Regexp.new("\\A#{pattern[:USERINFO]}\\z")
- ret[:HOST] = Regexp.new("\\A#{pattern[:HOST]}\\z")
- ret[:PORT] = Regexp.new("\\A#{pattern[:PORT]}\\z")
- ret[:OPAQUE] = Regexp.new("\\A#{pattern[:OPAQUE_PART]}\\z")
- ret[:REGISTRY] = Regexp.new("\\A#{pattern[:REG_NAME]}\\z")
- ret[:ABS_PATH] = Regexp.new("\\A#{pattern[:ABS_PATH]}\\z")
- ret[:REL_PATH] = Regexp.new("\\A#{pattern[:REL_PATH]}\\z")
- ret[:QUERY] = Regexp.new("\\A#{pattern[:QUERY]}\\z")
- ret[:FRAGMENT] = Regexp.new("\\A#{pattern[:FRAGMENT]}\\z")
-
- ret
- end
-
- def convert_to_uri(uri)
- if uri.is_a?(URI::Generic)
- uri
- elsif uri = String.try_convert(uri)
- parse(uri)
- else
- raise ArgumentError,
- "bad argument (expected URI object or URI string)"
- end
- end
-
- end # class Parser
-
- # URI::Parser.new
- DEFAULT_PARSER = Parser.new
- DEFAULT_PARSER.pattern.each_pair do |sym, str|
- unless REGEXP::PATTERN.const_defined?(sym)
- REGEXP::PATTERN.const_set(sym, str)
- end
- end
- DEFAULT_PARSER.regexp.each_pair do |sym, str|
- const_set(sym, str)
- end
-
- module Util # :nodoc:
- def make_components_hash(klass, array_hash)
- tmp = {}
- if array_hash.kind_of?(Array) &&
- array_hash.size == klass.component.size - 1
- klass.component[1..-1].each_index do |i|
- begin
- tmp[klass.component[i + 1]] = array_hash[i].clone
- rescue TypeError
- tmp[klass.component[i + 1]] = array_hash[i]
- end
- end
-
- elsif array_hash.kind_of?(Hash)
- array_hash.each do |key, value|
- begin
- tmp[key] = value.clone
- rescue TypeError
- tmp[key] = value
- end
- end
- else
- raise ArgumentError,
- "expected Array of or Hash of components of #{klass.to_s} (#{klass.component[1..-1].join(', ')})"
- end
- tmp[:scheme] = klass.to_s.sub(/\A.*::/, '').downcase
-
- return tmp
- end
- module_function :make_components_hash
- end
-
- # module for escaping unsafe characters with codes.
- module Escape
- #
- # == Synopsis
- #
- # URI.escape(str [, unsafe])
- #
- # == Args
- #
- # +str+::
- # String to replaces in.
- # +unsafe+::
- # Regexp that matches all symbols that must be replaced with codes.
- # By default uses <tt>REGEXP::UNSAFE</tt>.
- # When this argument is a String, it represents a character set.
- #
- # == Description
- #
- # Escapes the string, replacing all unsafe characters with codes.
- #
- # == Usage
- #
- # require 'uri'
- #
- # enc_uri = URI.escape("http://example.com/?a=\11\15")
- # p enc_uri
- # # => "http://example.com/?a=%09%0D"
- #
- # p URI.unescape(enc_uri)
- # # => "http://example.com/?a=\t\r"
- #
- # p URI.escape("@?@!", "!?")
- # # => "@%3F@%21"
- #
- def escape(*arg)
- warn "#{caller(1)[0]}: warning: URI.escape is obsolete" if $VERBOSE
- DEFAULT_PARSER.escape(*arg)
- end
- alias encode escape
- #
- # == Synopsis
- #
- # URI.unescape(str)
- #
- # == Args
- #
- # +str+::
- # Unescapes the string.
- #
- # == Usage
- #
- # require 'uri'
- #
- # enc_uri = URI.escape("http://example.com/?a=\11\15")
- # p enc_uri
- # # => "http://example.com/?a=%09%0D"
- #
- # p URI.unescape(enc_uri)
- # # => "http://example.com/?a=\t\r"
- #
- def unescape(*arg)
- warn "#{caller(1)[0]}: warning: URI.unescape is obsolete" if $VERBOSE
- DEFAULT_PARSER.unescape(*arg)
- end
- alias decode unescape
- end # module Escape
-
- extend Escape
- include REGEXP
-
- @@schemes = {}
- # Returns a Hash of the defined schemes
- def self.scheme_list
- @@schemes
- end
-
- #
- # Base class for all URI exceptions.
- #
- class Error < StandardError; end
- #
- # Not a URI.
- #
- class InvalidURIError < Error; end
- #
- # Not a URI component.
- #
- class InvalidComponentError < Error; end
- #
- # URI is valid, bad usage is not.
- #
- class BadURIError < Error; end
-
- #
- # == Synopsis
- #
- # URI::split(uri)
- #
- # == Args
- #
- # +uri+::
- # String with URI.
- #
- # == Description
- #
- # Splits the string on following parts and returns array with result:
- #
- # * Scheme
- # * Userinfo
- # * Host
- # * Port
- # * Registry
- # * Path
- # * Opaque
- # * Query
- # * Fragment
- #
- # == Usage
- #
- # require 'uri'
- #
- # p URI.split("http://www.ruby-lang.org/")
- # # => ["http", nil, "www.ruby-lang.org", nil, nil, "/", nil, nil, nil]
- #
- def self.split(uri)
- DEFAULT_PARSER.split(uri)
- end
-
- #
- # == Synopsis
- #
- # URI::parse(uri_str)
- #
- # == Args
- #
- # +uri_str+::
- # String with URI.
- #
- # == Description
- #
- # Creates one of the URI's subclasses instance from the string.
- #
- # == Raises
- #
- # URI::InvalidURIError
- # Raised if URI given is not a correct one.
- #
- # == Usage
- #
- # require 'uri'
- #
- # uri = URI.parse("http://www.ruby-lang.org/")
- # p uri
- # # => #<URI::HTTP:0x202281be URL:http://www.ruby-lang.org/>
- # p uri.scheme
- # # => "http"
- # p uri.host
- # # => "www.ruby-lang.org"
- #
- def self.parse(uri)
- DEFAULT_PARSER.parse(uri)
- end
-
- #
- # == Synopsis
- #
- # URI::join(str[, str, ...])
- #
- # == Args
- #
- # +str+::
- # String(s) to work with
- #
- # == Description
- #
- # Joins URIs.
- #
- # == Usage
- #
- # require 'uri'
- #
- # p URI.join("http://example.com/","main.rbx")
- # # => #<URI::HTTP:0x2022ac02 URL:http://localhost/main.rbx>
- #
- # p URI.join('http://example.com', 'foo')
- # # => #<URI::HTTP:0x01ab80a0 URL:http://example.com/foo>
- #
- # p URI.join('http://example.com', '/foo', '/bar')
- # # => #<URI::HTTP:0x01aaf0b0 URL:http://example.com/bar>
- #
- # p URI.join('http://example.com', '/foo', 'bar')
- # # => #<URI::HTTP:0x801a92af0 URL:http://example.com/bar>
- #
- # p URI.join('http://example.com', '/foo/', 'bar')
- # # => #<URI::HTTP:0x80135a3a0 URL:http://example.com/foo/bar>
- #
- #
- def self.join(*str)
- DEFAULT_PARSER.join(*str)
- end
-
- #
- # == Synopsis
- #
- # URI::extract(str[, schemes][,&blk])
- #
- # == Args
- #
- # +str+::
- # String to extract URIs from.
- # +schemes+::
- # Limit URI matching to a specific schemes.
- #
- # == Description
- #
- # Extracts URIs from a string. If block given, iterates through all matched URIs.
- # Returns nil if block given or array with matches.
- #
- # == Usage
- #
- # require "uri"
- #
- # URI.extract("text here http://foo.example.org/bla and here mailto:test@example.com and here also.")
- # # => ["http://foo.example.com/bla", "mailto:test@example.com"]
- #
- def self.extract(str, schemes = nil, &block)
- DEFAULT_PARSER.extract(str, schemes, &block)
- end
-
- #
- # == Synopsis
- #
- # URI::regexp([match_schemes])
- #
- # == Args
- #
- # +match_schemes+::
- # Array of schemes. If given, resulting regexp matches to URIs
- # whose scheme is one of the match_schemes.
- #
- # == Description
- # Returns a Regexp object which matches to URI-like strings.
- # The Regexp object returned by this method includes arbitrary
- # number of capture group (parentheses). Never rely on it's number.
- #
- # == Usage
- #
- # require 'uri'
- #
- # # extract first URI from html_string
- # html_string.slice(URI.regexp)
- #
- # # remove ftp URIs
- # html_string.sub(URI.regexp(['ftp'])
- #
- # # You should not rely on the number of parentheses
- # html_string.scan(URI.regexp) do |*matches|
- # p $&
- # end
- #
- def self.regexp(schemes = nil)
- DEFAULT_PARSER.make_regexp(schemes)
- end
-
- TBLENCWWWCOMP_ = {} # :nodoc:
- 256.times do |i|
- TBLENCWWWCOMP_[i.chr] = '%%%02X' % i
- end
- TBLENCWWWCOMP_[' '] = '+'
- TBLENCWWWCOMP_.freeze
- TBLDECWWWCOMP_ = {} # :nodoc:
- 256.times do |i|
- h, l = i>>4, i&15
- TBLDECWWWCOMP_['%%%X%X' % [h, l]] = i.chr
- TBLDECWWWCOMP_['%%%x%X' % [h, l]] = i.chr
- TBLDECWWWCOMP_['%%%X%x' % [h, l]] = i.chr
- TBLDECWWWCOMP_['%%%x%x' % [h, l]] = i.chr
- end
- TBLDECWWWCOMP_['+'] = ' '
- TBLDECWWWCOMP_.freeze
-
- HTML5ASCIIINCOMPAT = [Encoding::UTF_7, Encoding::UTF_16BE, Encoding::UTF_16LE,
- Encoding::UTF_32BE, Encoding::UTF_32LE] # :nodoc:
-
- # Encode given +str+ to URL-encoded form data.
- #
- # This method doesn't convert *, -, ., 0-9, A-Z, _, a-z, but does convert SP
- # (ASCII space) to + and converts others to %XX.
- #
- # This is an implementation of
- # http://www.w3.org/TR/html5/forms.html#url-encoded-form-data
- #
- # See URI.decode_www_form_component, URI.encode_www_form
- def self.encode_www_form_component(str)
- str = str.to_s
- if HTML5ASCIIINCOMPAT.include?(str.encoding)
- str = str.encode(Encoding::UTF_8)
- else
- str = str.dup
- end
- str.force_encoding(Encoding::ASCII_8BIT)
- str.gsub!(/[^*\-.0-9A-Z_a-z]/, TBLENCWWWCOMP_)
- str.force_encoding(Encoding::US_ASCII)
- end
-
- # Decode given +str+ of URL-encoded form data.
- #
- # This decods + to SP.
- #
- # See URI.encode_www_form_component, URI.decode_www_form
- def self.decode_www_form_component(str, enc=Encoding::UTF_8)
- raise ArgumentError, "invalid %-encoding (#{str})" unless /\A[^%]*(?:%\h\h[^%]*)*\z/ =~ str
- str.gsub(/\+|%\h\h/, TBLDECWWWCOMP_).force_encoding(enc)
- end
-
- # Generate URL-encoded form data from given +enum+.
- #
- # This generates application/x-www-form-urlencoded data defined in HTML5
- # from given an Enumerable object.
- #
- # This internally uses URI.encode_www_form_component(str).
- #
- # This method doesn't convert the encoding of given items, so convert them
- # before call this method if you want to send data as other than original
- # encoding or mixed encoding data. (Strings which are encoded in an HTML5
- # ASCII incompatible encoding are converted to UTF-8.)
- #
- # This method doesn't handle files. When you send a file, use
- # multipart/form-data.
- #
- # This is an implementation of
- # http://www.w3.org/TR/html5/forms.html#url-encoded-form-data
- #
- # URI.encode_www_form([["q", "ruby"], ["lang", "en"]])
- # #=> "q=ruby&lang=en"
- # URI.encode_www_form("q" => "ruby", "lang" => "en")
- # #=> "q=ruby&lang=en"
- # URI.encode_www_form("q" => ["ruby", "perl"], "lang" => "en")
- # #=> "q=ruby&q=perl&lang=en"
- # URI.encode_www_form([["q", "ruby"], ["q", "perl"], ["lang", "en"]])
- # #=> "q=ruby&q=perl&lang=en"
- #
- # See URI.encode_www_form_component, URI.decode_www_form
- def self.encode_www_form(enum)
- enum.map do |k,v|
- if v.nil?
- encode_www_form_component(k)
- elsif v.respond_to?(:to_ary)
- v.to_ary.map do |w|
- str = encode_www_form_component(k)
- unless w.nil?
- str << '='
- str << encode_www_form_component(w)
- end
- end.join('&')
- else
- str = encode_www_form_component(k)
- str << '='
- str << encode_www_form_component(v)
- end
- end.join('&')
- end
-
- WFKV_ = '(?:[^%#=;&]*(?:%\h\h[^%#=;&]*)*)' # :nodoc:
-
- # Decode URL-encoded form data from given +str+.
- #
- # This decodes application/x-www-form-urlencoded data
- # and returns array of key-value array.
- # This internally uses URI.decode_www_form_component.
- #
- # _charset_ hack is not supported now because the mapping from given charset
- # to Ruby's encoding is not clear yet.
- # see also http://www.w3.org/TR/html5/syntax.html#character-encodings-0
- #
- # This refers http://www.w3.org/TR/html5/forms.html#url-encoded-form-data
- #
- # ary = URI.decode_www_form("a=1&a=2&b=3")
- # p ary #=> [['a', '1'], ['a', '2'], ['b', '3']]
- # p ary.assoc('a').last #=> '1'
- # p ary.assoc('b').last #=> '3'
- # p ary.rassoc('a').last #=> '2'
- # p Hash[ary] # => {"a"=>"2", "b"=>"3"}
- #
- # See URI.decode_www_form_component, URI.encode_www_form
- def self.decode_www_form(str, enc=Encoding::UTF_8)
- return [] if str.empty?
- unless /\A#{WFKV_}=#{WFKV_}(?:[;&]#{WFKV_}=#{WFKV_})*\z/o =~ str
- raise ArgumentError, "invalid data of application/x-www-form-urlencoded (#{str})"
- end
- ary = []
- $&.scan(/([^=;&]+)=([^;&]*)/) do
- ary << [decode_www_form_component($1, enc), decode_www_form_component($2, enc)]
- end
- ary
- end
-end # module URI
-
-module Kernel
-
- #
- # Returns +uri+ converted to a URI object.
- #
- def URI(uri)
- if uri.is_a?(URI::Generic)
- uri
- elsif uri = String.try_convert(uri)
- URI.parse(uri)
- else
- raise ArgumentError,
- "bad argument (expected URI object or URI string)"
- end
- end
- module_function :URI
-end
diff --git a/ruby_1_9_3/lib/uri/ftp.rb b/ruby_1_9_3/lib/uri/ftp.rb
deleted file mode 100644
index 971684a545..0000000000
--- a/ruby_1_9_3/lib/uri/ftp.rb
+++ /dev/null
@@ -1,262 +0,0 @@
-# = uri/ftp.rb
-#
-# Author:: Akira Yamada <akira@ruby-lang.org>
-# License:: You can redistribute it and/or modify it under the same term as Ruby.
-# Revision:: $Id$
-#
-# See URI for general documentation
-#
-
-require 'uri/generic'
-
-module URI
-
- #
- # FTP URI syntax is defined by RFC1738 section 3.2.
- #
- # This class will be redesigned because of difference of implementations;
- # the structure of its path. draft-hoffman-ftp-uri-04 is a draft but it
- # is a good summary about the de facto spec.
- # http://tools.ietf.org/html/draft-hoffman-ftp-uri-04
- #
- class FTP < Generic
- # A Default port of 21 for URI::FTP
- DEFAULT_PORT = 21
-
- #
- # An Array of the available components for URI::FTP
- #
- COMPONENT = [
- :scheme,
- :userinfo, :host, :port,
- :path, :typecode
- ].freeze
-
- #
- # Typecode is "a", "i" or "d".
- #
- # * "a" indicates a text file (the FTP command was ASCII)
- # * "i" indicates a binary file (FTP command IMAGE)
- # * "d" indicates the contents of a directory should be displayed
- #
- TYPECODE = ['a', 'i', 'd'].freeze
-
- # Typecode prefix
- # ';type='
- TYPECODE_PREFIX = ';type='.freeze
-
- # alternate initialization
- # Creates a new URI::FTP object.
- #
- # Unlike build(), this method does not escape the path component as
- # required by RFC1738; instead it is treated as per RFC2396.
- #
- # Arguments are user, password, host, port, path, typecode,
- # and arg_check, in that order.
- def self.new2(user, password, host, port, path,
- typecode = nil, arg_check = true)
- typecode = nil if typecode.size == 0
- if typecode && !TYPECODE.include?(typecode)
- raise ArgumentError,
- "bad typecode is specified: #{typecode}"
- end
-
- # do escape
-
- self.new('ftp',
- [user, password],
- host, port, nil,
- typecode ? path + TYPECODE_PREFIX + typecode : path,
- nil, nil, nil, arg_check)
- end
-
- #
- # == Description
- #
- # Creates a new URI::FTP object from components, with syntax checking.
- #
- # The components accepted are +userinfo+, +host+, +port+, +path+ and
- # +typecode+.
- #
- # The components should be provided either as an Array, or as a Hash
- # with keys formed by preceding the component names with a colon.
- #
- # If an Array is used, the components must be passed in the order
- # [userinfo, host, port, path, typecode]
- #
- # If the path supplied is absolute, it will be escaped in order to
- # make it absolute in the URI. Examples:
- #
- # require 'uri'
- #
- # uri = URI::FTP.build(['user:password', 'ftp.example.com', nil,
- # '/path/file.> zip', 'i'])
- # puts uri.to_s -> ftp://user:password@ftp.example.com/%2Fpath/file.zip;type=a
- #
- # uri2 = URI::FTP.build({:host => 'ftp.example.com',
- # :path => 'ruby/src'})
- # puts uri2.to_s -> ftp://ftp.example.com/ruby/src
- #
- def self.build(args)
-
- # Fix the incoming path to be generic URL syntax
- # FTP path -> URL path
- # foo/bar /foo/bar
- # /foo/bar /%2Ffoo/bar
- #
- if args.kind_of?(Array)
- args[3] = '/' + args[3].sub(/^\//, '%2F')
- else
- args[:path] = '/' + args[:path].sub(/^\//, '%2F')
- end
-
- tmp = Util::make_components_hash(self, args)
-
- if tmp[:typecode]
- if tmp[:typecode].size == 1
- tmp[:typecode] = TYPECODE_PREFIX + tmp[:typecode]
- end
- tmp[:path] << tmp[:typecode]
- end
-
- return super(tmp)
- end
-
- #
- # == Description
- #
- # Creates a new URI::FTP object from generic URL components with no
- # syntax checking.
- #
- # Unlike build(), this method does not escape the path component as
- # required by RFC1738; instead it is treated as per RFC2396.
- #
- # Arguments are +scheme+, +userinfo+, +host+, +port+, +registry+, +path+,
- # +opaque+, +query+ and +fragment+, in that order.
- #
- def initialize(*arg)
- raise InvalidURIError unless arg[5]
- arg[5] = arg[5].sub(/^\//,'').sub(/^%2F/,'/')
- super(*arg)
- @typecode = nil
- tmp = @path.index(TYPECODE_PREFIX)
- if tmp
- typecode = @path[tmp + TYPECODE_PREFIX.size..-1]
- @path = @path[0..tmp - 1]
-
- if arg[-1]
- self.typecode = typecode
- else
- self.set_typecode(typecode)
- end
- end
- end
-
- # typecode accessor
- #
- # see URI::FTP::COMPONENT
- attr_reader :typecode
-
- # validates typecode +v+,
- # returns a +true+ or +false+ boolean
- #
- def check_typecode(v)
- if TYPECODE.include?(v)
- return true
- else
- raise InvalidComponentError,
- "bad typecode(expected #{TYPECODE.join(', ')}): #{v}"
- end
- end
- private :check_typecode
-
- # private setter for the typecode +v+
- #
- # see also URI::FTP.typecode=
- #
- def set_typecode(v)
- @typecode = v
- end
- protected :set_typecode
-
- #
- # == Args
- #
- # +v+::
- # String
- #
- # == Description
- #
- # public setter for the typecode +v+.
- # (with validation)
- #
- # see also URI::FTP.check_typecode
- #
- # == Usage
- #
- # require 'uri'
- #
- # uri = URI.parse("ftp://john@ftp.example.com/my_file.img")
- # #=> #<URI::FTP:0x00000000923650 URL:ftp://john@ftp.example.com/my_file.img>
- # uri.typecode = "i"
- # # => "i"
- # uri
- # #=> #<URI::FTP:0x00000000923650 URL:ftp://john@ftp.example.com/my_file.img;type=i>
- #
- def typecode=(typecode)
- check_typecode(typecode)
- set_typecode(typecode)
- typecode
- end
-
- def merge(oth) # :nodoc:
- tmp = super(oth)
- if self != tmp
- tmp.set_typecode(oth.typecode)
- end
-
- return tmp
- end
-
- # Returns the path from an FTP URI.
- #
- # RFC 1738 specifically states that the path for an FTP URI does not
- # include the / which separates the URI path from the URI host. Example:
- #
- # ftp://ftp.example.com/pub/ruby
- #
- # The above URI indicates that the client should connect to
- # ftp.example.com then cd pub/ruby from the initial login directory.
- #
- # If you want to cd to an absolute directory, you must include an
- # escaped / (%2F) in the path. Example:
- #
- # ftp://ftp.example.com/%2Fpub/ruby
- #
- # This method will then return "/pub/ruby"
- #
- def path
- return @path.sub(/^\//,'').sub(/^%2F/,'/')
- end
-
- def set_path(v)
- super("/" + v.sub(/^\//, "%2F"))
- end
- protected :set_path
-
- def to_s
- save_path = nil
- if @typecode
- save_path = @path
- @path = @path + TYPECODE_PREFIX + @typecode
- end
- str = super
- if @typecode
- @path = save_path
- end
-
- return str
- end
- end
- @@schemes['FTP'] = FTP
-end
diff --git a/ruby_1_9_3/lib/uri/generic.rb b/ruby_1_9_3/lib/uri/generic.rb
deleted file mode 100644
index 1056cfe3bc..0000000000
--- a/ruby_1_9_3/lib/uri/generic.rb
+++ /dev/null
@@ -1,1599 +0,0 @@
-# = uri/generic.rb
-#
-# Author:: Akira Yamada <akira@ruby-lang.org>
-# License:: You can redistribute it and/or modify it under the same term as Ruby.
-# Revision:: $Id$
-#
-# See URI for general documentation
-#
-
-require 'uri/common'
-
-module URI
-
- #
- # Base class for all URI classes.
- # Implements generic URI syntax as per RFC 2396.
- #
- class Generic
- include URI
-
- #
- # A Default port of nil for URI::Generic
- #
- DEFAULT_PORT = nil
-
- #
- # Returns default port
- #
- def self.default_port
- self::DEFAULT_PORT
- end
-
- #
- # Returns default port
- #
- def default_port
- self.class.default_port
- end
-
- #
- # An Array of the available components for URI::Generic
- #
- COMPONENT = [
- :scheme,
- :userinfo, :host, :port, :registry,
- :path, :opaque,
- :query,
- :fragment
- ].freeze
-
- #
- # Components of the URI in the order.
- #
- def self.component
- self::COMPONENT
- end
-
- #
- # Default to not use the registry for a URI::Generic
- #
- USE_REGISTRY = false
-
- #
- # Returns whether a registry of naming
- # authorities are being used.
- #
- def self.use_registry
- self::USE_REGISTRY
- end
-
- #
- # == Synopsis
- #
- # See #new
- #
- # == Description
- #
- # At first, tries to create a new URI::Generic instance using
- # URI::Generic::build. But, if exception URI::InvalidComponentError is raised,
- # then it URI::Escape.escape all URI components and tries again.
- #
- #
- def self.build2(args)
- begin
- return self.build(args)
- rescue InvalidComponentError
- if args.kind_of?(Array)
- return self.build(args.collect{|x|
- if x
- parser.escape(x)
- else
- x
- end
- })
- elsif args.kind_of?(Hash)
- tmp = {}
- args.each do |key, value|
- tmp[key] = if value
- parser.escape(value)
- else
- value
- end
- end
- return self.build(tmp)
- end
- end
- end
-
- #
- # == Synopsis
- #
- # See #new
- #
- # == Description
- #
- # Creates a new URI::Generic instance from components of URI::Generic
- # with check. Components are: scheme, userinfo, host, port, registry, path,
- # opaque, query and fragment. You can provide arguments either by an Array or a Hash.
- # See #new for hash keys to use or for order of array items.
- #
- def self.build(args)
- if args.kind_of?(Array) &&
- args.size == ::URI::Generic::COMPONENT.size
- tmp = args
- elsif args.kind_of?(Hash)
- tmp = ::URI::Generic::COMPONENT.collect do |c|
- if args.include?(c)
- args[c]
- else
- nil
- end
- end
- else
- raise ArgumentError,
- "expected Array of or Hash of components of #{self.class} (#{self.class.component.join(', ')})"
- end
-
- tmp << nil
- tmp << true
- return self.new(*tmp)
- end
- #
- # == Args
- #
- # +scheme+::
- # Protocol scheme, i.e. 'http','ftp','mailto' and so on.
- # +userinfo+::
- # User name and password, i.e. 'sdmitry:bla'
- # +host+::
- # Server host name
- # +port+::
- # Server port
- # +registry+::
- # Registry of naming authorities.
- # +path+::
- # Path on server
- # +opaque+::
- # Opaque part
- # +query+::
- # Query data
- # +fragment+::
- # A part of URI after '#' sign
- # +parser+::
- # Parser for internal use [URI::DEFAULT_PARSER by default]
- # +arg_check+::
- # Check arguments [false by default]
- #
- # == Description
- #
- # Creates a new URI::Generic instance from ``generic'' components without check.
- #
- def initialize(scheme,
- userinfo, host, port, registry,
- path, opaque,
- query,
- fragment,
- parser = DEFAULT_PARSER,
- arg_check = false)
- @scheme = nil
- @user = nil
- @password = nil
- @host = nil
- @port = nil
- @path = nil
- @query = nil
- @opaque = nil
- @registry = nil
- @fragment = nil
- @parser = parser == DEFAULT_PARSER ? nil : parser
-
- if arg_check
- self.scheme = scheme
- self.userinfo = userinfo
- self.host = host
- self.port = port
- self.path = path
- self.query = query
- self.opaque = opaque
- self.registry = registry
- self.fragment = fragment
- else
- self.set_scheme(scheme)
- self.set_userinfo(userinfo)
- self.set_host(host)
- self.set_port(port)
- self.set_path(path)
- self.set_query(query)
- self.set_opaque(opaque)
- self.set_registry(registry)
- self.set_fragment(fragment)
- end
- if @registry && !self.class.use_registry
- raise InvalidURIError,
- "the scheme #{@scheme} does not accept registry part: #{@registry} (or bad hostname?)"
- end
-
- @scheme.freeze if @scheme
- self.set_path('') if !@path && !@opaque # (see RFC2396 Section 5.2)
- self.set_port(self.default_port) if self.default_port && !@port
- end
-
- #
- # returns the scheme component of the URI.
- #
- # URI("http://foo/bar/baz").scheme #=> "http"
- #
- attr_reader :scheme
-
- # returns the host component of the URI.
- #
- # URI("http://foo/bar/baz").host #=> "foo"
- #
- # It returns nil if no host component.
- #
- # URI("mailto:foo@example.org").host #=> nil
- #
- # The component doesn't contains the port number.
- #
- # URI("http://foo:8080/bar/baz").host #=> "foo"
- #
- # Since IPv6 addresses are wrapped by brackets in URIs,
- # this method returns IPv6 addresses wrapped by brackets.
- # This form is not appropriate to pass socket methods such as TCPSocket.open.
- # If unwrapped host names are required, use "hostname" method.
- #
- # URI("http://[::1]/bar/baz").host #=> "[::1]"
- # URI("http://[::1]/bar/baz").hostname #=> "::1"
- #
- attr_reader :host
-
- # returns the port component of the URI.
- #
- # URI("http://foo/bar/baz").port #=> "80"
- #
- # URI("http://foo:8080/bar/baz").port #=> "8080"
- #
- attr_reader :port
-
- # returns the registry component of the URI.
- #
- # (see RFC2396 Section 3.2)
- #
- attr_reader :registry
-
- # returns the path component of the URI.
- #
- # URI("http://foo/bar/baz").path #=> "/bar/baz"
- #
- attr_reader :path
-
- # returns the query component of the URI.
- #
- # URI("http://foo/bar/baz?search=FooBar").query #=> "search=FooBar"
- #
- attr_reader :query
-
- # returns the opaque part of the URI.
- #
- # URI("mailto:foo@example.org").opaque #=> "foo@example.org"
- #
- # Portion of the path that does make use of the slash '/'.
- # The path typically refers to the absolute path and the opaque part.
- # (see RFC2396 Section 3 and 5.2)
- #
- attr_reader :opaque
-
- # returns the fragment component of the URI.
- #
- # URI("http://foo/bar/baz?search=FooBar#ponies").fragment #=> "ponies"
- #
- attr_reader :fragment
-
- # returns the parser to be used.
- #
- # Unless a URI::Parser is defined, then DEFAULT_PARSER is used.
- #
- def parser
- if !defined?(@parser) || !@parser
- DEFAULT_PARSER
- else
- @parser || DEFAULT_PARSER
- end
- end
-
- # replace self by other URI object
- def replace!(oth)
- if self.class != oth.class
- raise ArgumentError, "expected #{self.class} object"
- end
-
- component.each do |c|
- self.__send__("#{c}=", oth.__send__(c))
- end
- end
- private :replace!
-
- #
- # Components of the URI in the order.
- #
- def component
- self.class.component
- end
-
- #
- # check the scheme +v+ component against the URI::Parser Regexp for :SCHEME
- #
- def check_scheme(v)
- if v && parser.regexp[:SCHEME] !~ v
- raise InvalidComponentError,
- "bad component(expected scheme component): #{v}"
- end
-
- return true
- end
- private :check_scheme
-
- # protected setter for the scheme component +v+
- #
- # see also URI::Generic.scheme=
- #
- def set_scheme(v)
- @scheme = v
- end
- protected :set_scheme
-
- #
- # == Args
- #
- # +v+::
- # String
- #
- # == Description
- #
- # public setter for the scheme component +v+.
- # (with validation)
- #
- # see also URI::Generic.check_scheme
- #
- # == Usage
- #
- # require 'uri'
- #
- # uri = URI.parse("http://my.example.com")
- # uri.scheme = "https"
- # # => "https"
- # uri
- # #=> #<URI::HTTP:0x000000008e89e8 URL:https://my.example.com>
- #
- def scheme=(v)
- check_scheme(v)
- set_scheme(v)
- v
- end
-
- #
- # check the +user+ and +password+.
- #
- # If +password+ is not provided, then +user+ is
- # split, using URI::Generic.split_userinfo, to
- # pull +user+ and +password.
- #
- # see also URI::Generic.check_user, URI::Generic.check_password
- #
- def check_userinfo(user, password = nil)
- if !password
- user, password = split_userinfo(user)
- end
- check_user(user)
- check_password(password, user)
-
- return true
- end
- private :check_userinfo
-
- #
- # check the user +v+ component for RFC2396 compliance
- # and against the URI::Parser Regexp for :USERINFO
- #
- # Can not have a registry or opaque component defined,
- # with a user component defined.
- #
- def check_user(v)
- if @registry || @opaque
- raise InvalidURIError,
- "can not set user with registry or opaque"
- end
-
- return v unless v
-
- if parser.regexp[:USERINFO] !~ v
- raise InvalidComponentError,
- "bad component(expected userinfo component or user component): #{v}"
- end
-
- return true
- end
- private :check_user
-
- #
- # check the password +v+ component for RFC2396 compliance
- # and against the URI::Parser Regexp for :USERINFO
- #
- # Can not have a registry or opaque component defined,
- # with a user component defined.
- #
- def check_password(v, user = @user)
- if @registry || @opaque
- raise InvalidURIError,
- "can not set password with registry or opaque"
- end
- return v unless v
-
- if !user
- raise InvalidURIError,
- "password component depends user component"
- end
-
- if parser.regexp[:USERINFO] !~ v
- raise InvalidComponentError,
- "bad component(expected user component): #{v}"
- end
-
- return true
- end
- private :check_password
-
- #
- # Sets userinfo, argument is string like 'name:pass'
- #
- def userinfo=(userinfo)
- if userinfo.nil?
- return nil
- end
- check_userinfo(*userinfo)
- set_userinfo(*userinfo)
- # returns userinfo
- end
-
- #
- # == Args
- #
- # +v+::
- # String
- #
- # == Description
- #
- # public setter for the +user+ component.
- # (with validation)
- #
- # see also URI::Generic.check_user
- #
- # == Usage
- #
- # require 'uri'
- #
- # uri = URI.parse("http://john:S3nsit1ve@my.example.com")
- # uri.user = "sam"
- # # => "sam"
- # uri
- # #=> #<URI::HTTP:0x00000000881d90 URL:http://sam:V3ry_S3nsit1ve@my.example.com>
- #
- def user=(user)
- check_user(user)
- set_user(user)
- # returns user
- end
-
- #
- # == Args
- #
- # +v+::
- # String
- #
- # == Description
- #
- # public setter for the +password+ component.
- # (with validation)
- #
- # see also URI::Generic.check_password
- #
- # == Usage
- #
- # require 'uri'
- #
- # uri = URI.parse("http://john:S3nsit1ve@my.example.com")
- # uri.password = "V3ry_S3nsit1ve"
- # # => "V3ry_S3nsit1ve"
- # uri
- # #=> #<URI::HTTP:0x00000000881d90 URL:http://john:V3ry_S3nsit1ve@my.example.com>
- #
- def password=(password)
- check_password(password)
- set_password(password)
- # returns password
- end
-
- # protect setter for the +user+ component, and +password+ if available.
- # (with validation)
- #
- # see also URI::Generic.userinfo=
- #
- def set_userinfo(user, password = nil)
- unless password
- user, password = split_userinfo(user)
- end
- @user = user
- @password = password if password
-
- [@user, @password]
- end
- protected :set_userinfo
-
- # protected setter for the user component +v+
- #
- # see also URI::Generic.user=
- #
- def set_user(v)
- set_userinfo(v, @password)
- v
- end
- protected :set_user
-
- # protected setter for the password component +v+
- #
- # see also URI::Generic.password=
- #
- def set_password(v)
- @password = v
- # returns v
- end
- protected :set_password
-
- # returns the userinfo +ui+ as user, password
- # if properly formated as 'user:password'
- def split_userinfo(ui)
- return nil, nil unless ui
- user, password = ui.split(/:/, 2)
-
- return user, password
- end
- private :split_userinfo
-
- # escapes 'user:password' +v+ based on RFC 1738 section 3.1
- def escape_userpass(v)
- v = parser.escape(v, /[@:\/]/o) # RFC 1738 section 3.1 #/
- end
- private :escape_userpass
-
- # returns the userinfo, either as 'user' or 'user:password'
- def userinfo
- if @user.nil?
- nil
- elsif @password.nil?
- @user
- else
- @user + ':' + @password
- end
- end
-
- # returns the user component
- def user
- @user
- end
-
- # returns the password component
- def password
- @password
- end
-
- #
- # check the host +v+ component for RFC2396 compliance
- # and against the URI::Parser Regexp for :HOST
- #
- # Can not have a registry or opaque component defined,
- # with a host component defined.
- #
- def check_host(v)
- return v unless v
-
- if @registry || @opaque
- raise InvalidURIError,
- "can not set host with registry or opaque"
- elsif parser.regexp[:HOST] !~ v
- raise InvalidComponentError,
- "bad component(expected host component): #{v}"
- end
-
- return true
- end
- private :check_host
-
- # protected setter for the host component +v+
- #
- # see also URI::Generic.host=
- #
- def set_host(v)
- @host = v
- end
- protected :set_host
-
- #
- # == Args
- #
- # +v+::
- # String
- #
- # == Description
- #
- # public setter for the host component +v+.
- # (with validation)
- #
- # see also URI::Generic.check_host
- #
- # == Usage
- #
- # require 'uri'
- #
- # uri = URI.parse("http://my.example.com")
- # uri.host = "foo.com"
- # # => "foo.com"
- # uri
- # #=> #<URI::HTTP:0x000000008e89e8 URL:http://foo.com>
- #
- def host=(v)
- check_host(v)
- set_host(v)
- v
- end
-
- # extract the host part of the URI and unwrap brackets for IPv6 addresses.
- #
- # This method is same as URI::Generic#host except
- # brackets for IPv6 (andn future IP) addresses are removed.
- #
- # u = URI("http://[::1]/bar")
- # p u.hostname #=> "::1"
- # p u.host #=> "[::1]"
- #
- def hostname
- v = self.host
- /\A\[(.*)\]\z/ =~ v ? $1 : v
- end
-
- # set the host part of the URI as the argument with brackets for IPv6 addresses.
- #
- # This method is same as URI::Generic#host= except
- # the argument can be bare IPv6 address.
- #
- # u = URI("http://foo/bar")
- # p u.to_s #=> "http://foo/bar"
- # u.hostname = "::1"
- # p u.to_s #=> "http://[::1]/bar"
- #
- # If the arugument seems IPv6 address,
- # it is wrapped by brackets.
- #
- def hostname=(v)
- v = "[#{v}]" if /\A\[.*\]\z/ !~ v && /:/ =~ v
- self.host = v
- end
-
- #
- # check the port +v+ component for RFC2396 compliance
- # and against the URI::Parser Regexp for :PORT
- #
- # Can not have a registry or opaque component defined,
- # with a port component defined.
- #
- def check_port(v)
- return v unless v
-
- if @registry || @opaque
- raise InvalidURIError,
- "can not set port with registry or opaque"
- elsif !v.kind_of?(Fixnum) && parser.regexp[:PORT] !~ v
- raise InvalidComponentError,
- "bad component(expected port component): #{v}"
- end
-
- return true
- end
- private :check_port
-
- # protected setter for the port component +v+
- #
- # see also URI::Generic.port=
- #
- def set_port(v)
- unless !v || v.kind_of?(Fixnum)
- if v.empty?
- v = nil
- else
- v = v.to_i
- end
- end
- @port = v
- end
- protected :set_port
-
- #
- # == Args
- #
- # +v+::
- # String
- #
- # == Description
- #
- # public setter for the port component +v+.
- # (with validation)
- #
- # see also URI::Generic.check_port
- #
- # == Usage
- #
- # require 'uri'
- #
- # uri = URI.parse("http://my.example.com")
- # uri.port = 8080
- # # => 8080
- # uri
- # #=> #<URI::HTTP:0x000000008e89e8 URL:http://my.example.com:8080>
- #
- def port=(v)
- check_port(v)
- set_port(v)
- port
- end
-
- #
- # check the registry +v+ component for RFC2396 compliance
- # and against the URI::Parser Regexp for :REGISTRY
- #
- # Can not have a host, port or user component defined,
- # with a registry component defined.
- #
- def check_registry(v)
- return v unless v
-
- # raise if both server and registry are not nil, because:
- # authority = server | reg_name
- # server = [ [ userinfo "@" ] hostport ]
- if @host || @port || @user # userinfo = @user + ':' + @password
- raise InvalidURIError,
- "can not set registry with host, port, or userinfo"
- elsif v && parser.regexp[:REGISTRY] !~ v
- raise InvalidComponentError,
- "bad component(expected registry component): #{v}"
- end
-
- return true
- end
- private :check_registry
-
- # protected setter for the registry component +v+
- #
- # see also URI::Generic.registry=
- #
- def set_registry(v)
- @registry = v
- end
- protected :set_registry
-
- #
- # == Args
- #
- # +v+::
- # String
- #
- # == Description
- #
- # public setter for the registry component +v+.
- # (with validation)
- #
- # see also URI::Generic.check_registry
- #
- def registry=(v)
- check_registry(v)
- set_registry(v)
- v
- end
-
- #
- # check the path +v+ component for RFC2396 compliance
- # and against the URI::Parser Regexp
- # for :ABS_PATH and :REL_PATH
- #
- # Can not have a opaque component defined,
- # with a path component defined.
- #
- def check_path(v)
- # raise if both hier and opaque are not nil, because:
- # absoluteURI = scheme ":" ( hier_part | opaque_part )
- # hier_part = ( net_path | abs_path ) [ "?" query ]
- if v && @opaque
- raise InvalidURIError,
- "path conflicts with opaque"
- end
-
- # If scheme is ftp, path may be relative.
- # See RFC 1738 section 3.2.2, and RFC 2396.
- if @scheme && @scheme != "ftp"
- if v && v != '' && parser.regexp[:ABS_PATH] !~ v
- raise InvalidComponentError,
- "bad component(expected absolute path component): #{v}"
- end
- else
- if v && v != '' && parser.regexp[:ABS_PATH] !~ v && parser.regexp[:REL_PATH] !~ v
- raise InvalidComponentError,
- "bad component(expected relative path component): #{v}"
- end
- end
-
- return true
- end
- private :check_path
-
- # protected setter for the path component +v+
- #
- # see also URI::Generic.path=
- #
- def set_path(v)
- @path = v
- end
- protected :set_path
-
- #
- # == Args
- #
- # +v+::
- # String
- #
- # == Description
- #
- # public setter for the path component +v+.
- # (with validation)
- #
- # see also URI::Generic.check_path
- #
- # == Usage
- #
- # require 'uri'
- #
- # uri = URI.parse("http://my.example.com/pub/files")
- # uri.path = "/faq/"
- # # => "/faq/"
- # uri
- # #=> #<URI::HTTP:0x000000008e89e8 URL:http://my.example.com/faq/>
- #
- def path=(v)
- check_path(v)
- set_path(v)
- v
- end
-
- #
- # check the query +v+ component for RFC2396 compliance
- # and against the URI::Parser Regexp for :QUERY
- #
- # Can not have a opaque component defined,
- # with a query component defined.
- #
- def check_query(v)
- return v unless v
-
- # raise if both hier and opaque are not nil, because:
- # absoluteURI = scheme ":" ( hier_part | opaque_part )
- # hier_part = ( net_path | abs_path ) [ "?" query ]
- if @opaque
- raise InvalidURIError,
- "query conflicts with opaque"
- end
-
- if v && v != '' && parser.regexp[:QUERY] !~ v
- raise InvalidComponentError,
- "bad component(expected query component): #{v}"
- end
-
- return true
- end
- private :check_query
-
- # protected setter for the query component +v+
- #
- # see also URI::Generic.query=
- #
- def set_query(v)
- @query = v
- end
- protected :set_query
-
- #
- # == Args
- #
- # +v+::
- # String
- #
- # == Description
- #
- # public setter for the query component +v+.
- # (with validation)
- #
- # see also URI::Generic.check_query
- #
- # == Usage
- #
- # require 'uri'
- #
- # uri = URI.parse("http://my.example.com/?id=25")
- # uri.query = "id=1"
- # # => "id=1"
- # uri
- # #=> #<URI::HTTP:0x000000008e89e8 URL:http://my.example.com/?id=1>
- #
- def query=(v)
- check_query(v)
- set_query(v)
- v
- end
-
- #
- # check the opaque +v+ component for RFC2396 compliance and
- # against the URI::Parser Regexp for :OPAQUE
- #
- # Can not have a host, port, user or path component defined,
- # with an opaque component defined.
- #
- def check_opaque(v)
- return v unless v
-
- # raise if both hier and opaque are not nil, because:
- # absoluteURI = scheme ":" ( hier_part | opaque_part )
- # hier_part = ( net_path | abs_path ) [ "?" query ]
- if @host || @port || @user || @path # userinfo = @user + ':' + @password
- raise InvalidURIError,
- "can not set opaque with host, port, userinfo or path"
- elsif v && parser.regexp[:OPAQUE] !~ v
- raise InvalidComponentError,
- "bad component(expected opaque component): #{v}"
- end
-
- return true
- end
- private :check_opaque
-
- # protected setter for the opaque component +v+
- #
- # see also URI::Generic.opaque=
- #
- def set_opaque(v)
- @opaque = v
- end
- protected :set_opaque
-
- #
- # == Args
- #
- # +v+::
- # String
- #
- # == Description
- #
- # public setter for the opaque component +v+.
- # (with validation)
- #
- # see also URI::Generic.check_opaque
- #
- def opaque=(v)
- check_opaque(v)
- set_opaque(v)
- v
- end
-
- #
- # check the fragment +v+ component against the URI::Parser Regexp for :FRAGMENT
- #
- def check_fragment(v)
- return v unless v
-
- if v && v != '' && parser.regexp[:FRAGMENT] !~ v
- raise InvalidComponentError,
- "bad component(expected fragment component): #{v}"
- end
-
- return true
- end
- private :check_fragment
-
- # protected setter for the fragment component +v+
- #
- # see also URI::Generic.fragment=
- #
- def set_fragment(v)
- @fragment = v
- end
- protected :set_fragment
-
- #
- # == Args
- #
- # +v+::
- # String
- #
- # == Description
- #
- # public setter for the fragment component +v+.
- # (with validation)
- #
- # see also URI::Generic.check_fragment
- #
- # == Usage
- #
- # require 'uri'
- #
- # uri = URI.parse("http://my.example.com/?id=25#time=1305212049")
- # uri.fragment = "time=1305212086"
- # # => "time=1305212086"
- # uri
- # #=> #<URI::HTTP:0x000000007a81f8 URL:http://my.example.com/?id=25#time=1305212086>
- #
- def fragment=(v)
- check_fragment(v)
- set_fragment(v)
- v
- end
-
- #
- # Checks if URI has a path
- #
- def hierarchical?
- if @path
- true
- else
- false
- end
- end
-
- #
- # Checks if URI is an absolute one
- #
- def absolute?
- if @scheme
- true
- else
- false
- end
- end
- alias absolute absolute?
-
- #
- # Checks if URI is relative
- #
- def relative?
- !absolute?
- end
-
- #
- # returns an Array of the path split on '/'
- #
- def split_path(path)
- path.split(%r{/+}, -1)
- end
- private :split_path
-
- #
- # Merges a base path +base+, with relative path +rel+,
- # returns a modified base path.
- #
- def merge_path(base, rel)
-
- # RFC2396, Section 5.2, 5)
- # RFC2396, Section 5.2, 6)
- base_path = split_path(base)
- rel_path = split_path(rel)
-
- # RFC2396, Section 5.2, 6), a)
- base_path << '' if base_path.last == '..'
- while i = base_path.index('..')
- base_path.slice!(i - 1, 2)
- end
-
- if (first = rel_path.first) and first.empty?
- base_path.clear
- rel_path.shift
- end
-
- # RFC2396, Section 5.2, 6), c)
- # RFC2396, Section 5.2, 6), d)
- rel_path.push('') if rel_path.last == '.' || rel_path.last == '..'
- rel_path.delete('.')
-
- # RFC2396, Section 5.2, 6), e)
- tmp = []
- rel_path.each do |x|
- if x == '..' &&
- !(tmp.empty? || tmp.last == '..')
- tmp.pop
- else
- tmp << x
- end
- end
-
- add_trailer_slash = !tmp.empty?
- if base_path.empty?
- base_path = [''] # keep '/' for root directory
- elsif add_trailer_slash
- base_path.pop
- end
- while x = tmp.shift
- if x == '..'
- # RFC2396, Section 4
- # a .. or . in an absolute path has no special meaning
- base_path.pop if base_path.size > 1
- else
- # if x == '..'
- # valid absolute (but abnormal) path "/../..."
- # else
- # valid absolute path
- # end
- base_path << x
- tmp.each {|t| base_path << t}
- add_trailer_slash = false
- break
- end
- end
- base_path.push('') if add_trailer_slash
-
- return base_path.join('/')
- end
- private :merge_path
-
- #
- # == Args
- #
- # +oth+::
- # URI or String
- #
- # == Description
- #
- # Destructive form of #merge
- #
- # == Usage
- #
- # require 'uri'
- #
- # uri = URI.parse("http://my.example.com")
- # uri.merge!("/main.rbx?page=1")
- # p uri
- # # => #<URI::HTTP:0x2021f3b0 URL:http://my.example.com/main.rbx?page=1>
- #
- def merge!(oth)
- t = merge(oth)
- if self == t
- nil
- else
- replace!(t)
- self
- end
- end
-
- #
- # == Args
- #
- # +oth+::
- # URI or String
- #
- # == Description
- #
- # Merges two URI's.
- #
- # == Usage
- #
- # require 'uri'
- #
- # uri = URI.parse("http://my.example.com")
- # p uri.merge("/main.rbx?page=1")
- # # => #<URI::HTTP:0x2021f3b0 URL:http://my.example.com/main.rbx?page=1>
- #
- def merge(oth)
- begin
- base, rel = merge0(oth)
- rescue
- raise $!.class, $!.message
- end
-
- if base == rel
- return base
- end
-
- authority = rel.userinfo || rel.host || rel.port
-
- # RFC2396, Section 5.2, 2)
- if (rel.path.nil? || rel.path.empty?) && !authority && !rel.query
- base.set_fragment(rel.fragment) if rel.fragment
- return base
- end
-
- base.set_query(nil)
- base.set_fragment(nil)
-
- # RFC2396, Section 5.2, 4)
- if !authority
- base.set_path(merge_path(base.path, rel.path)) if base.path && rel.path
- else
- # RFC2396, Section 5.2, 4)
- base.set_path(rel.path) if rel.path
- end
-
- # RFC2396, Section 5.2, 7)
- base.set_userinfo(rel.userinfo) if rel.userinfo
- base.set_host(rel.host) if rel.host
- base.set_port(rel.port) if rel.port
- base.set_query(rel.query) if rel.query
- base.set_fragment(rel.fragment) if rel.fragment
-
- return base
- end # merge
- alias + merge
-
- # return base and rel.
- # you can modify `base', but can not `rel'.
- def merge0(oth)
- oth = parser.send(:convert_to_uri, oth)
-
- if self.relative? && oth.relative?
- raise BadURIError,
- "both URI are relative"
- end
-
- if self.absolute? && oth.absolute?
- #raise BadURIError,
- # "both URI are absolute"
- # hmm... should return oth for usability?
- return oth, oth
- end
-
- if self.absolute?
- return self.dup, oth
- else
- return oth, oth
- end
- end
- private :merge0
-
- # :stopdoc:
- def route_from_path(src, dst)
- case dst
- when src
- # RFC2396, Section 4.2
- return ''
- when %r{(?:\A|/)\.\.?(?:/|\z)}
- # dst has abnormal absolute path,
- # like "/./", "/../", "/x/../", ...
- return dst.dup
- end
-
- src_path = src.scan(%r{(?:\A|[^/]+)/})
- dst_path = dst.scan(%r{(?:\A|[^/]+)/?})
-
- # discard same parts
- while !dst_path.empty? && dst_path.first == src_path.first
- src_path.shift
- dst_path.shift
- end
-
- tmp = dst_path.join
-
- # calculate
- if src_path.empty?
- if tmp.empty?
- return './'
- elsif dst_path.first.include?(':') # (see RFC2396 Section 5)
- return './' + tmp
- else
- return tmp
- end
- end
-
- return '../' * src_path.size + tmp
- end
- private :route_from_path
- # :startdoc:
-
- # :stopdoc:
- def route_from0(oth)
- oth = parser.send(:convert_to_uri, oth)
- if self.relative?
- raise BadURIError,
- "relative URI: #{self}"
- end
- if oth.relative?
- raise BadURIError,
- "relative URI: #{oth}"
- end
-
- if self.scheme != oth.scheme
- return self, self.dup
- end
- rel = URI::Generic.new(nil, # it is relative URI
- self.userinfo, self.host, self.port,
- self.registry, self.path, self.opaque,
- self.query, self.fragment, parser)
-
- if rel.userinfo != oth.userinfo ||
- rel.host.to_s.downcase != oth.host.to_s.downcase ||
- rel.port != oth.port
-
- if self.userinfo.nil? && self.host.nil?
- return self, self.dup
- end
-
- rel.set_port(nil) if rel.port == oth.default_port
- return rel, rel
- end
- rel.set_userinfo(nil)
- rel.set_host(nil)
- rel.set_port(nil)
-
- if rel.path && rel.path == oth.path
- rel.set_path('')
- rel.set_query(nil) if rel.query == oth.query
- return rel, rel
- elsif rel.opaque && rel.opaque == oth.opaque
- rel.set_opaque('')
- rel.set_query(nil) if rel.query == oth.query
- return rel, rel
- end
-
- # you can modify `rel', but can not `oth'.
- return oth, rel
- end
- private :route_from0
- # :startdoc:
-
- #
- # == Args
- #
- # +oth+::
- # URI or String
- #
- # == Description
- #
- # Calculates relative path from oth to self
- #
- # == Usage
- #
- # require 'uri'
- #
- # uri = URI.parse('http://my.example.com/main.rbx?page=1')
- # p uri.route_from('http://my.example.com')
- # #=> #<URI::Generic:0x20218858 URL:/main.rbx?page=1>
- #
- def route_from(oth)
- # you can modify `rel', but can not `oth'.
- begin
- oth, rel = route_from0(oth)
- rescue
- raise $!.class, $!.message
- end
- if oth == rel
- return rel
- end
-
- rel.set_path(route_from_path(oth.path, self.path))
- if rel.path == './' && self.query
- # "./?foo" -> "?foo"
- rel.set_path('')
- end
-
- return rel
- end
-
- alias - route_from
-
- #
- # == Args
- #
- # +oth+::
- # URI or String
- #
- # == Description
- #
- # Calculates relative path to oth from self
- #
- # == Usage
- #
- # require 'uri'
- #
- # uri = URI.parse('http://my.example.com')
- # p uri.route_to('http://my.example.com/main.rbx?page=1')
- # #=> #<URI::Generic:0x2020c2f6 URL:/main.rbx?page=1>
- #
- def route_to(oth)
- parser.send(:convert_to_uri, oth).route_from(self)
- end
-
- #
- # Returns normalized URI
- #
- def normalize
- uri = dup
- uri.normalize!
- uri
- end
-
- #
- # Destructive version of #normalize
- #
- def normalize!
- if path && path == ''
- set_path('/')
- end
- if scheme && scheme != scheme.downcase
- set_scheme(self.scheme.downcase)
- end
- if host && host != host.downcase
- set_host(self.host.downcase)
- end
- end
-
- # returns the assemble String with path and query components
- def path_query
- str = @path
- if @query
- str += '?' + @query
- end
- str
- end
- private :path_query
-
- #
- # Constructs String from URI
- #
- def to_s
- str = ''
- if @scheme
- str << @scheme
- str << ':'
- end
-
- if @opaque
- str << @opaque
-
- else
- if @registry
- str << @registry
- else
- if @host
- str << '//'
- end
- if self.userinfo
- str << self.userinfo
- str << '@'
- end
- if @host
- str << @host
- end
- if @port && @port != self.default_port
- str << ':'
- str << @port.to_s
- end
- end
-
- str << path_query
- end
-
- if @fragment
- str << '#'
- str << @fragment
- end
-
- str
- end
-
- #
- # Compares to URI's
- #
- def ==(oth)
- if self.class == oth.class
- self.normalize.component_ary == oth.normalize.component_ary
- else
- false
- end
- end
-
- def hash
- self.component_ary.hash
- end
-
- def eql?(oth)
- self.class == oth.class &&
- parser == oth.parser &&
- self.component_ary.eql?(oth.component_ary)
- end
-
-=begin
-
---- URI::Generic#===(oth)
-
-=end
-# def ===(oth)
-# raise NotImplementedError
-# end
-
-=begin
-=end
-
-
- # returns an Array of the components defined from the COMPONENT Array
- def component_ary
- component.collect do |x|
- self.send(x)
- end
- end
- protected :component_ary
-
- # == Args
- #
- # +components+::
- # Multiple Symbol arguments defined in URI::HTTP
- #
- # == Description
- #
- # Selects specified components from URI
- #
- # == Usage
- #
- # require 'uri'
- #
- # uri = URI.parse('http://myuser:mypass@my.example.com/test.rbx')
- # p uri.select(:userinfo, :host, :path)
- # # => ["myuser:mypass", "my.example.com", "/test.rbx"]
- #
- def select(*components)
- components.collect do |c|
- if component.include?(c)
- self.send(c)
- else
- raise ArgumentError,
- "expected of components of #{self.class} (#{self.class.component.join(', ')})"
- end
- end
- end
-
- @@to_s = Kernel.instance_method(:to_s)
- def inspect
- @@to_s.bind(self).call.sub!(/>\z/) {" URL:#{self}>"}
- end
-
- #
- # == Args
- #
- # +v+::
- # URI or String
- #
- # == Description
- #
- # attempt to parse other URI +oth+
- # return [parsed_oth, self]
- #
- # == Usage
- #
- # require 'uri'
- #
- # uri = URI.parse("http://my.example.com")
- # uri.coerce("http://foo.com")
- # #=> [#<URI::HTTP:0x00000000bcb028 URL:http://foo.com/>, #<URI::HTTP:0x00000000d92178 URL:http://my.example.com>]
- #
- def coerce(oth)
- case oth
- when String
- oth = parser.parse(oth)
- else
- super
- end
-
- return oth, self
- end
- end
-end
diff --git a/ruby_1_9_3/lib/uri/http.rb b/ruby_1_9_3/lib/uri/http.rb
deleted file mode 100644
index 3b03405765..0000000000
--- a/ruby_1_9_3/lib/uri/http.rb
+++ /dev/null
@@ -1,106 +0,0 @@
-# = uri/http.rb
-#
-# Author:: Akira Yamada <akira@ruby-lang.org>
-# License:: You can redistribute it and/or modify it under the same term as Ruby.
-# Revision:: $Id$
-#
-# See URI for general documentation
-#
-
-require 'uri/generic'
-
-module URI
-
- #
- # The syntax of HTTP URIs is defined in RFC1738 section 3.3.
- #
- # Note that the Ruby URI library allows HTTP URLs containing usernames and
- # passwords. This is not legal as per the RFC, but used to be
- # supported in Internet Explorer 5 and 6, before the MS04-004 security
- # update. See <URL:http://support.microsoft.com/kb/834489>.
- #
- class HTTP < Generic
- # A Default port of 80 for URI::HTTP
- DEFAULT_PORT = 80
-
- # An Array of the available components for URI::HTTP
- COMPONENT = [
- :scheme,
- :userinfo, :host, :port,
- :path,
- :query,
- :fragment
- ].freeze
-
- #
- # == Description
- #
- # Create a new URI::HTTP object from components, with syntax checking.
- #
- # The components accepted are userinfo, host, port, path, query and
- # fragment.
- #
- # The components should be provided either as an Array, or as a Hash
- # with keys formed by preceding the component names with a colon.
- #
- # If an Array is used, the components must be passed in the order
- # [userinfo, host, port, path, query, fragment].
- #
- # Example:
- #
- # newuri = URI::HTTP.build({:host => 'www.example.com',
- # :path> => '/foo/bar'})
- #
- # newuri = URI::HTTP.build([nil, "www.example.com", nil, "/path",
- # "query", 'fragment'])
- #
- # Currently, if passed userinfo components this method generates
- # invalid HTTP URIs as per RFC 1738.
- #
- def self.build(args)
- tmp = Util::make_components_hash(self, args)
- return super(tmp)
- end
-
- #
- # == Description
- #
- # Create a new URI::HTTP object from generic URI components as per
- # RFC 2396. No HTTP-specific syntax checking (as per RFC 1738) is
- # performed.
- #
- # Arguments are +scheme+, +userinfo+, +host+, +port+, +registry+, +path+,
- # +opaque+, +query+ and +fragment+, in that order.
- #
- # Example:
- #
- # uri = URI::HTTP.new('http', nil, "www.example.com", nil, "/path",
- # "query", 'fragment')
- #
- #
- # See also URI::Generic.new
- #
- def initialize(*arg)
- super(*arg)
- end
-
- #
- # == Description
- #
- # Returns the full path for an HTTP request, as required by Net::HTTP::Get.
- #
- # If the URI contains a query, the full path is URI#path + '?' + URI#query.
- # Otherwise, the path is simply URI#path.
- #
- def request_uri
- r = path_query
- if r && r[0] != ?/
- r = '/' + r
- end
-
- r
- end
- end
-
- @@schemes['HTTP'] = HTTP
-end
diff --git a/ruby_1_9_3/lib/uri/https.rb b/ruby_1_9_3/lib/uri/https.rb
deleted file mode 100644
index 7d242e7e79..0000000000
--- a/ruby_1_9_3/lib/uri/https.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-# = uri/https.rb
-#
-# Author:: Akira Yamada <akira@ruby-lang.org>
-# License:: You can redistribute it and/or modify it under the same term as Ruby.
-# Revision:: $Id$
-#
-# See URI for general documentation
-#
-
-require 'uri/http'
-
-module URI
-
- # The default port for HTTPS URIs is 443, and the scheme is 'https:' rather
- # than 'http:'. Other than that, HTTPS URIs are identical to HTTP URIs;
- # see URI::HTTP.
- class HTTPS < HTTP
- # A Default port of 443 for URI::HTTPS
- DEFAULT_PORT = 443
- end
- @@schemes['HTTPS'] = HTTPS
-end
diff --git a/ruby_1_9_3/lib/uri/ldap.rb b/ruby_1_9_3/lib/uri/ldap.rb
deleted file mode 100644
index 56d748e59e..0000000000
--- a/ruby_1_9_3/lib/uri/ldap.rb
+++ /dev/null
@@ -1,260 +0,0 @@
-# = uri/ldap.rb
-#
-# Author::
-# Takaaki Tateishi <ttate@jaist.ac.jp>
-# Akira Yamada <akira@ruby-lang.org>
-# License::
-# URI::LDAP is copyrighted free software by Takaaki Tateishi and Akira Yamada.
-# You can redistribute it and/or modify it under the same term as Ruby.
-# Revision:: $Id$
-#
-# See URI for general documentation
-#
-
-require 'uri/generic'
-
-module URI
-
- #
- # LDAP URI SCHEMA (described in RFC2255)
- # ldap://<host>/<dn>[?<attrs>[?<scope>[?<filter>[?<extensions>]]]]
- #
- class LDAP < Generic
-
- # A Default port of 389 for URI::LDAP
- DEFAULT_PORT = 389
-
- # An Array of the available components for URI::LDAP
- COMPONENT = [
- :scheme,
- :host, :port,
- :dn,
- :attributes,
- :scope,
- :filter,
- :extensions,
- ].freeze
-
- # Scopes available for the starting point.
- #
- # * SCOPE_BASE - the Base DN
- # * SCOPE_ONE - one level under the Base DN, not including the base DN and
- # not including any entries under this.
- # * SCOPE_SUB - subtress, all entries at all levels
- #
- SCOPE = [
- SCOPE_ONE = 'one',
- SCOPE_SUB = 'sub',
- SCOPE_BASE = 'base',
- ].freeze
-
- #
- # == Description
- #
- # Create a new URI::LDAP object from components, with syntax checking.
- #
- # The components accepted are host, port, dn, attributes,
- # scope, filter, and extensions.
- #
- # The components should be provided either as an Array, or as a Hash
- # with keys formed by preceding the component names with a colon.
- #
- # If an Array is used, the components must be passed in the order
- # [host, port, dn, attributes, scope, filter, extensions].
- #
- # Example:
- #
- # newuri = URI::LDAP.build({:host => 'ldap.example.com',
- # :dn> => '/dc=example'})
- #
- # newuri = URI::LDAP.build(["ldap.example.com", nil,
- # "/dc=example;dc=com", "query", nil, nil, nil])
- #
- def self.build(args)
- tmp = Util::make_components_hash(self, args)
-
- if tmp[:dn]
- tmp[:path] = tmp[:dn]
- end
-
- query = []
- [:extensions, :filter, :scope, :attributes].collect do |x|
- next if !tmp[x] && query.size == 0
- query.unshift(tmp[x])
- end
-
- tmp[:query] = query.join('?')
-
- return super(tmp)
- end
-
- #
- # == Description
- #
- # Create a new URI::LDAP object from generic URI components as per
- # RFC 2396. No LDAP-specific syntax checking is performed.
- #
- # Arguments are +scheme+, +userinfo+, +host+, +port+, +registry+, +path+,
- # +opaque+, +query+ and +fragment+, in that order.
- #
- # Example:
- #
- # uri = URI::LDAP.new("ldap", nil, "ldap.example.com", nil,
- # "/dc=example;dc=com", "query", nil, nil, nil, nil)
- #
- #
- # See also URI::Generic.new
- #
- def initialize(*arg)
- super(*arg)
-
- if @fragment
- raise InvalidURIError, 'bad LDAP URL'
- end
-
- parse_dn
- parse_query
- end
-
- # private method to cleanup +dn+ from using the +path+ component attribute
- def parse_dn
- @dn = @path[1..-1]
- end
- private :parse_dn
-
- # private method to cleanup +attributes+, +scope+, +filter+ and +extensions+,
- # from using the +query+ component attribute
- def parse_query
- @attributes = nil
- @scope = nil
- @filter = nil
- @extensions = nil
-
- if @query
- attrs, scope, filter, extensions = @query.split('?')
-
- @attributes = attrs if attrs && attrs.size > 0
- @scope = scope if scope && scope.size > 0
- @filter = filter if filter && filter.size > 0
- @extensions = extensions if extensions && extensions.size > 0
- end
- end
- private :parse_query
-
- # private method to assemble +query+ from +attributes+, +scope+, +filter+ and +extensions+.
- def build_path_query
- @path = '/' + @dn
-
- query = []
- [@extensions, @filter, @scope, @attributes].each do |x|
- next if !x && query.size == 0
- query.unshift(x)
- end
- @query = query.join('?')
- end
- private :build_path_query
-
- # returns dn.
- def dn
- @dn
- end
-
- # private setter for dn +val+
- def set_dn(val)
- @dn = val
- build_path_query
- @dn
- end
- protected :set_dn
-
- # setter for dn +val+
- def dn=(val)
- set_dn(val)
- val
- end
-
- # returns attributes.
- def attributes
- @attributes
- end
-
- # private setter for attributes +val+
- def set_attributes(val)
- @attributes = val
- build_path_query
- @attributes
- end
- protected :set_attributes
-
- # setter for attributes +val+
- def attributes=(val)
- set_attributes(val)
- val
- end
-
- # returns scope.
- def scope
- @scope
- end
-
- # private setter for scope +val+
- def set_scope(val)
- @scope = val
- build_path_query
- @scope
- end
- protected :set_scope
-
- # setter for scope +val+
- def scope=(val)
- set_scope(val)
- val
- end
-
- # returns filter.
- def filter
- @filter
- end
-
- # private setter for filter +val+
- def set_filter(val)
- @filter = val
- build_path_query
- @filter
- end
- protected :set_filter
-
- # setter for filter +val+
- def filter=(val)
- set_filter(val)
- val
- end
-
- # returns extensions.
- def extensions
- @extensions
- end
-
- # private setter for extensions +val+
- def set_extensions(val)
- @extensions = val
- build_path_query
- @extensions
- end
- protected :set_extensions
-
- # setter for extensions +val+
- def extensions=(val)
- set_extensions(val)
- val
- end
-
- # Checks if URI has a path
- # For URI::LDAP this will return +false+
- def hierarchical?
- false
- end
- end
-
- @@schemes['LDAP'] = LDAP
-end
diff --git a/ruby_1_9_3/lib/uri/ldaps.rb b/ruby_1_9_3/lib/uri/ldaps.rb
deleted file mode 100644
index 42bbfe86ba..0000000000
--- a/ruby_1_9_3/lib/uri/ldaps.rb
+++ /dev/null
@@ -1,20 +0,0 @@
-# = uri/ldap.rb
-#
-# License:: You can redistribute it and/or modify it under the same term as Ruby.
-#
-# See URI for general documentation
-#
-
-require 'uri/ldap'
-
-module URI
-
- # The default port for LDAPS URIs is 636, and the scheme is 'ldaps:' rather
- # than 'ldap:'. Other than that, LDAPS URIs are identical to LDAP URIs;
- # see URI::LDAP.
- class LDAPS < LDAP
- # A Default port of 636 for URI::LDAPS
- DEFAULT_PORT = 636
- end
- @@schemes['LDAPS'] = LDAPS
-end
diff --git a/ruby_1_9_3/lib/uri/mailto.rb b/ruby_1_9_3/lib/uri/mailto.rb
deleted file mode 100644
index 765528fb7f..0000000000
--- a/ruby_1_9_3/lib/uri/mailto.rb
+++ /dev/null
@@ -1,280 +0,0 @@
-# = uri/mailto.rb
-#
-# Author:: Akira Yamada <akira@ruby-lang.org>
-# License:: You can redistribute it and/or modify it under the same term as Ruby.
-# Revision:: $Id$
-#
-# See URI for general documentation
-#
-
-require 'uri/generic'
-
-module URI
-
- #
- # RFC2368, The mailto URL scheme
- #
- class MailTo < Generic
- include REGEXP
-
- # A Default port of nil for URI::MailTo
- DEFAULT_PORT = nil
-
- # An Array of the available components for URI::MailTo
- COMPONENT = [ :scheme, :to, :headers ].freeze
-
- # :stopdoc:
- # "hname" and "hvalue" are encodings of an RFC 822 header name and
- # value, respectively. As with "to", all URL reserved characters must
- # be encoded.
- #
- # "#mailbox" is as specified in RFC 822 [RFC822]. This means that it
- # consists of zero or more comma-separated mail addresses, possibly
- # including "phrase" and "comment" components. Note that all URL
- # reserved characters in "to" must be encoded: in particular,
- # parentheses, commas, and the percent sign ("%"), which commonly occur
- # in the "mailbox" syntax.
- #
- # Within mailto URLs, the characters "?", "=", "&" are reserved.
-
- # hname = *urlc
- # hvalue = *urlc
- # header = hname "=" hvalue
- HEADER_PATTERN = "(?:[^?=&]*=[^?=&]*)".freeze
- HEADER_REGEXP = Regexp.new(HEADER_PATTERN).freeze
- # headers = "?" header *( "&" header )
- # to = #mailbox
- # mailtoURL = "mailto:" [ to ] [ headers ]
- MAILBOX_PATTERN = "(?:#{PATTERN::ESCAPED}|[^(),%?=&])".freeze
- MAILTO_REGEXP = Regexp.new(" # :nodoc:
- \\A
- (#{MAILBOX_PATTERN}*?) (?# 1: to)
- (?:
- \\?
- (#{HEADER_PATTERN}(?:\\&#{HEADER_PATTERN})*) (?# 2: headers)
- )?
- (?:
- \\#
- (#{PATTERN::FRAGMENT}) (?# 3: fragment)
- )?
- \\z
- ", Regexp::EXTENDED).freeze
- # :startdoc:
-
- #
- # == Description
- #
- # Creates a new URI::MailTo object from components, with syntax checking.
- #
- # Components can be provided as an Array or Hash. If an Array is used,
- # the components must be supplied as [to, headers].
- #
- # If a Hash is used, the keys are the component names preceded by colons.
- #
- # The headers can be supplied as a pre-encoded string, such as
- # "subject=subscribe&cc=address", or as an Array of Arrays like
- # [['subject', 'subscribe'], ['cc', 'address']]
- #
- # Examples:
- #
- # require 'uri'
- #
- # m1 = URI::MailTo.build(['joe@example.com', 'subject=Ruby'])
- # puts m1.to_s -> mailto:joe@example.com?subject=Ruby
- #
- # m2 = URI::MailTo.build(['john@example.com', [['Subject', 'Ruby'], ['Cc', 'jack@example.com']]])
- # puts m2.to_s -> mailto:john@example.com?Subject=Ruby&Cc=jack@example.com
- #
- # m3 = URI::MailTo.build({:to => 'listman@example.com', :headers => [['subject', 'subscribe']]})
- # puts m3.to_s -> mailto:listman@example.com?subject=subscribe
- #
- def self.build(args)
- tmp = Util::make_components_hash(self, args)
-
- if tmp[:to]
- tmp[:opaque] = tmp[:to]
- else
- tmp[:opaque] = ''
- end
-
- if tmp[:headers]
- tmp[:opaque] << '?'
-
- if tmp[:headers].kind_of?(Array)
- tmp[:opaque] << tmp[:headers].collect { |x|
- if x.kind_of?(Array)
- x[0] + '=' + x[1..-1].to_s
- else
- x.to_s
- end
- }.join('&')
-
- elsif tmp[:headers].kind_of?(Hash)
- tmp[:opaque] << tmp[:headers].collect { |h,v|
- h + '=' + v
- }.join('&')
-
- else
- tmp[:opaque] << tmp[:headers].to_s
- end
- end
-
- return super(tmp)
- end
-
- #
- # == Description
- #
- # Creates a new URI::MailTo object from generic URL components with
- # no syntax checking.
- #
- # This method is usually called from URI::parse, which checks
- # the validity of each component.
- #
- def initialize(*arg)
- super(*arg)
-
- @to = nil
- @headers = []
-
- if MAILTO_REGEXP =~ @opaque
- if arg[-1]
- self.to = $1
- self.headers = $2
- else
- set_to($1)
- set_headers($2)
- end
-
- else
- raise InvalidComponentError,
- "unrecognised opaque part for mailtoURL: #{@opaque}"
- end
- end
-
- # The primary e-mail address of the URL, as a String
- attr_reader :to
-
- # E-mail headers set by the URL, as an Array of Arrays
- attr_reader :headers
-
- # check the to +v+ component against either
- # * URI::Parser Regexp for :OPAQUE
- # * MAILBOX_PATTERN
- def check_to(v)
- return true unless v
- return true if v.size == 0
-
- if parser.regexp[:OPAQUE] !~ v || /\A#{MAILBOX_PATTERN}*\z/o !~ v
- raise InvalidComponentError,
- "bad component(expected opaque component): #{v}"
- end
-
- return true
- end
- private :check_to
-
- # private setter for to +v+
- def set_to(v)
- @to = v
- end
- protected :set_to
-
- # setter for to +v+
- def to=(v)
- check_to(v)
- set_to(v)
- v
- end
-
- # check the headers +v+ component against either
- # * URI::Parser Regexp for :OPAQUE
- # * HEADER_PATTERN
- def check_headers(v)
- return true unless v
- return true if v.size == 0
-
- if parser.regexp[:OPAQUE] !~ v ||
- /\A(#{HEADER_PATTERN}(?:\&#{HEADER_PATTERN})*)\z/o !~ v
- raise InvalidComponentError,
- "bad component(expected opaque component): #{v}"
- end
-
- return true
- end
- private :check_headers
-
- # private setter for headers +v+
- def set_headers(v)
- @headers = []
- if v
- v.scan(HEADER_REGEXP) do |x|
- @headers << x.split(/=/o, 2)
- end
- end
- end
- protected :set_headers
-
- # setter for headers +v+
- def headers=(v)
- check_headers(v)
- set_headers(v)
- v
- end
-
- # Constructs String from URI
- def to_s
- @scheme + ':' +
- if @to
- @to
- else
- ''
- end +
- if @headers.size > 0
- '?' + @headers.collect{|x| x.join('=')}.join('&')
- else
- ''
- end +
- if @fragment
- '#' + @fragment
- else
- ''
- end
- end
-
- # Returns the RFC822 e-mail text equivalent of the URL, as a String.
- #
- # Example:
- #
- # require 'uri'
- #
- # uri = URI.parse("mailto:ruby-list@ruby-lang.org?Subject=subscribe&cc=myaddr")
- # uri.to_mailtext
- # # => "To: ruby-list@ruby-lang.org\nSubject: subscribe\nCc: myaddr\n\n\n"
- #
- def to_mailtext
- to = parser.unescape(@to)
- head = ''
- body = ''
- @headers.each do |x|
- case x[0]
- when 'body'
- body = parser.unescape(x[1])
- when 'to'
- to << ', ' + parser.unescape(x[1])
- else
- head << parser.unescape(x[0]).capitalize + ': ' +
- parser.unescape(x[1]) + "\n"
- end
- end
-
- return "To: #{to}
-#{head}
-#{body}
-"
- end
- alias to_rfc822text to_mailtext
- end
-
- @@schemes['MAILTO'] = MailTo
-end
diff --git a/ruby_1_9_3/lib/weakref.rb b/ruby_1_9_3/lib/weakref.rb
deleted file mode 100644
index ee5444a584..0000000000
--- a/ruby_1_9_3/lib/weakref.rb
+++ /dev/null
@@ -1,94 +0,0 @@
-require "delegate"
-require 'thread'
-
-# Weak Reference class that allows a referenced object to be
-# garbage-collected. A WeakRef may be used exactly like the object it
-# references.
-#
-# Usage:
-#
-# foo = Object.new
-# foo = Object.new
-# p foo.to_s # original's class
-# foo = WeakRef.new(foo)
-# p foo.to_s # should be same class
-# ObjectSpace.garbage_collect
-# p foo.to_s # should raise exception (recycled)
-
-class WeakRef < Delegator
-
- ##
- # RefError is raised when a referenced object has been recycled by the
- # garbage collector
-
- class RefError < StandardError
- end
-
- @@id_map = {} # obj -> [ref,...]
- @@id_rev_map = {} # ref -> obj
- @@mutex = Mutex.new
- @@final = lambda {|id|
- @@mutex.synchronize {
- rids = @@id_map[id]
- if rids
- for rid in rids
- @@id_rev_map.delete(rid)
- end
- @@id_map.delete(id)
- end
- rid = @@id_rev_map[id]
- if rid
- @@id_rev_map.delete(id)
- @@id_map[rid].delete(id)
- @@id_map.delete(rid) if @@id_map[rid].empty?
- end
- }
- }
-
- ##
- # Creates a weak reference to +orig+
-
- def initialize(orig)
- @__id = orig.object_id
- ObjectSpace.define_finalizer orig, @@final
- ObjectSpace.define_finalizer self, @@final
- @@mutex.synchronize {
- @@id_map[@__id] = [] unless @@id_map[@__id]
- }
- @@id_map[@__id].push self.object_id
- @@id_rev_map[self.object_id] = @__id
- super
- end
-
- def __getobj__ # :nodoc:
- unless @@id_rev_map[self.object_id] == @__id
- Kernel::raise RefError, "Invalid Reference - probably recycled", Kernel::caller(2)
- end
- begin
- ObjectSpace._id2ref(@__id)
- rescue RangeError
- Kernel::raise RefError, "Invalid Reference - probably recycled", Kernel::caller(2)
- end
- end
-
- def __setobj__(obj) # :nodoc:
- end
-
- ##
- # Returns true if the referenced object is still alive.
-
- def weakref_alive?
- @@id_rev_map[self.object_id] == @__id
- end
-end
-
-if __FILE__ == $0
-# require 'thread'
- foo = Object.new
- p foo.to_s # original's class
- foo = WeakRef.new(foo)
- p foo.to_s # should be same class
- ObjectSpace.garbage_collect
- ObjectSpace.garbage_collect
- p foo.to_s # should raise exception (recycled)
-end
diff --git a/ruby_1_9_3/lib/webrick.rb b/ruby_1_9_3/lib/webrick.rb
deleted file mode 100644
index 842bda21ef..0000000000
--- a/ruby_1_9_3/lib/webrick.rb
+++ /dev/null
@@ -1,227 +0,0 @@
-##
-# = WEB server toolkit.
-#
-# WEBrick is an HTTP server toolkit that can be configured as an HTTPS server,
-# a proxy server, and a virtual-host server. WEBrick features complete
-# logging of both server operations and HTTP access. WEBrick supports both
-# basic and digest authentication in addition to algorithms not in RFC 2617.
-#
-# A WEBrick servers can be composed of multiple WEBrick servers or servlets to
-# provide differing behavior on a per-host or per-path basis. WEBrick
-# includes servlets for handling CGI scripts, ERb pages, ruby blocks and
-# directory listings.
-#
-# WEBrick also includes tools for daemonizing a process and starting a process
-# at a higher privilege level and dropping permissions.
-#
-# == Starting an HTTP server
-#
-# To create a new WEBrick::HTTPServer that will listen to connections on port
-# 8000 and serve documents from the current user's public_html folder:
-#
-# require 'webrick'
-#
-# root = File.expand_path '~/public_html'
-# server = WEBrick::HTTPServer.new :Port => 8000, :DocumentRoot => root
-#
-# To run the server you will need to provide a suitable shutdown hook as
-# starting the server blocks the current thread:
-#
-# trap 'INT' do server.shutdown end
-#
-# server.start
-#
-# == Custom Behavior
-#
-# The easiest way to have a server perform custom operations is through
-# WEBrick::HTTPServer#mount_proc. The block given will be called with a
-# WEBrick::HTTPRequest with request info and a WEBrick::HTTPResponse which
-# must be filled in appropriately:
-#
-# server.mount_proc '/' do |req, res|
-# res.body = 'Hello, world!'
-# end
-#
-# Remember that <tt>server.mount_proc</tt> must <tt>server.start</tt>.
-#
-# == Servlets
-#
-# Advanced custom behavior can be obtained through mounting a subclass of
-# WEBrick::HTTPServlet::AbstractServlet. Servlets provide more modularity
-# when writing an HTTP server than mount_proc allows. Here is a simple
-# servlet:
-#
-# class Simple < WEBrick::HTTPServlet::AbstractServlet
-# def do_GET request, response
-# status, content_type, body = do_stuff_with request
-#
-# response.status = 200
-# response['Content-Type'] = 'text/plain'
-# response.body = 'Hello, World!'
-# end
-# end
-#
-# To initialize the servlet you mount it on the server:
-#
-# server.mount '/simple', Simple
-#
-# See WEBrick::HTTPServlet::AbstractServlet for more details.
-#
-# == Virtual Hosts
-#
-# A server can act as a virtual host for multiple host names. After creating
-# the listening host, additional hosts that do not listen can be created and
-# attached as virtual hosts:
-#
-# server = WEBrick::HTTPServer.new # ...
-#
-# vhost = WEBrick::HTTPServer.new :ServerName => 'vhost.example',
-# :DoNotListen => true, # ...
-# vhost.mount '/', ...
-#
-# server.virtual_host vhost
-#
-# If no +:DocumentRoot+ is provided and no servlets or procs are mounted on the
-# main server it will return 404 for all URLs.
-#
-# == HTTPS
-#
-# To create an HTTPS server you only need to enable SSL and provide an SSL
-# certificate name:
-#
-# require 'webrick'
-# require 'webrick/https'
-#
-# cert_name = [
-# %w[CN localhost],
-# ]
-#
-# server = WEBrick::HTTPServer.new(:Port => 8000,
-# :SSLEnable => true,
-# :SSLCertName => cert_name)
-#
-# This will start the server with a self-generated self-signed certificate.
-# The certificate will be changed every time the server is restarted.
-#
-# To create a server with a pre-determined key and certificate you can provide
-# them:
-#
-# require 'webrick'
-# require 'webrick/https'
-# require 'openssl'
-#
-# cert = OpenSSL::X509::Certificate.new File.read '/path/to/cert.pem'
-# pkey = OpenSSL::PKey::RSA.new File.read '/path/to/pkey.pem'
-#
-# server = WEBrick::HTTPServer.new(:Port => 8000,
-# :SSLEnable => true,
-# :SSLCertificate => cert,
-# :SSLPrivateKey => pkey)
-#
-# == Proxy Server
-#
-# WEBrick can act as a proxy server:
-#
-# require 'webrick'
-# require 'webrick/httpproxy'
-#
-# proxy = WEBrick::HTTPProxyServer.new :Port => 8000
-#
-# trap 'INT' do proxy.shutdown end
-#
-# Proxies may modifier the content of the response through the
-# +:ProxyContentHandler+ callback which will be invoked with the request and
-# respone after the remote content has been fetched.
-#
-# == Basic and Digest authentication
-#
-# WEBrick provides both Basic and Digest authentication for regular and proxy
-# servers. See WEBrick::HTTPAuth, WEBrick::HTTPAuth::BasicAuth and
-# WEBrick::HTTPAuth::DigestAuth.
-#
-# == WEBrick as a Production Web Server
-#
-# WEBrick can be run as a production server for small loads.
-#
-# === Daemonizing
-#
-# To start a WEBrick server as a daemon simple run WEBrick::Daemon.start
-# before starting the server.
-#
-# === Dropping Permissions
-#
-# WEBrick can be started as one user to gain permission to bind to port 80 or
-# 443 for serving HTTP or HTTPS traffic then can drop these permissions for
-# regular operation. To listen on all interfaces for HTTP traffic:
-#
-# sockets = WEBrick::Utils.create_listeners nil, 80
-#
-# Then drop privileges:
-#
-# WEBrick::Utils.su 'www'
-#
-# Then create a server that does not listen by default:
-#
-# server = WEBrick::HTTPServer.new :DoNotListen => true, # ...
-#
-# Then overwrite the listening sockets with the port 80 sockets:
-#
-# server.listeners.replace sockets
-#
-# === Logging
-#
-# WEBrick can separately log server operations and end-user access. For
-# server operations:
-#
-# log_file = File.open '/var/log/webrick.log', 'a+'
-# log = WEBrick::Log.new log_file
-#
-# For user access logging:
-#
-# access_log = [
-# [log_file, WEBrick::AccessLog::COMBINED_LOG_FORMAT],
-# ]
-#
-# server = WEBrick::HTTPServer.new :Logger => log, :AccessLog => access_log
-#
-# See WEBrick::AccessLog for further log formats.
-#
-# === Log Rotation
-#
-# To rotate logs in WEBrick on a HUP signal (like syslogd can send), open the
-# log file in 'a+' mode (as above) and trap 'HUP' to reopen the log file:
-#
-# trap 'HUP' do log_file.reopen '/path/to/webrick.log', 'a+'
-#
-# == Copyright
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-#
-# Copyright (c) 2000 TAKAHASHI Masayoshi, GOTOU YUUZOU
-# Copyright (c) 2002 Internet Programming with Ruby writers. All rights
-# reserved.
-#--
-# $IPR: webrick.rb,v 1.12 2002/10/01 17:16:31 gotoyuzo Exp $
-
-module WEBrick
-end
-
-require 'webrick/compat.rb'
-
-require 'webrick/version.rb'
-require 'webrick/config.rb'
-require 'webrick/log.rb'
-require 'webrick/server.rb'
-require 'webrick/utils.rb'
-require 'webrick/accesslog'
-
-require 'webrick/htmlutils.rb'
-require 'webrick/httputils.rb'
-require 'webrick/cookie.rb'
-require 'webrick/httpversion.rb'
-require 'webrick/httpstatus.rb'
-require 'webrick/httprequest.rb'
-require 'webrick/httpresponse.rb'
-require 'webrick/httpserver.rb'
-require 'webrick/httpservlet.rb'
-require 'webrick/httpauth.rb'
diff --git a/ruby_1_9_3/lib/webrick/accesslog.rb b/ruby_1_9_3/lib/webrick/accesslog.rb
deleted file mode 100644
index 029b5a4902..0000000000
--- a/ruby_1_9_3/lib/webrick/accesslog.rb
+++ /dev/null
@@ -1,151 +0,0 @@
-#--
-# accesslog.rb -- Access log handling utilities
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2002 keita yamaguchi
-# Copyright (c) 2002 Internet Programming with Ruby writers
-#
-# $IPR: accesslog.rb,v 1.1 2002/10/01 17:16:32 gotoyuzo Exp $
-
-module WEBrick
-
- ##
- # AccessLog provides logging to various files in various formats.
- #
- # Multiple logs may be written to at the same time:
- #
- # access_log = [
- # [$stderr, WEBrick::AccessLog::COMMON_LOG_FORMAT],
- # [$stderr, WEBrick::AccessLog::REFERER_LOG_FORMAT],
- # ]
- #
- # server = WEBrick::HTTPServer.new :AccessLog => access_log
- #
- # Custom log formats may be defined. WEBrick::AccessLog provides a subset
- # of the formatting from Apache's mod_log_config
- # http://httpd.apache.org/docs/mod/mod_log_config.html#formats. See
- # AccessLog::setup_params for a list of supported options
-
- module AccessLog
-
- ##
- # Raised if a parameter such as %e, %i, %o or %n is used without fetching
- # a specific field.
-
- class AccessLogError < StandardError; end
-
- ##
- # The Common Log Format's time format
-
- CLF_TIME_FORMAT = "[%d/%b/%Y:%H:%M:%S %Z]"
-
- ##
- # Common Log Format
-
- COMMON_LOG_FORMAT = "%h %l %u %t \"%r\" %s %b"
-
- ##
- # Short alias for Common Log Format
-
- CLF = COMMON_LOG_FORMAT
-
- ##
- # Referer Log Format
-
- REFERER_LOG_FORMAT = "%{Referer}i -> %U"
-
- ##
- # User-Agent Log Format
-
- AGENT_LOG_FORMAT = "%{User-Agent}i"
-
- ##
- # Combined Log Format
-
- COMBINED_LOG_FORMAT = "#{CLF} \"%{Referer}i\" \"%{User-agent}i\""
-
- module_function
-
- # This format specification is a subset of mod_log_config of Apache:
- #
- # %a:: Remote IP address
- # %b:: Total response size
- # %e{variable}:: Given variable in ENV
- # %f:: Response filename
- # %h:: Remote host name
- # %{header}i:: Given request header
- # %l:: Remote logname, always "-"
- # %m:: Request method
- # %{attr}n:: Given request attribute from <tt>req.attributes</tt>
- # %{header}o:: Given response header
- # %p:: Server's request port
- # %{format}p:: The canonical port of the server serving the request or the
- # actual port or the client's actual port. Valid formats are
- # canonical, local or remote.
- # %q:: Request query string
- # %r:: First line of the request
- # %s:: Request status
- # %t:: Time the request was recieved
- # %T:: Time taken to process the request
- # %u:: Remote user from auth
- # %U:: Unparsed URI
- # %%:: Literal %
-
- def setup_params(config, req, res)
- params = Hash.new("")
- params["a"] = req.peeraddr[3]
- params["b"] = res.sent_size
- params["e"] = ENV
- params["f"] = res.filename || ""
- params["h"] = req.peeraddr[2]
- params["i"] = req
- params["l"] = "-"
- params["m"] = req.request_method
- params["n"] = req.attributes
- params["o"] = res
- params["p"] = req.port
- params["q"] = req.query_string
- params["r"] = req.request_line.sub(/\x0d?\x0a\z/o, '')
- params["s"] = res.status # won't support "%>s"
- params["t"] = req.request_time
- params["T"] = Time.now - req.request_time
- params["u"] = req.user || "-"
- params["U"] = req.unparsed_uri
- params["v"] = config[:ServerName]
- params
- end
-
- def format(format_string, params)
- format_string.gsub(/\%(?:\{(.*?)\})?>?([a-zA-Z%])/){
- param, spec = $1, $2
- case spec[0]
- when ?e, ?i, ?n, ?o
- raise AccessLogError,
- "parameter is required for \"#{spec}\"" unless param
- (param = params[spec][param]) ? escape(param) : "-"
- when ?t
- params[spec].strftime(param || CLF_TIME_FORMAT)
- when ?p
- case param
- when 'remote'
- escape(params["i"].peeraddr[1].to_s)
- else
- escape(params["p"].to_s)
- end
- when ?%
- "%"
- else
- escape(params[spec].to_s)
- end
- }
- end
-
- def escape(data)
- if data.tainted?
- data.gsub(/[[:cntrl:]\\]+/) {$&.dump[1...-1]}.untaint
- else
- data
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/cgi.rb b/ruby_1_9_3/lib/webrick/cgi.rb
deleted file mode 100644
index 806d050bc9..0000000000
--- a/ruby_1_9_3/lib/webrick/cgi.rb
+++ /dev/null
@@ -1,260 +0,0 @@
-#
-# cgi.rb -- Yet another CGI library
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2003 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $Id$
-
-require "webrick/httprequest"
-require "webrick/httpresponse"
-require "webrick/config"
-require "stringio"
-
-module WEBrick
- class CGI
- CGIError = Class.new(StandardError)
-
- attr_reader :config, :logger
-
- def initialize(*args)
- if defined?(MOD_RUBY)
- unless ENV.has_key?("GATEWAY_INTERFACE")
- Apache.request.setup_cgi_env
- end
- end
- if %r{HTTP/(\d+\.\d+)} =~ ENV["SERVER_PROTOCOL"]
- httpv = $1
- end
- @config = WEBrick::Config::HTTP.dup.update(
- :ServerSoftware => ENV["SERVER_SOFTWARE"] || "null",
- :HTTPVersion => HTTPVersion.new(httpv || "1.0"),
- :RunOnCGI => true, # to detect if it runs on CGI.
- :NPH => false # set true to run as NPH script.
- )
- if config = args.shift
- @config.update(config)
- end
- @config[:Logger] ||= WEBrick::BasicLog.new($stderr)
- @logger = @config[:Logger]
- @options = args
- end
-
- def [](key)
- @config[key]
- end
-
- def start(env=ENV, stdin=$stdin, stdout=$stdout)
- sock = WEBrick::CGI::Socket.new(@config, env, stdin, stdout)
- req = HTTPRequest.new(@config)
- res = HTTPResponse.new(@config)
- unless @config[:NPH] or defined?(MOD_RUBY)
- def res.setup_header
- unless @header["status"]
- phrase = HTTPStatus::reason_phrase(@status)
- @header["status"] = "#{@status} #{phrase}"
- end
- super
- end
- def res.status_line
- ""
- end
- end
-
- begin
- req.parse(sock)
- req.script_name = (env["SCRIPT_NAME"] || File.expand_path($0)).dup
- req.path_info = (env["PATH_INFO"] || "").dup
- req.query_string = env["QUERY_STRING"]
- req.user = env["REMOTE_USER"]
- res.request_method = req.request_method
- res.request_uri = req.request_uri
- res.request_http_version = req.http_version
- res.keep_alive = req.keep_alive?
- self.service(req, res)
- rescue HTTPStatus::Error => ex
- res.set_error(ex)
- rescue HTTPStatus::Status => ex
- res.status = ex.code
- rescue Exception => ex
- @logger.error(ex)
- res.set_error(ex, true)
- ensure
- req.fixup
- if defined?(MOD_RUBY)
- res.setup_header
- Apache.request.status_line = "#{res.status} #{res.reason_phrase}"
- Apache.request.status = res.status
- table = Apache.request.headers_out
- res.header.each{|key, val|
- case key
- when /^content-encoding$/i
- Apache::request.content_encoding = val
- when /^content-type$/i
- Apache::request.content_type = val
- else
- table[key] = val.to_s
- end
- }
- res.cookies.each{|cookie|
- table.add("Set-Cookie", cookie.to_s)
- }
- Apache.request.send_http_header
- res.send_body(sock)
- else
- res.send_response(sock)
- end
- end
- end
-
- def service(req, res)
- method_name = "do_" + req.request_method.gsub(/-/, "_")
- if respond_to?(method_name)
- __send__(method_name, req, res)
- else
- raise HTTPStatus::MethodNotAllowed,
- "unsupported method `#{req.request_method}'."
- end
- end
-
- class Socket
- include Enumerable
-
- private
-
- def initialize(config, env, stdin, stdout)
- @config = config
- @env = env
- @header_part = StringIO.new
- @body_part = stdin
- @out_port = stdout
- @out_port.binmode
-
- @server_addr = @env["SERVER_ADDR"] || "0.0.0.0"
- @server_name = @env["SERVER_NAME"]
- @server_port = @env["SERVER_PORT"]
- @remote_addr = @env["REMOTE_ADDR"]
- @remote_host = @env["REMOTE_HOST"] || @remote_addr
- @remote_port = @env["REMOTE_PORT"] || 0
-
- begin
- @header_part << request_line << CRLF
- setup_header
- @header_part << CRLF
- @header_part.rewind
- rescue Exception
- raise CGIError, "invalid CGI environment"
- end
- end
-
- def request_line
- meth = @env["REQUEST_METHOD"] || "GET"
- unless url = @env["REQUEST_URI"]
- url = (@env["SCRIPT_NAME"] || File.expand_path($0)).dup
- url << @env["PATH_INFO"].to_s
- url = WEBrick::HTTPUtils.escape_path(url)
- if query_string = @env["QUERY_STRING"]
- unless query_string.empty?
- url << "?" << query_string
- end
- end
- end
- # we cannot get real HTTP version of client ;)
- httpv = @config[:HTTPVersion]
- return "#{meth} #{url} HTTP/#{httpv}"
- end
-
- def setup_header
- @env.each{|key, value|
- case key
- when "CONTENT_TYPE", "CONTENT_LENGTH"
- add_header(key.gsub(/_/, "-"), value)
- when /^HTTP_(.*)/
- add_header($1.gsub(/_/, "-"), value)
- end
- }
- end
-
- def add_header(hdrname, value)
- unless value.empty?
- @header_part << hdrname << ": " << value << CRLF
- end
- end
-
- def input
- @header_part.eof? ? @body_part : @header_part
- end
-
- public
-
- def peeraddr
- [nil, @remote_port, @remote_host, @remote_addr]
- end
-
- def addr
- [nil, @server_port, @server_name, @server_addr]
- end
-
- def gets(eol=LF, size=nil)
- input.gets(eol, size)
- end
-
- def read(size=nil)
- input.read(size)
- end
-
- def each
- input.each{|line| yield(line) }
- end
-
- def eof?
- input.eof?
- end
-
- def <<(data)
- @out_port << data
- end
-
- def cert
- return nil unless defined?(OpenSSL)
- if pem = @env["SSL_SERVER_CERT"]
- OpenSSL::X509::Certificate.new(pem) unless pem.empty?
- end
- end
-
- def peer_cert
- return nil unless defined?(OpenSSL)
- if pem = @env["SSL_CLIENT_CERT"]
- OpenSSL::X509::Certificate.new(pem) unless pem.empty?
- end
- end
-
- def peer_cert_chain
- return nil unless defined?(OpenSSL)
- if @env["SSL_CLIENT_CERT_CHAIN_0"]
- keys = @env.keys
- certs = keys.sort.collect{|k|
- if /^SSL_CLIENT_CERT_CHAIN_\d+$/ =~ k
- if pem = @env[k]
- OpenSSL::X509::Certificate.new(pem) unless pem.empty?
- end
- end
- }
- certs.compact
- end
- end
-
- def cipher
- return nil unless defined?(OpenSSL)
- if cipher = @env["SSL_CIPHER"]
- ret = [ cipher ]
- ret << @env["SSL_PROTOCOL"]
- ret << @env["SSL_CIPHER_USEKEYSIZE"]
- ret << @env["SSL_CIPHER_ALGKEYSIZE"]
- ret
- end
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/compat.rb b/ruby_1_9_3/lib/webrick/compat.rb
deleted file mode 100644
index 33521f0a76..0000000000
--- a/ruby_1_9_3/lib/webrick/compat.rb
+++ /dev/null
@@ -1,35 +0,0 @@
-#
-# compat.rb -- cross platform compatibility
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2002 GOTOU Yuuzou
-# Copyright (c) 2002 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: compat.rb,v 1.6 2002/10/01 17:16:32 gotoyuzo Exp $
-
-##
-# System call error module used by webrick for cross platform compatability.
-#
-# EPROTO:: protocol error
-# ECONNRESET:: remote host reset the connection request
-# ECONNABORTED:: Client sent TCP reset (RST) before server has accepted the
-# connection requested by client.
-#
-module Errno
- ##
- # Protocol error.
-
- class EPROTO < SystemCallError; end
-
- ##
- # Remote host reset the connection request.
-
- class ECONNRESET < SystemCallError; end
-
- ##
- # Client sent TCP reset (RST) before server has accepted the connection
- # requested by client.
-
- class ECONNABORTED < SystemCallError; end
-end
diff --git a/ruby_1_9_3/lib/webrick/config.rb b/ruby_1_9_3/lib/webrick/config.rb
deleted file mode 100644
index 8c6427020d..0000000000
--- a/ruby_1_9_3/lib/webrick/config.rb
+++ /dev/null
@@ -1,121 +0,0 @@
-#
-# config.rb -- Default configurations.
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou
-# Copyright (c) 2003 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: config.rb,v 1.52 2003/07/22 19:20:42 gotoyuzo Exp $
-
-require 'webrick/version'
-require 'webrick/httpversion'
-require 'webrick/httputils'
-require 'webrick/utils'
-require 'webrick/log'
-
-module WEBrick
- module Config
- LIBDIR = File::dirname(__FILE__)
-
- # for GenericServer
- General = {
- :ServerName => Utils::getservername,
- :BindAddress => nil, # "0.0.0.0" or "::" or nil
- :Port => nil, # users MUST specify this!!
- :MaxClients => 100, # maximum number of the concurrent connections
- :ServerType => nil, # default: WEBrick::SimpleServer
- :Logger => nil, # default: WEBrick::Log.new
- :ServerSoftware => "WEBrick/#{WEBrick::VERSION} " +
- "(Ruby/#{RUBY_VERSION}/#{RUBY_RELEASE_DATE})",
- :TempDir => ENV['TMPDIR']||ENV['TMP']||ENV['TEMP']||'/tmp',
- :DoNotListen => false,
- :StartCallback => nil,
- :StopCallback => nil,
- :AcceptCallback => nil,
- :DoNotReverseLookup => nil,
- :ShutdownSocketWithoutClose => false,
- }
-
- # for HTTPServer, HTTPRequest, HTTPResponse ...
- HTTP = General.dup.update(
- :Port => 80,
- :RequestTimeout => 30,
- :HTTPVersion => HTTPVersion.new("1.1"),
- :AccessLog => nil,
- :MimeTypes => HTTPUtils::DefaultMimeTypes,
- :DirectoryIndex => ["index.html","index.htm","index.cgi","index.rhtml"],
- :DocumentRoot => nil,
- :DocumentRootOptions => { :FancyIndexing => true },
- :RequestCallback => nil,
- :ServerAlias => nil,
- :InputBufferSize => 65536, # input buffer size in reading request body
- :OutputBufferSize => 65536, # output buffer size in sending File or IO
-
- # for HTTPProxyServer
- :ProxyAuthProc => nil,
- :ProxyContentHandler => nil,
- :ProxyVia => true,
- :ProxyTimeout => true,
- :ProxyURI => nil,
-
- :CGIInterpreter => nil,
- :CGIPathEnv => nil,
-
- # workaround: if Request-URIs contain 8bit chars,
- # they should be escaped before calling of URI::parse().
- :Escape8bitURI => false
- )
-
- FileHandler = {
- :NondisclosureName => [".ht*", "*~"],
- :FancyIndexing => false,
- :HandlerTable => {},
- :HandlerCallback => nil,
- :DirectoryCallback => nil,
- :FileCallback => nil,
- :UserDir => nil, # e.g. "public_html"
- :AcceptableLanguages => [] # ["en", "ja", ... ]
- }
-
- BasicAuth = {
- :AutoReloadUserDB => true,
- }
-
- ##
- # Default configuration for WEBrick::HTTPAuth::DigestAuth.
- #
- # :Algorithm:: MD5, MD5-sess (default), SHA1, SHA1-sess
- # :Domain:: An Array of URIs that define the protected space
- # :Qop:: 'auth' for authentication, 'auth-int' for integrity protection or
- # both
- # :UseOpaque:: Should the server send opaque values to the client? This
- # helps prevent replay attacks.
- # :CheckNc:: Should the server check the nonce count? This helps the
- # server detect replay attacks.
- # :UseAuthenticationInfoHeader:: Should the server send an
- # AuthenticationInfo header?
- # :AutoReloadUserDB:: Reload the user database provided by :UserDB
- # automatically?
- # :NonceExpirePeriod:: How long should we store used nonces? Default is
- # 30 minutes.
- # :NonceExpireDelta:: How long is a nonce valid? Default is 1 minute
- # :InternetExplorerHack:: Hack which allows Internet Explorer to work.
- # :OperaHack:: Hack which allows Opera to work.
-
- DigestAuth = {
- :Algorithm => 'MD5-sess', # or 'MD5'
- :Domain => nil, # an array includes domain names.
- :Qop => [ 'auth' ], # 'auth' or 'auth-int' or both.
- :UseOpaque => true,
- :UseNextNonce => false,
- :CheckNc => false,
- :UseAuthenticationInfoHeader => true,
- :AutoReloadUserDB => true,
- :NonceExpirePeriod => 30*60,
- :NonceExpireDelta => 60,
- :InternetExplorerHack => true,
- :OperaHack => true,
- }
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/cookie.rb b/ruby_1_9_3/lib/webrick/cookie.rb
deleted file mode 100644
index 814e6645a3..0000000000
--- a/ruby_1_9_3/lib/webrick/cookie.rb
+++ /dev/null
@@ -1,110 +0,0 @@
-#
-# cookie.rb -- Cookie class
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou
-# Copyright (c) 2002 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: cookie.rb,v 1.16 2002/09/21 12:23:35 gotoyuzo Exp $
-
-require 'time'
-require 'webrick/httputils'
-
-module WEBrick
- class Cookie
-
- attr_reader :name
- attr_accessor :value, :version
- attr_accessor :domain, :path, :secure
- attr_accessor :comment, :max_age
- #attr_accessor :comment_url, :discard, :port
-
- def initialize(name, value)
- @name = name
- @value = value
- @version = 0 # Netscape Cookie
-
- @domain = @path = @secure = @comment = @max_age =
- @expires = @comment_url = @discard = @port = nil
- end
-
- def expires=(t)
- @expires = t && (t.is_a?(Time) ? t.httpdate : t.to_s)
- end
-
- def expires
- @expires && Time.parse(@expires)
- end
-
- def to_s
- ret = ""
- ret << @name << "=" << @value
- ret << "; " << "Version=" << @version.to_s if @version > 0
- ret << "; " << "Domain=" << @domain if @domain
- ret << "; " << "Expires=" << @expires if @expires
- ret << "; " << "Max-Age=" << @max_age.to_s if @max_age
- ret << "; " << "Comment=" << @comment if @comment
- ret << "; " << "Path=" << @path if @path
- ret << "; " << "Secure" if @secure
- ret
- end
-
- # Cookie::parse()
- # It parses Cookie field sent from the user agent.
- def self.parse(str)
- if str
- ret = []
- cookie = nil
- ver = 0
- str.split(/[;,]\s+/).each{|x|
- key, val = x.split(/=/,2)
- val = val ? HTTPUtils::dequote(val) : ""
- case key
- when "$Version"; ver = val.to_i
- when "$Path"; cookie.path = val
- when "$Domain"; cookie.domain = val
- when "$Port"; cookie.port = val
- else
- ret << cookie if cookie
- cookie = self.new(key, val)
- cookie.version = ver
- end
- }
- ret << cookie if cookie
- ret
- end
- end
-
- def self.parse_set_cookie(str)
- cookie_elem = str.split(/;/)
- first_elem = cookie_elem.shift
- first_elem.strip!
- key, value = first_elem.split(/=/, 2)
- cookie = new(key, HTTPUtils.dequote(value))
- cookie_elem.each{|pair|
- pair.strip!
- key, value = pair.split(/=/, 2)
- if value
- value = HTTPUtils.dequote(value.strip)
- end
- case key.downcase
- when "domain" then cookie.domain = value
- when "path" then cookie.path = value
- when "expires" then cookie.expires = value
- when "max-age" then cookie.max_age = Integer(value)
- when "comment" then cookie.comment = value
- when "version" then cookie.version = Integer(value)
- when "secure" then cookie.secure = true
- end
- }
- return cookie
- end
-
- def self.parse_set_cookies(str)
- return str.split(/,(?=[^;,]*=)|,$/).collect{|c|
- parse_set_cookie(c)
- }
- end
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/htmlutils.rb b/ruby_1_9_3/lib/webrick/htmlutils.rb
deleted file mode 100644
index ed901f1ce2..0000000000
--- a/ruby_1_9_3/lib/webrick/htmlutils.rb
+++ /dev/null
@@ -1,28 +0,0 @@
-#--
-# htmlutils.rb -- HTMLUtils Module
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou
-# Copyright (c) 2002 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: htmlutils.rb,v 1.7 2002/09/21 12:23:35 gotoyuzo Exp $
-
-module WEBrick
- module HTMLUtils
-
- ##
- # Escapes &, ", > and < in +string+
-
- def escape(string)
- str = string ? string.dup : ""
- str.gsub!(/&/n, '&amp;')
- str.gsub!(/\"/n, '&quot;')
- str.gsub!(/>/n, '&gt;')
- str.gsub!(/</n, '&lt;')
- str
- end
- module_function :escape
-
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/httpauth.rb b/ruby_1_9_3/lib/webrick/httpauth.rb
deleted file mode 100644
index 96d479b2d7..0000000000
--- a/ruby_1_9_3/lib/webrick/httpauth.rb
+++ /dev/null
@@ -1,95 +0,0 @@
-#
-# httpauth.rb -- HTTP access authentication
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou
-# Copyright (c) 2002 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: httpauth.rb,v 1.14 2003/07/22 19:20:42 gotoyuzo Exp $
-
-require 'webrick/httpauth/basicauth'
-require 'webrick/httpauth/digestauth'
-require 'webrick/httpauth/htpasswd'
-require 'webrick/httpauth/htdigest'
-require 'webrick/httpauth/htgroup'
-
-module WEBrick
-
- ##
- # HTTPAuth provides both basic and digest authentication.
- #
- # To enable authentication for requests in WEBrick you will need a user
- # database and an authenticator. To start, here's an Htpasswd database for
- # use with a DigestAuth authenticator:
- #
- # config = { :Realm => 'DigestAuth example realm' }
- #
- # htpasswd = WEBrick::HTTPAuth::Htpasswd.new 'my_password_file'
- # htpasswd.auth_type = WEBrick::HTTPAuth::DigestAuth
- # htpasswd.set_passwd config[:Realm], 'username', 'password'
- # htpasswd.flush
- #
- # The +:Realm+ is used to provide different access to different groups
- # across several resources on a server. Typically you'll need only one
- # realm for a server.
- #
- # This database can be used to create an authenticator:
- #
- # config[:UserDB] = htpasswd
- #
- # digest_auth = WEBrick::HTTPAuth::DigestAuth.new config
- #
- # To authenticate a request call #authenticate with a request and response
- # object in a servlet:
- #
- # def do_GET req, res
- # @authenticator.authenticate req, res
- # end
- #
- # For digest authentication the authenticator must not be created every
- # request, it must be passed in as an option via WEBrick::HTTPServer#mount.
-
- module HTTPAuth
- module_function
-
- def _basic_auth(req, res, realm, req_field, res_field, err_type,
- block) # :nodoc:
- user = pass = nil
- if /^Basic\s+(.*)/o =~ req[req_field]
- userpass = $1
- user, pass = userpass.unpack("m*")[0].split(":", 2)
- end
- if block.call(user, pass)
- req.user = user
- return
- end
- res[res_field] = "Basic realm=\"#{realm}\""
- raise err_type
- end
-
- ##
- # Simple wrapper for providing basic authentication for a request. When
- # called with a request +req+, response +res+, authentication +realm+ and
- # +block+ the block will be called with a +username+ and +password+. If
- # the block returns true the request is allowed to continue, otherwise an
- # HTTPStatus::Unauthorized error is raised.
-
- def basic_auth(req, res, realm, &block) # :yield: username, password
- _basic_auth(req, res, realm, "Authorization", "WWW-Authenticate",
- HTTPStatus::Unauthorized, block)
- end
-
- ##
- # Simple wrapper for providing basic authentication for a proxied request.
- # When called with a request +req+, response +res+, authentication +realm+
- # and +block+ the block will be called with a +username+ and +password+.
- # If the block returns true the request is allowed to continue, otherwise
- # an HTTPStatus::ProxyAuthenticationRequired error is raised.
-
- def proxy_basic_auth(req, res, realm, &block) # :yield: username, password
- _basic_auth(req, res, realm, "Proxy-Authorization", "Proxy-Authenticate",
- HTTPStatus::ProxyAuthenticationRequired, block)
- end
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/httpauth/authenticator.rb b/ruby_1_9_3/lib/webrick/httpauth/authenticator.rb
deleted file mode 100644
index 9b9beeceba..0000000000
--- a/ruby_1_9_3/lib/webrick/httpauth/authenticator.rb
+++ /dev/null
@@ -1,112 +0,0 @@
-#--
-# httpauth/authenticator.rb -- Authenticator mix-in module.
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2003 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: authenticator.rb,v 1.3 2003/02/20 07:15:47 gotoyuzo Exp $
-
-module WEBrick
- module HTTPAuth
-
- ##
- # Module providing generic support for both Digest and Basic
- # authentication schemes.
-
- module Authenticator
-
- RequestField = "Authorization"
- ResponseField = "WWW-Authenticate"
- ResponseInfoField = "Authentication-Info"
- AuthException = HTTPStatus::Unauthorized
-
- ##
- # Method of authentication, must be overridden by the including class
-
- AuthScheme = nil
-
- ##
- # The realm this authenticator covers
-
- attr_reader :realm
-
- ##
- # The user database for this authenticator
-
- attr_reader :userdb
-
- ##
- # The logger for this authenticator
-
- attr_reader :logger
-
- private
-
- ##
- # Initializes the authenticator from +config+
-
- def check_init(config)
- [:UserDB, :Realm].each{|sym|
- unless config[sym]
- raise ArgumentError, "Argument #{sym.inspect} missing."
- end
- }
- @realm = config[:Realm]
- @userdb = config[:UserDB]
- @logger = config[:Logger] || Log::new($stderr)
- @reload_db = config[:AutoReloadUserDB]
- @request_field = self::class::RequestField
- @response_field = self::class::ResponseField
- @resp_info_field = self::class::ResponseInfoField
- @auth_exception = self::class::AuthException
- @auth_scheme = self::class::AuthScheme
- end
-
- ##
- # Ensures +req+ has credentials that can be authenticated.
-
- def check_scheme(req)
- unless credentials = req[@request_field]
- error("no credentials in the request.")
- return nil
- end
- unless match = /^#{@auth_scheme}\s+/i.match(credentials)
- error("invalid scheme in %s.", credentials)
- info("%s: %s", @request_field, credentials) if $DEBUG
- return nil
- end
- return match.post_match
- end
-
- def log(meth, fmt, *args)
- msg = format("%s %s: ", @auth_scheme, @realm)
- msg << fmt % args
- @logger.send(meth, msg)
- end
-
- def error(fmt, *args)
- if @logger.error?
- log(:error, fmt, *args)
- end
- end
-
- def info(fmt, *args)
- if @logger.info?
- log(:info, fmt, *args)
- end
- end
- end
-
- ##
- # Module providing generic support for both Digest and Basic
- # authentication schemes for proxies.
-
- module ProxyAuthenticator
- RequestField = "Proxy-Authorization"
- ResponseField = "Proxy-Authenticate"
- InfoField = "Proxy-Authentication-Info"
- AuthException = HTTPStatus::ProxyAuthenticationRequired
- end
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/httpauth/basicauth.rb b/ruby_1_9_3/lib/webrick/httpauth/basicauth.rb
deleted file mode 100644
index 4c51e53199..0000000000
--- a/ruby_1_9_3/lib/webrick/httpauth/basicauth.rb
+++ /dev/null
@@ -1,108 +0,0 @@
-#
-# httpauth/basicauth.rb -- HTTP basic access authentication
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2003 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: basicauth.rb,v 1.5 2003/02/20 07:15:47 gotoyuzo Exp $
-
-require 'webrick/config'
-require 'webrick/httpstatus'
-require 'webrick/httpauth/authenticator'
-
-module WEBrick
- module HTTPAuth
-
- ##
- # Basic Authentication for WEBrick
- #
- # Use this class to add basic authentication to a WEBrick servlet.
- #
- # Here is an example of how to set up a BasicAuth:
- #
- # config = { :Realm => 'BasicAuth example realm' }
- #
- # htpasswd = WEBrick::HTTPAuth::Htpasswd.new 'my_password_file'
- # htpasswd.set_passwd config[:Realm], 'username', 'password'
- # htpasswd.flush
- #
- # config[:UserDB] = htpasswd
- #
- # basic_auth = WEBrick::HTTPAuth::BasicAuth.new config
-
- class BasicAuth
- include Authenticator
-
- AuthScheme = "Basic"
-
- ##
- # Used by UserDB to create a basic password entry
-
- def self.make_passwd(realm, user, pass)
- pass ||= ""
- pass.crypt(Utils::random_string(2))
- end
-
- attr_reader :realm, :userdb, :logger
-
- ##
- # Creates a new BasicAuth instance.
- #
- # See WEBrick::Config::BasicAuth for default configuration entries
- #
- # You must supply the following configuration entries:
- #
- # :Realm:: The name of the realm being protected.
- # :UserDB:: A database of usernames and passwords.
- # A WEBrick::HTTPAuth::Htpasswd instance should be used.
-
- def initialize(config, default=Config::BasicAuth)
- check_init(config)
- @config = default.dup.update(config)
- end
-
- ##
- # Authenticates a +req+ and returns a 401 Unauthorized using +res+ if
- # the authentication was not correct.
-
- def authenticate(req, res)
- unless basic_credentials = check_scheme(req)
- challenge(req, res)
- end
- userid, password = basic_credentials.unpack("m*")[0].split(":", 2)
- password ||= ""
- if userid.empty?
- error("user id was not given.")
- challenge(req, res)
- end
- unless encpass = @userdb.get_passwd(@realm, userid, @reload_db)
- error("%s: the user is not allowed.", userid)
- challenge(req, res)
- end
- if password.crypt(encpass) != encpass
- error("%s: password unmatch.", userid)
- challenge(req, res)
- end
- info("%s: authentication succeeded.", userid)
- req.user = userid
- end
-
- ##
- # Returns a challenge response which asks for for authentication
- # information
-
- def challenge(req, res)
- res[@response_field] = "#{@auth_scheme} realm=\"#{@realm}\""
- raise @auth_exception
- end
- end
-
- ##
- # Basic authentication for proxy servers. See BasicAuth for details.
-
- class ProxyBasicAuth < BasicAuth
- include ProxyAuthenticator
- end
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/httpauth/digestauth.rb b/ruby_1_9_3/lib/webrick/httpauth/digestauth.rb
deleted file mode 100644
index 4e47fe163f..0000000000
--- a/ruby_1_9_3/lib/webrick/httpauth/digestauth.rb
+++ /dev/null
@@ -1,392 +0,0 @@
-#
-# httpauth/digestauth.rb -- HTTP digest access authentication
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2003 Internet Programming with Ruby writers.
-# Copyright (c) 2003 H.M.
-#
-# The original implementation is provided by H.M.
-# URL: http://rwiki.jin.gr.jp/cgi-bin/rw-cgi.rb?cmd=view;name=
-# %C7%A7%BE%DA%B5%A1%C7%BD%A4%F2%B2%FE%C2%A4%A4%B7%A4%C6%A4%DF%A4%EB
-#
-# $IPR: digestauth.rb,v 1.5 2003/02/20 07:15:47 gotoyuzo Exp $
-
-require 'webrick/config'
-require 'webrick/httpstatus'
-require 'webrick/httpauth/authenticator'
-require 'digest/md5'
-require 'digest/sha1'
-
-module WEBrick
- module HTTPAuth
-
- ##
- # RFC 2617 Digest Access Authentication for WEBrick
- #
- # Use this class to add digest authentication to a WEBrick servlet.
- #
- # Here is an example of how to set up DigestAuth:
- #
- # config = { :Realm => 'DigestAuth example realm' }
- #
- # htdigest = WEBrick::HTTPAuth::Htdigest.new 'my_password_file'
- # htdigest.set_passwd config[:Realm], 'username', 'password'
- # htdigest.flush
- #
- # config[:UserDB] = htdigest
- #
- # digest_auth = WEBrick::HTTPAuth::DigestAuth.new config
- #
- # When using this as with a servlet be sure not to create a new DigestAuth
- # object in the servlet's #initialize. By default WEBrick creates a new
- # servlet instance for every request and the DigestAuth object must be
- # used across requests.
-
- class DigestAuth
- include Authenticator
-
- AuthScheme = "Digest"
- OpaqueInfo = Struct.new(:time, :nonce, :nc)
- attr_reader :algorithm, :qop
-
- ##
- # Used by UserDB to create a digest password entry
-
- def self.make_passwd(realm, user, pass)
- pass ||= ""
- Digest::MD5::hexdigest([user, realm, pass].join(":"))
- end
-
- ##
- # Creates a new DigestAuth instance. Be sure to use the same DigestAuth
- # instance for multiple requests as it saves state between requests in
- # order to perform authentication.
- #
- # See WEBrick::Config::DigestAuth for default configuration entries
- #
- # You must supply the following configuration entries:
- #
- # :Realm:: The name of the realm being protected.
- # :UserDB:: A database of usernames and passwords.
- # A WEBrick::HTTPAuth::Htdigest instance should be used.
-
- def initialize(config, default=Config::DigestAuth)
- check_init(config)
- @config = default.dup.update(config)
- @algorithm = @config[:Algorithm]
- @domain = @config[:Domain]
- @qop = @config[:Qop]
- @use_opaque = @config[:UseOpaque]
- @use_next_nonce = @config[:UseNextNonce]
- @check_nc = @config[:CheckNc]
- @use_auth_info_header = @config[:UseAuthenticationInfoHeader]
- @nonce_expire_period = @config[:NonceExpirePeriod]
- @nonce_expire_delta = @config[:NonceExpireDelta]
- @internet_explorer_hack = @config[:InternetExplorerHack]
-
- case @algorithm
- when 'MD5','MD5-sess'
- @h = Digest::MD5
- when 'SHA1','SHA1-sess' # it is a bonus feature :-)
- @h = Digest::SHA1
- else
- msg = format('Algorithm "%s" is not supported.', @algorithm)
- raise ArgumentError.new(msg)
- end
-
- @instance_key = hexdigest(self.__id__, Time.now.to_i, Process.pid)
- @opaques = {}
- @last_nonce_expire = Time.now
- @mutex = Mutex.new
- end
-
- ##
- # Authenticates a +req+ and returns a 401 Unauthorized using +res+ if
- # the authentication was not correct.
-
- def authenticate(req, res)
- unless result = @mutex.synchronize{ _authenticate(req, res) }
- challenge(req, res)
- end
- if result == :nonce_is_stale
- challenge(req, res, true)
- end
- return true
- end
-
- ##
- # Returns a challenge response which asks for for authentication
- # information
-
- def challenge(req, res, stale=false)
- nonce = generate_next_nonce(req)
- if @use_opaque
- opaque = generate_opaque(req)
- @opaques[opaque].nonce = nonce
- end
-
- param = Hash.new
- param["realm"] = HTTPUtils::quote(@realm)
- param["domain"] = HTTPUtils::quote(@domain.to_a.join(" ")) if @domain
- param["nonce"] = HTTPUtils::quote(nonce)
- param["opaque"] = HTTPUtils::quote(opaque) if opaque
- param["stale"] = stale.to_s
- param["algorithm"] = @algorithm
- param["qop"] = HTTPUtils::quote(@qop.to_a.join(",")) if @qop
-
- res[@response_field] =
- "#{@auth_scheme} " + param.map{|k,v| "#{k}=#{v}" }.join(", ")
- info("%s: %s", @response_field, res[@response_field]) if $DEBUG
- raise @auth_exception
- end
-
- private
-
- MustParams = ['username','realm','nonce','uri','response']
- MustParamsAuth = ['cnonce','nc']
-
- def _authenticate(req, res)
- unless digest_credentials = check_scheme(req)
- return false
- end
-
- auth_req = split_param_value(digest_credentials)
- if auth_req['qop'] == "auth" || auth_req['qop'] == "auth-int"
- req_params = MustParams + MustParamsAuth
- else
- req_params = MustParams
- end
- req_params.each{|key|
- unless auth_req.has_key?(key)
- error('%s: parameter missing. "%s"', auth_req['username'], key)
- raise HTTPStatus::BadRequest
- end
- }
-
- if !check_uri(req, auth_req)
- raise HTTPStatus::BadRequest
- end
-
- if auth_req['realm'] != @realm
- error('%s: realm unmatch. "%s" for "%s"',
- auth_req['username'], auth_req['realm'], @realm)
- return false
- end
-
- auth_req['algorithm'] ||= 'MD5'
- if auth_req['algorithm'].upcase != @algorithm.upcase
- error('%s: algorithm unmatch. "%s" for "%s"',
- auth_req['username'], auth_req['algorithm'], @algorithm)
- return false
- end
-
- if (@qop.nil? && auth_req.has_key?('qop')) ||
- (@qop && (! @qop.member?(auth_req['qop'])))
- error('%s: the qop is not allowed. "%s"',
- auth_req['username'], auth_req['qop'])
- return false
- end
-
- password = @userdb.get_passwd(@realm, auth_req['username'], @reload_db)
- unless password
- error('%s: the user is not allowd.', auth_req['username'])
- return false
- end
-
- nonce_is_invalid = false
- if @use_opaque
- info("@opaque = %s", @opaque.inspect) if $DEBUG
- if !(opaque = auth_req['opaque'])
- error('%s: opaque is not given.', auth_req['username'])
- nonce_is_invalid = true
- elsif !(opaque_struct = @opaques[opaque])
- error('%s: invalid opaque is given.', auth_req['username'])
- nonce_is_invalid = true
- elsif !check_opaque(opaque_struct, req, auth_req)
- @opaques.delete(auth_req['opaque'])
- nonce_is_invalid = true
- end
- elsif !check_nonce(req, auth_req)
- nonce_is_invalid = true
- end
-
- if /-sess$/i =~ auth_req['algorithm']
- ha1 = hexdigest(password, auth_req['nonce'], auth_req['cnonce'])
- else
- ha1 = password
- end
-
- if auth_req['qop'] == "auth" || auth_req['qop'] == nil
- ha2 = hexdigest(req.request_method, auth_req['uri'])
- ha2_res = hexdigest("", auth_req['uri'])
- elsif auth_req['qop'] == "auth-int"
- ha2 = hexdigest(req.request_method, auth_req['uri'],
- hexdigest(req.body))
- ha2_res = hexdigest("", auth_req['uri'], hexdigest(res.body))
- end
-
- if auth_req['qop'] == "auth" || auth_req['qop'] == "auth-int"
- param2 = ['nonce', 'nc', 'cnonce', 'qop'].map{|key|
- auth_req[key]
- }.join(':')
- digest = hexdigest(ha1, param2, ha2)
- digest_res = hexdigest(ha1, param2, ha2_res)
- else
- digest = hexdigest(ha1, auth_req['nonce'], ha2)
- digest_res = hexdigest(ha1, auth_req['nonce'], ha2_res)
- end
-
- if digest != auth_req['response']
- error("%s: digest unmatch.", auth_req['username'])
- return false
- elsif nonce_is_invalid
- error('%s: digest is valid, but nonce is not valid.',
- auth_req['username'])
- return :nonce_is_stale
- elsif @use_auth_info_header
- auth_info = {
- 'nextnonce' => generate_next_nonce(req),
- 'rspauth' => digest_res
- }
- if @use_opaque
- opaque_struct.time = req.request_time
- opaque_struct.nonce = auth_info['nextnonce']
- opaque_struct.nc = "%08x" % (auth_req['nc'].hex + 1)
- end
- if auth_req['qop'] == "auth" || auth_req['qop'] == "auth-int"
- ['qop','cnonce','nc'].each{|key|
- auth_info[key] = auth_req[key]
- }
- end
- res[@resp_info_field] = auth_info.keys.map{|key|
- if key == 'nc'
- key + '=' + auth_info[key]
- else
- key + "=" + HTTPUtils::quote(auth_info[key])
- end
- }.join(', ')
- end
- info('%s: authentication succeeded.', auth_req['username'])
- req.user = auth_req['username']
- return true
- end
-
- def split_param_value(string)
- ret = {}
- while string.bytesize != 0
- case string
- when /^\s*([\w\-\.\*\%\!]+)=\s*\"((\\.|[^\"])*)\"\s*,?/
- key = $1
- matched = $2
- string = $'
- ret[key] = matched.gsub(/\\(.)/, "\\1")
- when /^\s*([\w\-\.\*\%\!]+)=\s*([^,\"]*),?/
- key = $1
- matched = $2
- string = $'
- ret[key] = matched.clone
- when /^s*^,/
- string = $'
- else
- break
- end
- end
- ret
- end
-
- def generate_next_nonce(req)
- now = "%012d" % req.request_time.to_i
- pk = hexdigest(now, @instance_key)[0,32]
- nonce = [now + ":" + pk].pack("m*").chop # it has 60 length of chars.
- nonce
- end
-
- def check_nonce(req, auth_req)
- username = auth_req['username']
- nonce = auth_req['nonce']
-
- pub_time, pk = nonce.unpack("m*")[0].split(":", 2)
- if (!pub_time || !pk)
- error("%s: empty nonce is given", username)
- return false
- elsif (hexdigest(pub_time, @instance_key)[0,32] != pk)
- error("%s: invalid private-key: %s for %s",
- username, hexdigest(pub_time, @instance_key)[0,32], pk)
- return false
- end
-
- diff_time = req.request_time.to_i - pub_time.to_i
- if (diff_time < 0)
- error("%s: difference of time-stamp is negative.", username)
- return false
- elsif diff_time > @nonce_expire_period
- error("%s: nonce is expired.", username)
- return false
- end
-
- return true
- end
-
- def generate_opaque(req)
- @mutex.synchronize{
- now = req.request_time
- if now - @last_nonce_expire > @nonce_expire_delta
- @opaques.delete_if{|key,val|
- (now - val.time) > @nonce_expire_period
- }
- @last_nonce_expire = now
- end
- begin
- opaque = Utils::random_string(16)
- end while @opaques[opaque]
- @opaques[opaque] = OpaqueInfo.new(now, nil, '00000001')
- opaque
- }
- end
-
- def check_opaque(opaque_struct, req, auth_req)
- if (@use_next_nonce && auth_req['nonce'] != opaque_struct.nonce)
- error('%s: nonce unmatched. "%s" for "%s"',
- auth_req['username'], auth_req['nonce'], opaque_struct.nonce)
- return false
- elsif !check_nonce(req, auth_req)
- return false
- end
- if (@check_nc && auth_req['nc'] != opaque_struct.nc)
- error('%s: nc unmatched."%s" for "%s"',
- auth_req['username'], auth_req['nc'], opaque_struct.nc)
- return false
- end
- true
- end
-
- def check_uri(req, auth_req)
- uri = auth_req['uri']
- if uri != req.request_uri.to_s && uri != req.unparsed_uri &&
- (@internet_explorer_hack && uri != req.path)
- error('%s: uri unmatch. "%s" for "%s"', auth_req['username'],
- auth_req['uri'], req.request_uri.to_s)
- return false
- end
- true
- end
-
- def hexdigest(*args)
- @h.hexdigest(args.join(":"))
- end
-
- end
-
- ##
- # Digest authentication for proxy servers. See DigestAuth for details.
-
- class ProxyDigestAuth < DigestAuth
- include ProxyAuthenticator
-
- private
- def check_uri(req, auth_req)
- return true
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/httpauth/htdigest.rb b/ruby_1_9_3/lib/webrick/httpauth/htdigest.rb
deleted file mode 100644
index 4b74588c77..0000000000
--- a/ruby_1_9_3/lib/webrick/httpauth/htdigest.rb
+++ /dev/null
@@ -1,128 +0,0 @@
-#
-# httpauth/htdigest.rb -- Apache compatible htdigest file
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2003 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: htdigest.rb,v 1.4 2003/07/22 19:20:45 gotoyuzo Exp $
-
-require 'webrick/httpauth/userdb'
-require 'webrick/httpauth/digestauth'
-require 'tempfile'
-
-module WEBrick
- module HTTPAuth
-
- ##
- # Htdigest accesses apache-compatible digest password files. Passwords are
- # matched to a realm where they are valid. For security, the path for a
- # digest password database should be stored outside of the paths available
- # to the HTTP server.
- #
- # Htdigest is intended for use with WEBrick::HTTPAuth::DigestAuth and
- # stores passwords using cryptographic hashes.
- #
- # htpasswd = WEBrick::HTTPAuth::Htdigest.new 'my_password_file'
- # htpasswd.set_passwd 'my realm', 'username', 'password'
- # htpasswd.flush
-
- class Htdigest
- include UserDB
-
- ##
- # Open a digest password database at +path+
-
- def initialize(path)
- @path = path
- @mtime = Time.at(0)
- @digest = Hash.new
- @mutex = Mutex::new
- @auth_type = DigestAuth
- open(@path,"a").close unless File::exist?(@path)
- reload
- end
-
- ##
- # Reloads passwords from the database
-
- def reload
- mtime = File::mtime(@path)
- if mtime > @mtime
- @digest.clear
- open(@path){|io|
- while line = io.gets
- line.chomp!
- user, realm, pass = line.split(/:/, 3)
- unless @digest[realm]
- @digest[realm] = Hash.new
- end
- @digest[realm][user] = pass
- end
- }
- @mtime = mtime
- end
- end
-
- ##
- # Flush the password database. If +output+ is given the database will
- # be written there instead of to the original path.
-
- def flush(output=nil)
- output ||= @path
- tmp = Tempfile.new("htpasswd", File::dirname(output))
- begin
- each{|item| tmp.puts(item.join(":")) }
- tmp.close
- File::rename(tmp.path, output)
- rescue
- tmp.close(true)
- end
- end
-
- ##
- # Retrieves a password from the database for +user+ in +realm+. If
- # +reload_db+ is true the database will be reloaded first.
-
- def get_passwd(realm, user, reload_db)
- reload() if reload_db
- if hash = @digest[realm]
- hash[user]
- end
- end
-
- ##
- # Sets a password in the database for +user+ in +realm+ to +pass+.
-
- def set_passwd(realm, user, pass)
- @mutex.synchronize{
- unless @digest[realm]
- @digest[realm] = Hash.new
- end
- @digest[realm][user] = make_passwd(realm, user, pass)
- }
- end
-
- ##
- # Removes a password from the database for +user+ in +realm+.
-
- def delete_passwd(realm, user)
- if hash = @digest[realm]
- hash.delete(user)
- end
- end
-
- ##
- # Iterate passwords in the database.
-
- def each # :yields: [user, realm, password_hash]
- @digest.keys.sort.each{|realm|
- hash = @digest[realm]
- hash.keys.sort.each{|user|
- yield([user, realm, hash[user]])
- }
- }
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/httpauth/htgroup.rb b/ruby_1_9_3/lib/webrick/httpauth/htgroup.rb
deleted file mode 100644
index 0ecabef820..0000000000
--- a/ruby_1_9_3/lib/webrick/httpauth/htgroup.rb
+++ /dev/null
@@ -1,93 +0,0 @@
-#
-# httpauth/htgroup.rb -- Apache compatible htgroup file
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2003 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: htgroup.rb,v 1.1 2003/02/16 22:22:56 gotoyuzo Exp $
-
-require 'tempfile'
-
-module WEBrick
- module HTTPAuth
-
- ##
- # Htgroup accesses apache-compatible group files. Htgroup can be used to
- # provide group-based authentication for users. Currently Htgroup is not
- # directly integrated with any authenticators in WEBrick. For security,
- # the path for a digest password database should be stored outside of the
- # paths available to the HTTP server.
- #
- # Example:
- #
- # htgroup = WEBrick::HTTPAuth::Htgroup.new 'my_group_file'
- # htgroup.add 'superheroes', %w[spiderman batman]
- #
- # htgroup.members('superheroes').include? 'magneto' # => false
-
- class Htgroup
-
- ##
- # Open a group database at +path+
-
- def initialize(path)
- @path = path
- @mtime = Time.at(0)
- @group = Hash.new
- open(@path,"a").close unless File::exist?(@path)
- reload
- end
-
- ##
- # Reload groups from the database
-
- def reload
- if (mtime = File::mtime(@path)) > @mtime
- @group.clear
- open(@path){|io|
- while line = io.gets
- line.chomp!
- group, members = line.split(/:\s*/)
- @group[group] = members.split(/\s+/)
- end
- }
- @mtime = mtime
- end
- end
-
- ##
- # Flush the group database. If +output+ is given the database will be
- # written there instead of to the original path.
-
- def flush(output=nil)
- output ||= @path
- tmp = Tempfile.new("htgroup", File::dirname(output))
- begin
- @group.keys.sort.each{|group|
- tmp.puts(format("%s: %s", group, self.members(group).join(" ")))
- }
- tmp.close
- File::rename(tmp.path, output)
- rescue
- tmp.close(true)
- end
- end
-
- ##
- # Retrieve the list of members from +group+
-
- def members(group)
- reload
- @group[group] || []
- end
-
- ##
- # Add an Array of +members+ to +group+
-
- def add(group, members)
- @group[group] = members(group) | members
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/httpauth/htpasswd.rb b/ruby_1_9_3/lib/webrick/httpauth/htpasswd.rb
deleted file mode 100644
index 205a6db2f0..0000000000
--- a/ruby_1_9_3/lib/webrick/httpauth/htpasswd.rb
+++ /dev/null
@@ -1,121 +0,0 @@
-#
-# httpauth/htpasswd -- Apache compatible htpasswd file
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2003 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: htpasswd.rb,v 1.4 2003/07/22 19:20:45 gotoyuzo Exp $
-
-require 'webrick/httpauth/userdb'
-require 'webrick/httpauth/basicauth'
-require 'tempfile'
-
-module WEBrick
- module HTTPAuth
-
- ##
- # Htpasswd accesses apache-compatible password files. Passwords are
- # matched to a realm where they are valid. For security, the path for a
- # password database should be stored outside of the paths available to the
- # HTTP server.
- #
- # Htpasswd is intended for use with WEBrick::HTTPAuth::BasicAuth.
- #
- # To create an Htpasswd database with a single user:
- #
- # htpasswd = WEBrick::HTTPAuth::Htpasswd.new 'my_password_file'
- # htpasswd.set_passwd 'my realm', 'username', 'password'
- # htpasswd.flush
-
- class Htpasswd
- include UserDB
-
- ##
- # Open a password database at +path+
-
- def initialize(path)
- @path = path
- @mtime = Time.at(0)
- @passwd = Hash.new
- @auth_type = BasicAuth
- open(@path,"a").close unless File::exist?(@path)
- reload
- end
-
- ##
- # Reload passwords from the database
-
- def reload
- mtime = File::mtime(@path)
- if mtime > @mtime
- @passwd.clear
- open(@path){|io|
- while line = io.gets
- line.chomp!
- case line
- when %r!\A[^:]+:[a-zA-Z0-9./]{13}\z!
- user, pass = line.split(":")
- when /:\$/, /:{SHA}/
- raise NotImplementedError,
- 'MD5, SHA1 .htpasswd file not supported'
- else
- raise StandardError, 'bad .htpasswd file'
- end
- @passwd[user] = pass
- end
- }
- @mtime = mtime
- end
- end
-
- ##
- # Flush the password database. If +output+ is given the database will
- # be written there instead of to the original path.
-
- def flush(output=nil)
- output ||= @path
- tmp = Tempfile.new("htpasswd", File::dirname(output))
- begin
- each{|item| tmp.puts(item.join(":")) }
- tmp.close
- File::rename(tmp.path, output)
- rescue
- tmp.close(true)
- end
- end
-
- ##
- # Retrieves a password from the database for +user+ in +realm+. If
- # +reload_db+ is true the database will be reloaded first.
-
- def get_passwd(realm, user, reload_db)
- reload() if reload_db
- @passwd[user]
- end
-
- ##
- # Sets a password in the database for +user+ in +realm+ to +pass+.
-
- def set_passwd(realm, user, pass)
- @passwd[user] = make_passwd(realm, user, pass)
- end
-
- ##
- # Removes a password from the database for +user+ in +realm+.
-
- def delete_passwd(realm, user)
- @passwd.delete(user)
- end
-
- ##
- # Iterate passwords in the database.
-
- def each # :yields: [user, password]
- @passwd.keys.sort.each{|user|
- yield([user, @passwd[user]])
- }
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/httpauth/userdb.rb b/ruby_1_9_3/lib/webrick/httpauth/userdb.rb
deleted file mode 100644
index 005c18dfd0..0000000000
--- a/ruby_1_9_3/lib/webrick/httpauth/userdb.rb
+++ /dev/null
@@ -1,52 +0,0 @@
-#--
-# httpauth/userdb.rb -- UserDB mix-in module.
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2003 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: userdb.rb,v 1.2 2003/02/20 07:15:48 gotoyuzo Exp $
-
-module WEBrick
- module HTTPAuth
-
- ##
- # User database mixin for HTTPAuth. This mixin dispatches user record
- # access to the underlying auth_type for this database.
-
- module UserDB
-
- ##
- # The authentication type.
- #
- # WEBrick::HTTPAuth::BasicAuth or WEBrick::HTTPAuth::DigestAuth are
- # built-in.
-
- attr_accessor :auth_type
-
- ##
- # Creates an obscured password in +realm+ with +user+ and +password+
- # using the auth_type of this database.
-
- def make_passwd(realm, user, pass)
- @auth_type::make_passwd(realm, user, pass)
- end
-
- ##
- # Sets a password in +realm+ with +user+ and +password+ for the
- # auth_type of this database.
-
- def set_passwd(realm, user, pass)
- self[user] = pass
- end
-
- ##
- # Retrieves a password in +realm+ for +user+ for the auth_type of this
- # database. +reload_db+ is a dummy value.
-
- def get_passwd(realm, user, reload_db=false)
- make_passwd(realm, user, self[user])
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/httpproxy.rb b/ruby_1_9_3/lib/webrick/httpproxy.rb
deleted file mode 100644
index 33ce17b2d4..0000000000
--- a/ruby_1_9_3/lib/webrick/httpproxy.rb
+++ /dev/null
@@ -1,305 +0,0 @@
-#
-# httpproxy.rb -- HTTPProxy Class
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2002 GOTO Kentaro
-# Copyright (c) 2002 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: httpproxy.rb,v 1.18 2003/03/08 18:58:10 gotoyuzo Exp $
-# $kNotwork: straw.rb,v 1.3 2002/02/12 15:13:07 gotoken Exp $
-
-require "webrick/httpserver"
-require "net/http"
-
-Net::HTTP::version_1_2 if RUBY_VERSION < "1.7"
-
-module WEBrick
- NullReader = Object.new
- class << NullReader
- def read(*args)
- nil
- end
- alias gets read
- end
-
- FakeProxyURI = Object.new
- class << FakeProxyURI
- def method_missing(meth, *args)
- if %w(scheme host port path query userinfo).member?(meth.to_s)
- return nil
- end
- super
- end
- end
-
- ##
- # An HTTP Proxy server which proxies GET, HEAD and POST requests.
-
- class HTTPProxyServer < HTTPServer
-
- ##
- # Proxy server configurations. The proxy server handles the following
- # configuration items in addition to those supported by HTTPServer:
- #
- # :ProxyAuthProc:: Called with a request and response to authorize a
- # request
- # :ProxyVia:: Appended to the via header
- # :ProxyURI:: The proxy server's URI
- # :ProxyContentHandler:: Called with a request and resopnse and allows
- # modification of the response
- # :ProxyTimeout:: Sets the proxy timeouts to 30 seconds for open and 60
- # seconds for read operations
-
- def initialize(config={}, default=Config::HTTP)
- super(config, default)
- c = @config
- @via = "#{c[:HTTPVersion]} #{c[:ServerName]}:#{c[:Port]}"
- end
-
- def service(req, res)
- if req.request_method == "CONNECT"
- do_CONNECT(req, res)
- elsif req.unparsed_uri =~ %r!^http://!
- proxy_service(req, res)
- else
- super(req, res)
- end
- end
-
- def proxy_auth(req, res)
- if proc = @config[:ProxyAuthProc]
- proc.call(req, res)
- end
- req.header.delete("proxy-authorization")
- end
-
- def proxy_uri(req, res)
- # should return upstream proxy server's URI
- return @config[:ProxyURI]
- end
-
- def proxy_service(req, res)
- # Proxy Authentication
- proxy_auth(req, res)
-
- begin
- self.send("do_#{req.request_method}", req, res)
- rescue NoMethodError
- raise HTTPStatus::MethodNotAllowed,
- "unsupported method `#{req.request_method}'."
- rescue => err
- logger.debug("#{err.class}: #{err.message}")
- raise HTTPStatus::ServiceUnavailable, err.message
- end
-
- # Process contents
- if handler = @config[:ProxyContentHandler]
- handler.call(req, res)
- end
- end
-
- def do_CONNECT(req, res)
- # Proxy Authentication
- proxy_auth(req, res)
-
- ua = Thread.current[:WEBrickSocket] # User-Agent
- raise HTTPStatus::InternalServerError,
- "[BUG] cannot get socket" unless ua
-
- host, port = req.unparsed_uri.split(":", 2)
- # Proxy authentication for upstream proxy server
- if proxy = proxy_uri(req, res)
- proxy_request_line = "CONNECT #{host}:#{port} HTTP/1.0"
- if proxy.userinfo
- credentials = "Basic " + [proxy.userinfo].pack("m").delete("\n")
- end
- host, port = proxy.host, proxy.port
- end
-
- begin
- @logger.debug("CONNECT: upstream proxy is `#{host}:#{port}'.")
- os = TCPSocket.new(host, port) # origin server
-
- if proxy
- @logger.debug("CONNECT: sending a Request-Line")
- os << proxy_request_line << CRLF
- @logger.debug("CONNECT: > #{proxy_request_line}")
- if credentials
- @logger.debug("CONNECT: sending a credentials")
- os << "Proxy-Authorization: " << credentials << CRLF
- end
- os << CRLF
- proxy_status_line = os.gets(LF)
- @logger.debug("CONNECT: read a Status-Line form the upstream server")
- @logger.debug("CONNECT: < #{proxy_status_line}")
- if %r{^HTTP/\d+\.\d+\s+200\s*} =~ proxy_status_line
- while line = os.gets(LF)
- break if /\A(#{CRLF}|#{LF})\z/om =~ line
- end
- else
- raise HTTPStatus::BadGateway
- end
- end
- @logger.debug("CONNECT #{host}:#{port}: succeeded")
- res.status = HTTPStatus::RC_OK
- rescue => ex
- @logger.debug("CONNECT #{host}:#{port}: failed `#{ex.message}'")
- res.set_error(ex)
- raise HTTPStatus::EOFError
- ensure
- if handler = @config[:ProxyContentHandler]
- handler.call(req, res)
- end
- res.send_response(ua)
- access_log(@config, req, res)
-
- # Should clear request-line not to send the sesponse twice.
- # see: HTTPServer#run
- req.parse(NullReader) rescue nil
- end
-
- begin
- while fds = IO::select([ua, os])
- if fds[0].member?(ua)
- buf = ua.sysread(1024);
- @logger.debug("CONNECT: #{buf.bytesize} byte from User-Agent")
- os.syswrite(buf)
- elsif fds[0].member?(os)
- buf = os.sysread(1024);
- @logger.debug("CONNECT: #{buf.bytesize} byte from #{host}:#{port}")
- ua.syswrite(buf)
- end
- end
- rescue => ex
- os.close
- @logger.debug("CONNECT #{host}:#{port}: closed")
- end
-
- raise HTTPStatus::EOFError
- end
-
- def do_GET(req, res)
- perform_proxy_request(req, res) do |http, path, header|
- http.get(path, header)
- end
- end
-
- def do_HEAD(req, res)
- perform_proxy_request(req, res) do |http, path, header|
- http.head(path, header)
- end
- end
-
- def do_POST(req, res)
- perform_proxy_request(req, res) do |http, path, header|
- http.post(path, req.body || "", header)
- end
- end
-
- def do_OPTIONS(req, res)
- res['allow'] = "GET,HEAD,POST,OPTIONS,CONNECT"
- end
-
- private
-
- # Some header fields should not be transferred.
- HopByHop = %w( connection keep-alive proxy-authenticate upgrade
- proxy-authorization te trailers transfer-encoding )
- ShouldNotTransfer = %w( set-cookie proxy-connection )
- def split_field(f) f ? f.split(/,\s+/).collect{|i| i.downcase } : [] end
-
- def choose_header(src, dst)
- connections = split_field(src['connection'])
- src.each{|key, value|
- key = key.downcase
- if HopByHop.member?(key) || # RFC2616: 13.5.1
- connections.member?(key) || # RFC2616: 14.10
- ShouldNotTransfer.member?(key) # pragmatics
- @logger.debug("choose_header: `#{key}: #{value}'")
- next
- end
- dst[key] = value
- }
- end
-
- # Net::HTTP is stupid about the multiple header fields.
- # Here is workaround:
- def set_cookie(src, dst)
- if str = src['set-cookie']
- cookies = []
- str.split(/,\s*/).each{|token|
- if /^[^=]+;/o =~ token
- cookies[-1] << ", " << token
- elsif /=/o =~ token
- cookies << token
- else
- cookies[-1] << ", " << token
- end
- }
- dst.cookies.replace(cookies)
- end
- end
-
- def set_via(h)
- if @config[:ProxyVia]
- if h['via']
- h['via'] << ", " << @via
- else
- h['via'] = @via
- end
- end
- end
-
- def setup_proxy_header(req, res)
- # Choose header fields to transfer
- header = Hash.new
- choose_header(req, header)
- set_via(header)
- return header
- end
-
- def setup_upstream_proxy_authentication(req, res, header)
- if upstream = proxy_uri(req, res)
- if upstream.userinfo
- header['proxy-authorization'] =
- "Basic " + [upstream.userinfo].pack("m").delete("\n")
- end
- return upstream
- end
- return FakeProxyURI
- end
-
- def perform_proxy_request(req, res)
- uri = req.request_uri
- path = uri.path.dup
- path << "?" << uri.query if uri.query
- header = setup_proxy_header(req, res)
- upstream = setup_upstream_proxy_authentication(req, res, header)
- response = nil
-
- http = Net::HTTP.new(uri.host, uri.port, upstream.host, upstream.port)
- http.start do
- if @config[:ProxyTimeout]
- ################################## these issues are
- http.open_timeout = 30 # secs # necessary (maybe bacause
- http.read_timeout = 60 # secs # Ruby's bug, but why?)
- ##################################
- end
- response = yield(http, path, header)
- end
-
- # Persistent connection requirements are mysterious for me.
- # So I will close the connection in every response.
- res['proxy-connection'] = "close"
- res['connection'] = "close"
-
- # Convert Net::HTTP::HTTPResponse to WEBrick::HTTPResponse
- res.status = response.code.to_i
- choose_header(response, res)
- set_cookie(response, res)
- set_via(res)
- res.body = response.body
- end
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/httprequest.rb b/ruby_1_9_3/lib/webrick/httprequest.rb
deleted file mode 100644
index 050b5ed45b..0000000000
--- a/ruby_1_9_3/lib/webrick/httprequest.rb
+++ /dev/null
@@ -1,461 +0,0 @@
-#
-# httprequest.rb -- HTTPRequest Class
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou
-# Copyright (c) 2002 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: httprequest.rb,v 1.64 2003/07/13 17:18:22 gotoyuzo Exp $
-
-require 'uri'
-require 'webrick/httpversion'
-require 'webrick/httpstatus'
-require 'webrick/httputils'
-require 'webrick/cookie'
-
-module WEBrick
-
- ##
- # An HTTP request.
- class HTTPRequest
-
- BODY_CONTAINABLE_METHODS = [ "POST", "PUT" ]
-
- # :section: Request line
- attr_reader :request_line
- attr_reader :request_method, :unparsed_uri, :http_version
-
- # :section: Request-URI
- attr_reader :request_uri, :path
- attr_accessor :script_name, :path_info, :query_string
-
- # :section: Header and entity body
- attr_reader :raw_header, :header, :cookies
- attr_reader :accept, :accept_charset
- attr_reader :accept_encoding, :accept_language
-
- # :section:
- attr_accessor :user
- attr_reader :addr, :peeraddr
- attr_reader :attributes
- attr_reader :keep_alive
- attr_reader :request_time
-
- def initialize(config)
- @config = config
- @buffer_size = @config[:InputBufferSize]
- @logger = config[:Logger]
-
- @request_line = @request_method =
- @unparsed_uri = @http_version = nil
-
- @request_uri = @host = @port = @path = nil
- @script_name = @path_info = nil
- @query_string = nil
- @query = nil
- @form_data = nil
-
- @raw_header = Array.new
- @header = nil
- @cookies = []
- @accept = []
- @accept_charset = []
- @accept_encoding = []
- @accept_language = []
- @body = ""
-
- @addr = @peeraddr = nil
- @attributes = {}
- @user = nil
- @keep_alive = false
- @request_time = nil
-
- @remaining_size = nil
- @socket = nil
-
- @forwarded_proto = @forwarded_host = @forwarded_port =
- @forwarded_server = @forwarded_for = nil
- end
-
- def parse(socket=nil)
- @socket = socket
- begin
- @peeraddr = socket.respond_to?(:peeraddr) ? socket.peeraddr : []
- @addr = socket.respond_to?(:addr) ? socket.addr : []
- rescue Errno::ENOTCONN
- raise HTTPStatus::EOFError
- end
-
- read_request_line(socket)
- if @http_version.major > 0
- read_header(socket)
- @header['cookie'].each{|cookie|
- @cookies += Cookie::parse(cookie)
- }
- @accept = HTTPUtils.parse_qvalues(self['accept'])
- @accept_charset = HTTPUtils.parse_qvalues(self['accept-charset'])
- @accept_encoding = HTTPUtils.parse_qvalues(self['accept-encoding'])
- @accept_language = HTTPUtils.parse_qvalues(self['accept-language'])
- end
- return if @request_method == "CONNECT"
- return if @unparsed_uri == "*"
-
- begin
- setup_forwarded_info
- @request_uri = parse_uri(@unparsed_uri)
- @path = HTTPUtils::unescape(@request_uri.path)
- @path = HTTPUtils::normalize_path(@path)
- @host = @request_uri.host
- @port = @request_uri.port
- @query_string = @request_uri.query
- @script_name = ""
- @path_info = @path.dup
- rescue
- raise HTTPStatus::BadRequest, "bad URI `#{@unparsed_uri}'."
- end
-
- if /close/io =~ self["connection"]
- @keep_alive = false
- elsif /keep-alive/io =~ self["connection"]
- @keep_alive = true
- elsif @http_version < "1.1"
- @keep_alive = false
- else
- @keep_alive = true
- end
- end
-
- # Generate HTTP/1.1 100 continue response if the client expects it,
- # otherwise does nothing.
- def continue
- if self['expect'] == '100-continue' && @config[:HTTPVersion] >= "1.1"
- @socket << "HTTP/#{@config[:HTTPVersion]} 100 continue#{CRLF}#{CRLF}"
- @header.delete('expect')
- end
- end
-
- def body(&block)
- block ||= Proc.new{|chunk| @body << chunk }
- read_body(@socket, block)
- @body.empty? ? nil : @body
- end
-
- ##
- # Request query as a Hash
-
- def query
- unless @query
- parse_query()
- end
- @query
- end
-
- ##
- # The content-length header
-
- def content_length
- return Integer(self['content-length'])
- end
-
- ##
- # The content-type header
-
- def content_type
- return self['content-type']
- end
-
- ##
- # Retrieves +header_name+
-
- def [](header_name)
- if @header
- value = @header[header_name.downcase]
- value.empty? ? nil : value.join(", ")
- end
- end
-
- ##
- # Iterates over the request headers
-
- def each
- if @header
- @header.each{|k, v|
- value = @header[k]
- yield(k, value.empty? ? nil : value.join(", "))
- }
- end
- end
-
- ##
- # The host this request is for
-
- def host
- return @forwarded_host || @host
- end
-
- ##
- # The port this request is for
-
- def port
- return @forwarded_port || @port
- end
-
- ##
- # The server name this request is for
-
- def server_name
- return @forwarded_server || @config[:ServerName]
- end
-
- ##
- # The client's IP address
-
- def remote_ip
- return self["client-ip"] || @forwarded_for || @peeraddr[3]
- end
-
- ##
- # Is this an SSL request?
-
- def ssl?
- return @request_uri.scheme == "https"
- end
-
- ##
- # Should the connection this request was made on be kept alive?
-
- def keep_alive?
- @keep_alive
- end
-
- def to_s # :nodoc:
- ret = @request_line.dup
- @raw_header.each{|line| ret << line }
- ret << CRLF
- ret << body if body
- ret
- end
-
- def fixup()
- begin
- body{|chunk| } # read remaining body
- rescue HTTPStatus::Error => ex
- @logger.error("HTTPRequest#fixup: #{ex.class} occured.")
- @keep_alive = false
- rescue => ex
- @logger.error(ex)
- @keep_alive = false
- end
- end
-
- # This method provides the metavariables defined by the revision 3
- # of "The WWW Common Gateway Interface Version 1.1"
- # http://Web.Golux.Com/coar/cgi/
-
- def meta_vars
- meta = Hash.new
-
- cl = self["Content-Length"]
- ct = self["Content-Type"]
- meta["CONTENT_LENGTH"] = cl if cl.to_i > 0
- meta["CONTENT_TYPE"] = ct.dup if ct
- meta["GATEWAY_INTERFACE"] = "CGI/1.1"
- meta["PATH_INFO"] = @path_info ? @path_info.dup : ""
- #meta["PATH_TRANSLATED"] = nil # no plan to be provided
- meta["QUERY_STRING"] = @query_string ? @query_string.dup : ""
- meta["REMOTE_ADDR"] = @peeraddr[3]
- meta["REMOTE_HOST"] = @peeraddr[2]
- #meta["REMOTE_IDENT"] = nil # no plan to be provided
- meta["REMOTE_USER"] = @user
- meta["REQUEST_METHOD"] = @request_method.dup
- meta["REQUEST_URI"] = @request_uri.to_s
- meta["SCRIPT_NAME"] = @script_name.dup
- meta["SERVER_NAME"] = @host
- meta["SERVER_PORT"] = @port.to_s
- meta["SERVER_PROTOCOL"] = "HTTP/" + @config[:HTTPVersion].to_s
- meta["SERVER_SOFTWARE"] = @config[:ServerSoftware].dup
-
- self.each{|key, val|
- next if /^content-type$/i =~ key
- next if /^content-length$/i =~ key
- name = "HTTP_" + key
- name.gsub!(/-/o, "_")
- name.upcase!
- meta[name] = val
- }
-
- meta
- end
-
- private
-
- MAX_URI_LENGTH = 2083 # :nodoc:
-
- def read_request_line(socket)
- @request_line = read_line(socket, MAX_URI_LENGTH) if socket
- if @request_line.bytesize >= MAX_URI_LENGTH and @request_line[-1, 1] != LF
- raise HTTPStatus::RequestURITooLarge
- end
- @request_time = Time.now
- raise HTTPStatus::EOFError unless @request_line
- if /^(\S+)\s+(\S++)(?:\s+HTTP\/(\d+\.\d+))?\r?\n/mo =~ @request_line
- @request_method = $1
- @unparsed_uri = $2
- @http_version = HTTPVersion.new($3 ? $3 : "0.9")
- else
- rl = @request_line.sub(/\x0d?\x0a\z/o, '')
- raise HTTPStatus::BadRequest, "bad Request-Line `#{rl}'."
- end
- end
-
- def read_header(socket)
- if socket
- while line = read_line(socket)
- break if /\A(#{CRLF}|#{LF})\z/om =~ line
- @raw_header << line
- end
- end
- @header = HTTPUtils::parse_header(@raw_header.join)
- end
-
- def parse_uri(str, scheme="http")
- if @config[:Escape8bitURI]
- str = HTTPUtils::escape8bit(str)
- end
- str.sub!(%r{\A/+}o, '/')
- uri = URI::parse(str)
- return uri if uri.absolute?
- if @forwarded_host
- host, port = @forwarded_host, @forwarded_port
- elsif self["host"]
- pattern = /\A(#{URI::REGEXP::PATTERN::HOST})(?::(\d+))?\z/n
- host, port = *self['host'].scan(pattern)[0]
- elsif @addr.size > 0
- host, port = @addr[2], @addr[1]
- else
- host, port = @config[:ServerName], @config[:Port]
- end
- uri.scheme = @forwarded_proto || scheme
- uri.host = host
- uri.port = port ? port.to_i : nil
- return URI::parse(uri.to_s)
- end
-
- def read_body(socket, block)
- return unless socket
- if tc = self['transfer-encoding']
- case tc
- when /chunked/io then read_chunked(socket, block)
- else raise HTTPStatus::NotImplemented, "Transfer-Encoding: #{tc}."
- end
- elsif self['content-length'] || @remaining_size
- @remaining_size ||= self['content-length'].to_i
- while @remaining_size > 0
- sz = [@buffer_size, @remaining_size].min
- break unless buf = read_data(socket, sz)
- @remaining_size -= buf.bytesize
- block.call(buf)
- end
- if @remaining_size > 0 && @socket.eof?
- raise HTTPStatus::BadRequest, "invalid body size."
- end
- elsif BODY_CONTAINABLE_METHODS.member?(@request_method)
- raise HTTPStatus::LengthRequired
- end
- return @body
- end
-
- def read_chunk_size(socket)
- line = read_line(socket)
- if /^([0-9a-fA-F]+)(?:;(\S+))?/ =~ line
- chunk_size = $1.hex
- chunk_ext = $2
- [ chunk_size, chunk_ext ]
- else
- raise HTTPStatus::BadRequest, "bad chunk `#{line}'."
- end
- end
-
- def read_chunked(socket, block)
- chunk_size, = read_chunk_size(socket)
- while chunk_size > 0
- data = read_data(socket, chunk_size) # read chunk-data
- if data.nil? || data.bytesize != chunk_size
- raise BadRequest, "bad chunk data size."
- end
- read_line(socket) # skip CRLF
- block.call(data)
- chunk_size, = read_chunk_size(socket)
- end
- read_header(socket) # trailer + CRLF
- @header.delete("transfer-encoding")
- @remaining_size = 0
- end
-
- def _read_data(io, method, *arg)
- begin
- WEBrick::Utils.timeout(@config[:RequestTimeout]){
- return io.__send__(method, *arg)
- }
- rescue Errno::ECONNRESET
- return nil
- rescue TimeoutError
- raise HTTPStatus::RequestTimeout
- end
- end
-
- def read_line(io, size=4096)
- _read_data(io, :gets, LF, size)
- end
-
- def read_data(io, size)
- _read_data(io, :read, size)
- end
-
- def parse_query()
- begin
- if @request_method == "GET" || @request_method == "HEAD"
- @query = HTTPUtils::parse_query(@query_string)
- elsif self['content-type'] =~ /^application\/x-www-form-urlencoded/
- @query = HTTPUtils::parse_query(body)
- elsif self['content-type'] =~ /^multipart\/form-data; boundary=(.+)/
- boundary = HTTPUtils::dequote($1)
- @query = HTTPUtils::parse_form_data(body, boundary)
- else
- @query = Hash.new
- end
- rescue => ex
- raise HTTPStatus::BadRequest, ex.message
- end
- end
-
- PrivateNetworkRegexp = /
- ^unknown$|
- ^((::ffff:)?127.0.0.1|::1)$|
- ^(::ffff:)?(10|172\.(1[6-9]|2[0-9]|3[01])|192\.168)\.
- /ixo
-
- # It's said that all X-Forwarded-* headers will contain more than one
- # (comma-separated) value if the original request already contained one of
- # these headers. Since we could use these values as Host header, we choose
- # the initial(first) value. (apr_table_mergen() adds new value after the
- # existing value with ", " prefix)
- def setup_forwarded_info
- if @forwarded_server = self["x-forwarded-server"]
- @forwarded_server = @forwarded_server.split(",", 2).first
- end
- @forwarded_proto = self["x-forwarded-proto"]
- if host_port = self["x-forwarded-host"]
- host_port = host_port.split(",", 2).first
- @forwarded_host, tmp = host_port.split(":", 2)
- @forwarded_port = (tmp || (@forwarded_proto == "https" ? 443 : 80)).to_i
- end
- if addrs = self["x-forwarded-for"]
- addrs = addrs.split(",").collect(&:strip)
- addrs.reject!{|ip| PrivateNetworkRegexp =~ ip }
- @forwarded_for = addrs.first
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/httpresponse.rb b/ruby_1_9_3/lib/webrick/httpresponse.rb
deleted file mode 100644
index 0d36c0747e..0000000000
--- a/ruby_1_9_3/lib/webrick/httpresponse.rb
+++ /dev/null
@@ -1,399 +0,0 @@
-#
-# httpresponse.rb -- HTTPResponse Class
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou
-# Copyright (c) 2002 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: httpresponse.rb,v 1.45 2003/07/11 11:02:25 gotoyuzo Exp $
-
-require 'time'
-require 'webrick/httpversion'
-require 'webrick/htmlutils'
-require 'webrick/httputils'
-require 'webrick/httpstatus'
-
-module WEBrick
- ##
- # An HTTP response.
-
- class HTTPResponse
- attr_reader :http_version, :status, :header
- attr_reader :cookies
- attr_accessor :reason_phrase
-
- ##
- # Body may be a String or IO subclass.
-
- attr_accessor :body
-
- attr_accessor :request_method, :request_uri, :request_http_version
- attr_accessor :filename
- attr_accessor :keep_alive
- attr_reader :config, :sent_size
-
- ##
- # Creates a new HTTP response object
-
- def initialize(config)
- @config = config
- @buffer_size = config[:OutputBufferSize]
- @logger = config[:Logger]
- @header = Hash.new
- @status = HTTPStatus::RC_OK
- @reason_phrase = nil
- @http_version = HTTPVersion::convert(@config[:HTTPVersion])
- @body = ''
- @keep_alive = true
- @cookies = []
- @request_method = nil
- @request_uri = nil
- @request_http_version = @http_version # temporary
- @chunked = false
- @filename = nil
- @sent_size = 0
- end
-
- ##
- # The response's HTTP status line
-
- def status_line
- "HTTP/#@http_version #@status #@reason_phrase #{CRLF}"
- end
-
- ##
- # Sets the response's status to the +status+ code
-
- def status=(status)
- @status = status
- @reason_phrase = HTTPStatus::reason_phrase(status)
- end
-
- ##
- # Retrieves the response header +field+
-
- def [](field)
- @header[field.downcase]
- end
-
- ##
- # Sets the response header +field+ to +value+
-
- def []=(field, value)
- @header[field.downcase] = value.to_s
- end
-
- ##
- # The content-length header
-
- def content_length
- if len = self['content-length']
- return Integer(len)
- end
- end
-
- ##
- # Sets the content-length header to +len+
-
- def content_length=(len)
- self['content-length'] = len.to_s
- end
-
- ##
- # The content-type header
-
- def content_type
- self['content-type']
- end
-
- ##
- # Sets the content-type header to +type+
-
- def content_type=(type)
- self['content-type'] = type
- end
-
- ##
- # Iterates over each header in the resopnse
-
- def each
- @header.each{|field, value| yield(field, value) }
- end
-
- ##
- # Will this response body be returned using chunked transfer-encoding?
-
- def chunked?
- @chunked
- end
-
- ##
- # Enables chunked transfer encoding.
-
- def chunked=(val)
- @chunked = val ? true : false
- end
-
- ##
- # Will this response's connection be kept alive?
-
- def keep_alive?
- @keep_alive
- end
-
- ##
- # Sends the response on +socket+
-
- def send_response(socket)
- begin
- setup_header()
- send_header(socket)
- send_body(socket)
- rescue Errno::EPIPE, Errno::ECONNRESET, Errno::ENOTCONN => ex
- @logger.debug(ex)
- @keep_alive = false
- rescue Exception => ex
- @logger.error(ex)
- @keep_alive = false
- end
- end
-
- ##
- # Sets up the headers for sending
-
- def setup_header()
- @reason_phrase ||= HTTPStatus::reason_phrase(@status)
- @header['server'] ||= @config[:ServerSoftware]
- @header['date'] ||= Time.now.httpdate
-
- # HTTP/0.9 features
- if @request_http_version < "1.0"
- @http_version = HTTPVersion.new("0.9")
- @keep_alive = false
- end
-
- # HTTP/1.0 features
- if @request_http_version < "1.1"
- if chunked?
- @chunked = false
- ver = @request_http_version.to_s
- msg = "chunked is set for an HTTP/#{ver} request. (ignored)"
- @logger.warn(msg)
- end
- end
-
- # Determine the message length (RFC2616 -- 4.4 Message Length)
- if @status == 304 || @status == 204 || HTTPStatus::info?(@status)
- @header.delete('content-length')
- @body = ""
- elsif chunked?
- @header["transfer-encoding"] = "chunked"
- @header.delete('content-length')
- elsif %r{^multipart/byteranges} =~ @header['content-type']
- @header.delete('content-length')
- elsif @header['content-length'].nil?
- unless @body.is_a?(IO)
- @header['content-length'] = @body ? @body.bytesize : 0
- end
- end
-
- # Keep-Alive connection.
- if @header['connection'] == "close"
- @keep_alive = false
- elsif keep_alive?
- if chunked? || @header['content-length']
- @header['connection'] = "Keep-Alive"
- else
- msg = "Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true"
- @logger.warn(msg)
- @header['connection'] = "close"
- @keep_alive = false
- end
- else
- @header['connection'] = "close"
- end
-
- # Location is a single absoluteURI.
- if location = @header['location']
- if @request_uri
- @header['location'] = @request_uri.merge(location)
- end
- end
- end
-
- ##
- # Sends the headers on +socket+
-
- def send_header(socket)
- if @http_version.major > 0
- data = status_line()
- @header.each{|key, value|
- tmp = key.gsub(/\bwww|^te$|\b\w/){ $&.upcase }
- data << "#{tmp}: #{value}" << CRLF
- }
- @cookies.each{|cookie|
- data << "Set-Cookie: " << cookie.to_s << CRLF
- }
- data << CRLF
- _write_data(socket, data)
- end
- end
-
- ##
- # Sends the body on +socket+
-
- def send_body(socket)
- case @body
- when IO then send_body_io(socket)
- else send_body_string(socket)
- end
- end
-
- def to_s # :nodoc:
- ret = ""
- send_response(ret)
- ret
- end
-
- ##
- # Redirects to +url+ with a WEBrick::HTTPStatus::Redirect +status+.
- #
- # Example:
- #
- # res.set_redirect WEBrick::HTTPStatus::TemporaryRedirect
-
- def set_redirect(status, url)
- @body = "<HTML><A HREF=\"#{url.to_s}\">#{url.to_s}</A>.</HTML>\n"
- @header['location'] = url.to_s
- raise status
- end
-
- ##
- # Creates an error page for exception +ex+ with an optional +backtrace+
-
- def set_error(ex, backtrace=false)
- case ex
- when HTTPStatus::Status
- @keep_alive = false if HTTPStatus::error?(ex.code)
- self.status = ex.code
- else
- @keep_alive = false
- self.status = HTTPStatus::RC_INTERNAL_SERVER_ERROR
- end
- @header['content-type'] = "text/html; charset=ISO-8859-1"
-
- if respond_to?(:create_error_page)
- create_error_page()
- return
- end
-
- if @request_uri
- host, port = @request_uri.host, @request_uri.port
- else
- host, port = @config[:ServerName], @config[:Port]
- end
-
- @body = ''
- @body << <<-_end_of_html_
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
-<HTML>
- <HEAD><TITLE>#{HTMLUtils::escape(@reason_phrase)}</TITLE></HEAD>
- <BODY>
- <H1>#{HTMLUtils::escape(@reason_phrase)}</H1>
- #{HTMLUtils::escape(ex.message)}
- <HR>
- _end_of_html_
-
- if backtrace && $DEBUG
- @body << "backtrace of `#{HTMLUtils::escape(ex.class.to_s)}' "
- @body << "#{HTMLUtils::escape(ex.message)}"
- @body << "<PRE>"
- ex.backtrace.each{|line| @body << "\t#{line}\n"}
- @body << "</PRE><HR>"
- end
-
- @body << <<-_end_of_html_
- <ADDRESS>
- #{HTMLUtils::escape(@config[:ServerSoftware])} at
- #{host}:#{port}
- </ADDRESS>
- </BODY>
-</HTML>
- _end_of_html_
- end
-
- private
-
- def send_body_io(socket)
- begin
- if @request_method == "HEAD"
- # do nothing
- elsif chunked?
- while buf = @body.read(@buffer_size)
- next if buf.empty?
- data = ""
- data << format("%x", buf.bytesize) << CRLF
- data << buf << CRLF
- _write_data(socket, data)
- @sent_size += buf.bytesize
- end
- _write_data(socket, "0#{CRLF}#{CRLF}")
- else
- size = @header['content-length'].to_i
- _send_file(socket, @body, 0, size)
- @sent_size = size
- end
- ensure
- @body.close
- end
- end
-
- def send_body_string(socket)
- if @request_method == "HEAD"
- # do nothing
- elsif chunked?
- body ? @body.bytesize : 0
- while buf = @body[@sent_size, @buffer_size]
- break if buf.empty?
- data = ""
- data << format("%x", buf.bytesize) << CRLF
- data << buf << CRLF
- _write_data(socket, data)
- @sent_size += buf.bytesize
- end
- _write_data(socket, "0#{CRLF}#{CRLF}")
- else
- if @body && @body.bytesize > 0
- _write_data(socket, @body)
- @sent_size = @body.bytesize
- end
- end
- end
-
- def _send_file(output, input, offset, size)
- while offset > 0
- sz = @buffer_size < size ? @buffer_size : size
- buf = input.read(sz)
- offset -= buf.bytesize
- end
-
- if size == 0
- while buf = input.read(@buffer_size)
- _write_data(output, buf)
- end
- else
- while size > 0
- sz = @buffer_size < size ? @buffer_size : size
- buf = input.read(sz)
- _write_data(output, buf)
- size -= buf.bytesize
- end
- end
- end
-
- def _write_data(socket, data)
- socket << data
- end
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/https.rb b/ruby_1_9_3/lib/webrick/https.rb
deleted file mode 100644
index abb428451f..0000000000
--- a/ruby_1_9_3/lib/webrick/https.rb
+++ /dev/null
@@ -1,64 +0,0 @@
-#
-# https.rb -- SSL/TLS enhancement for HTTPServer
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2001 GOTOU Yuuzou
-# Copyright (c) 2002 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: https.rb,v 1.15 2003/07/22 19:20:42 gotoyuzo Exp $
-
-require 'webrick/ssl'
-
-module WEBrick
- module Config
- HTTP.update(SSL)
- end
-
- class HTTPRequest
- attr_reader :cipher, :server_cert, :client_cert
-
- alias orig_parse parse
-
- def parse(socket=nil)
- if socket.respond_to?(:cert)
- @server_cert = socket.cert || @config[:SSLCertificate]
- @client_cert = socket.peer_cert
- @client_cert_chain = socket.peer_cert_chain
- @cipher = socket.cipher
- end
- orig_parse(socket)
- end
-
- alias orig_parse_uri parse_uri
-
- def parse_uri(str, scheme="https")
- if server_cert
- return orig_parse_uri(str, scheme)
- end
- return orig_parse_uri(str)
- end
- private :parse_uri
-
- alias orig_meta_vars meta_vars
-
- def meta_vars
- meta = orig_meta_vars
- if server_cert
- meta["HTTPS"] = "on"
- meta["SSL_SERVER_CERT"] = @server_cert.to_pem
- meta["SSL_CLIENT_CERT"] = @client_cert ? @client_cert.to_pem : ""
- if @client_cert_chain
- @client_cert_chain.each_with_index{|cert, i|
- meta["SSL_CLIENT_CERT_CHAIN_#{i}"] = cert.to_pem
- }
- end
- meta["SSL_CIPHER"] = @cipher[0]
- meta["SSL_PROTOCOL"] = @cipher[1]
- meta["SSL_CIPHER_USEKEYSIZE"] = @cipher[2].to_s
- meta["SSL_CIPHER_ALGKEYSIZE"] = @cipher[3].to_s
- end
- meta
- end
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/httpserver.rb b/ruby_1_9_3/lib/webrick/httpserver.rb
deleted file mode 100644
index ddf1ac7404..0000000000
--- a/ruby_1_9_3/lib/webrick/httpserver.rb
+++ /dev/null
@@ -1,264 +0,0 @@
-#
-# httpserver.rb -- HTTPServer Class
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou
-# Copyright (c) 2002 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: httpserver.rb,v 1.63 2002/10/01 17:16:32 gotoyuzo Exp $
-
-require 'webrick/server'
-require 'webrick/httputils'
-require 'webrick/httpstatus'
-require 'webrick/httprequest'
-require 'webrick/httpresponse'
-require 'webrick/httpservlet'
-require 'webrick/accesslog'
-
-module WEBrick
- class HTTPServerError < ServerError; end
-
- ##
- # An HTTP Server
-
- class HTTPServer < ::WEBrick::GenericServer
- ##
- # Creates a new HTTP server according to +config+
- #
- # An HTTP server uses the following attributes:
- #
- # :AccessLog:: An array of access logs. See WEBrick::AccessLog
- # :BindAddress:: Local address for the server to bind to
- # :DocumentRoot:: Root path to serve files from
- # :DocumentRootOptions:: Options for the default HTTPServlet::FileHandler
- # :HTTPVersion:: The HTTP version of this server
- # :Port:: Port to listen on
- # :RequestCallback:: Called with a request and response before each
- # request is serviced.
- # :RequestTimeout:: Maximum time to wait between requests
- # :ServerAlias:: Array of alternate names for this server for virtual
- # hosting
- # :ServerName:: Name for this server for virtual hosting
-
- def initialize(config={}, default=Config::HTTP)
- super(config, default)
- @http_version = HTTPVersion::convert(@config[:HTTPVersion])
-
- @mount_tab = MountTable.new
- if @config[:DocumentRoot]
- mount("/", HTTPServlet::FileHandler, @config[:DocumentRoot],
- @config[:DocumentRootOptions])
- end
-
- unless @config[:AccessLog]
- @config[:AccessLog] = [
- [ $stderr, AccessLog::COMMON_LOG_FORMAT ],
- [ $stderr, AccessLog::REFERER_LOG_FORMAT ]
- ]
- end
-
- @virtual_hosts = Array.new
- end
-
- ##
- # Processes requests on +sock+
-
- def run(sock)
- while true
- res = HTTPResponse.new(@config)
- req = HTTPRequest.new(@config)
- server = self
- begin
- timeout = @config[:RequestTimeout]
- while timeout > 0
- break if IO.select([sock], nil, nil, 0.5)
- timeout = 0 if @status != :Running
- timeout -= 0.5
- end
- raise HTTPStatus::EOFError if timeout <= 0
- raise HTTPStatus::EOFError if sock.eof?
- req.parse(sock)
- res.request_method = req.request_method
- res.request_uri = req.request_uri
- res.request_http_version = req.http_version
- res.keep_alive = req.keep_alive?
- server = lookup_server(req) || self
- if callback = server[:RequestCallback]
- callback.call(req, res)
- elsif callback = server[:RequestHandler]
- msg = ":RequestHandler is deprecated, please use :RequestCallback"
- @logger.warn(msg)
- callback.call(req, res)
- end
- server.service(req, res)
- rescue HTTPStatus::EOFError, HTTPStatus::RequestTimeout => ex
- res.set_error(ex)
- rescue HTTPStatus::Error => ex
- @logger.error(ex.message)
- res.set_error(ex)
- rescue HTTPStatus::Status => ex
- res.status = ex.code
- rescue StandardError => ex
- @logger.error(ex)
- res.set_error(ex, true)
- ensure
- if req.request_line
- if req.keep_alive? && res.keep_alive?
- req.fixup()
- end
- res.send_response(sock)
- server.access_log(@config, req, res)
- end
- end
- break if @http_version < "1.1"
- break unless req.keep_alive?
- break unless res.keep_alive?
- end
- end
-
- ##
- # Services +req+ and fills in +res+
-
- def service(req, res)
- if req.unparsed_uri == "*"
- if req.request_method == "OPTIONS"
- do_OPTIONS(req, res)
- raise HTTPStatus::OK
- end
- raise HTTPStatus::NotFound, "`#{req.unparsed_uri}' not found."
- end
-
- servlet, options, script_name, path_info = search_servlet(req.path)
- raise HTTPStatus::NotFound, "`#{req.path}' not found." unless servlet
- req.script_name = script_name
- req.path_info = path_info
- si = servlet.get_instance(self, *options)
- @logger.debug(format("%s is invoked.", si.class.name))
- si.service(req, res)
- end
-
- def do_OPTIONS(req, res)
- res["allow"] = "GET,HEAD,POST,OPTIONS"
- end
-
- ##
- # Mounts +servlet+ on +dir+ passing +options+ to the servlet at creation
- # time
-
- def mount(dir, servlet, *options)
- @logger.debug(sprintf("%s is mounted on %s.", servlet.inspect, dir))
- @mount_tab[dir] = [ servlet, options ]
- end
-
- ##
- # Mounts +proc+ or +block+ on +dir+ and calls it with a
- # WEBrick::HTTPRequest and WEBrick::HTTPResponse
-
- def mount_proc(dir, proc=nil, &block)
- proc ||= block
- raise HTTPServerError, "must pass a proc or block" unless proc
- mount(dir, HTTPServlet::ProcHandler.new(proc))
- end
-
- ##
- # Unmounts +dir+
-
- def unmount(dir)
- @logger.debug(sprintf("unmount %s.", dir))
- @mount_tab.delete(dir)
- end
- alias umount unmount
-
- ##
- # Finds a servlet for +path+
-
- def search_servlet(path)
- script_name, path_info = @mount_tab.scan(path)
- servlet, options = @mount_tab[script_name]
- if servlet
- [ servlet, options, script_name, path_info ]
- end
- end
-
- ##
- # Adds +server+ as a virtual host.
-
- def virtual_host(server)
- @virtual_hosts << server
- @virtual_hosts = @virtual_hosts.sort_by{|s|
- num = 0
- num -= 4 if s[:BindAddress]
- num -= 2 if s[:Port]
- num -= 1 if s[:ServerName]
- num
- }
- end
-
- ##
- # Finds the appropriate virtual host to handle +req+
-
- def lookup_server(req)
- @virtual_hosts.find{|s|
- (s[:BindAddress].nil? || req.addr[3] == s[:BindAddress]) &&
- (s[:Port].nil? || req.port == s[:Port]) &&
- ((s[:ServerName].nil? || req.host == s[:ServerName]) ||
- (!s[:ServerAlias].nil? && s[:ServerAlias].find{|h| h === req.host}))
- }
- end
-
- def access_log(config, req, res)
- param = AccessLog::setup_params(config, req, res)
- @config[:AccessLog].each{|logger, fmt|
- logger << AccessLog::format(fmt+"\n", param)
- }
- end
-
- class MountTable
- def initialize
- @tab = Hash.new
- compile
- end
-
- def [](dir)
- dir = normalize(dir)
- @tab[dir]
- end
-
- def []=(dir, val)
- dir = normalize(dir)
- @tab[dir] = val
- compile
- val
- end
-
- def delete(dir)
- dir = normalize(dir)
- res = @tab.delete(dir)
- compile
- res
- end
-
- def scan(path)
- @scanner =~ path
- [ $&, $' ]
- end
-
- private
-
- def compile
- k = @tab.keys
- k.sort!
- k.reverse!
- k.collect!{|path| Regexp.escape(path) }
- @scanner = Regexp.new("^(" + k.join("|") +")(?=/|$)")
- end
-
- def normalize(dir)
- ret = dir ? dir.dup : ""
- ret.sub!(%r|/+$|, "")
- ret
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/httpservlet.rb b/ruby_1_9_3/lib/webrick/httpservlet.rb
deleted file mode 100644
index ac7c022bd7..0000000000
--- a/ruby_1_9_3/lib/webrick/httpservlet.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-#
-# httpservlet.rb -- HTTPServlet Utility File
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou
-# Copyright (c) 2002 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: httpservlet.rb,v 1.21 2003/02/23 12:24:46 gotoyuzo Exp $
-
-require 'webrick/httpservlet/abstract'
-require 'webrick/httpservlet/filehandler'
-require 'webrick/httpservlet/cgihandler'
-require 'webrick/httpservlet/erbhandler'
-require 'webrick/httpservlet/prochandler'
-
-module WEBrick
- module HTTPServlet
- FileHandler.add_handler("cgi", CGIHandler)
- FileHandler.add_handler("rhtml", ERBHandler)
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/httpservlet/abstract.rb b/ruby_1_9_3/lib/webrick/httpservlet/abstract.rb
deleted file mode 100644
index 0d5c5ae48d..0000000000
--- a/ruby_1_9_3/lib/webrick/httpservlet/abstract.rb
+++ /dev/null
@@ -1,153 +0,0 @@
-#
-# httpservlet.rb -- HTTPServlet Module
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2000 TAKAHASHI Masayoshi, GOTOU Yuuzou
-# Copyright (c) 2002 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: abstract.rb,v 1.24 2003/07/11 11:16:46 gotoyuzo Exp $
-
-require 'thread'
-
-require 'webrick/htmlutils'
-require 'webrick/httputils'
-require 'webrick/httpstatus'
-
-module WEBrick
- module HTTPServlet
- class HTTPServletError < StandardError; end
-
- ##
- # AbstractServlet allows HTTP server modules to be reused across multiple
- # servers and allows encapsulation of functionality.
- #
- # By default a servlet will respond to GET, HEAD (through an alias to GET)
- # and OPTIONS requests.
- #
- # By default a new servlet is initialized for every request. A servlet
- # instance can be reused by overriding ::get_instance in the
- # AbstractServlet subclass.
- #
- # == A Simple Servlet
- #
- # class Simple < WEBrick::HTTPServlet::AbstractServlet
- # def do_GET request, response
- # status, content_type, body = do_stuff_with request
- #
- # response.status = status
- # response['Content-Type'] = content_type
- # response.body = body
- # end
- #
- # def do_stuff_with request
- # return 200, 'text/plain', 'you got a page'
- # end
- # end
- #
- # This servlet can be mounted on a server at a given path:
- #
- # server.mount '/simple', Simple
- #
- # == Servlet Configuration
- #
- # Servlets can be configured via initialize. The first argument is the
- # HTTP server the servlet is being initialized for.
- #
- # class Configureable < Simple
- # def initialize server, color, size
- # super server
- # @color = color
- # @size = size
- # end
- #
- # def do_stuff_with request
- # content = "<p " \
- # %q{style="color: #{@color}; font-size: #{@size}"} \
- # ">Hello, World!"
- #
- # return 200, "text/html", content
- # end
- # end
- #
- # This servlet must be provided two arguments at mount time:
- #
- # server.mount '/configurable', Configurable, 'red', '2em'
-
- class AbstractServlet
-
- ##
- # Factory for servlet instances that will handle a request from +server+
- # using +options+ from the mount point. By default a new servlet
- # instance is created for every call.
-
- def self.get_instance(server, *options)
- self.new(server, *options)
- end
-
- ##
- # Initializes a new servlet for +server+ using +options+ which are
- # stored as-is in +@options+. +@logger+ is also provided.
-
- def initialize(server, *options)
- @server = @config = server
- @logger = @server[:Logger]
- @options = options
- end
-
- ##
- # Dispatches to a +do_+ method based on +req+ if such a method is
- # available. (+do_GET+ for a GET request). Raises a MethodNotAllowed
- # exception if the method is not implemented.
-
- def service(req, res)
- method_name = "do_" + req.request_method.gsub(/-/, "_")
- if respond_to?(method_name)
- __send__(method_name, req, res)
- else
- raise HTTPStatus::MethodNotAllowed,
- "unsupported method `#{req.request_method}'."
- end
- end
-
- ##
- # Raises a NotFound exception
-
- def do_GET(req, res)
- raise HTTPStatus::NotFound, "not found."
- end
-
- ##
- # Dispatches to do_GET
-
- def do_HEAD(req, res)
- do_GET(req, res)
- end
-
- ##
- # Returns the allowed HTTP request methods
-
- def do_OPTIONS(req, res)
- m = self.methods.grep(/\Ado_([A-Z]+)\z/) {$1}
- m.sort!
- res["allow"] = m.join(",")
- end
-
- private
-
- ##
- # Redirects to a path ending in /
-
- def redirect_to_directory_uri(req, res)
- if req.path[-1] != ?/
- location = WEBrick::HTTPUtils.escape_path(req.path + "/")
- if req.query_string && req.query_string.bytesize > 0
- location << "?" << req.query_string
- end
- res.set_redirect(HTTPStatus::MovedPermanently, location)
- end
- end
- end
-
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/httpservlet/cgi_runner.rb b/ruby_1_9_3/lib/webrick/httpservlet/cgi_runner.rb
deleted file mode 100644
index 32ecb6fe00..0000000000
--- a/ruby_1_9_3/lib/webrick/httpservlet/cgi_runner.rb
+++ /dev/null
@@ -1,46 +0,0 @@
-#
-# cgi_runner.rb -- CGI launcher.
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2000 TAKAHASHI Masayoshi, GOTOU YUUZOU
-# Copyright (c) 2002 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: cgi_runner.rb,v 1.9 2002/09/25 11:33:15 gotoyuzo Exp $
-
-def sysread(io, size)
- buf = ""
- while size > 0
- tmp = io.sysread(size)
- buf << tmp
- size -= tmp.bytesize
- end
- return buf
-end
-
-STDIN.binmode
-
-len = sysread(STDIN, 8).to_i
-out = sysread(STDIN, len)
-STDOUT.reopen(open(out, "w"))
-
-len = sysread(STDIN, 8).to_i
-err = sysread(STDIN, len)
-STDERR.reopen(open(err, "w"))
-
-len = sysread(STDIN, 8).to_i
-dump = sysread(STDIN, len)
-hash = Marshal.restore(dump)
-ENV.keys.each{|name| ENV.delete(name) }
-hash.each{|k, v| ENV[k] = v if v }
-
-dir = File::dirname(ENV["SCRIPT_FILENAME"])
-Dir::chdir dir
-
-if ARGV[0]
- argv = ARGV.dup
- argv << ENV["SCRIPT_FILENAME"]
- exec(*argv)
- # NOTREACHED
-end
-exec ENV["SCRIPT_FILENAME"]
diff --git a/ruby_1_9_3/lib/webrick/httpservlet/cgihandler.rb b/ruby_1_9_3/lib/webrick/httpservlet/cgihandler.rb
deleted file mode 100644
index 1976ae6948..0000000000
--- a/ruby_1_9_3/lib/webrick/httpservlet/cgihandler.rb
+++ /dev/null
@@ -1,108 +0,0 @@
-#
-# cgihandler.rb -- CGIHandler Class
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou
-# Copyright (c) 2002 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: cgihandler.rb,v 1.27 2003/03/21 19:56:01 gotoyuzo Exp $
-
-require 'rbconfig'
-require 'tempfile'
-require 'webrick/config'
-require 'webrick/httpservlet/abstract'
-
-module WEBrick
- module HTTPServlet
-
- class CGIHandler < AbstractServlet
- Ruby = RbConfig.ruby
- CGIRunner = "\"#{Ruby}\" \"#{WEBrick::Config::LIBDIR}/httpservlet/cgi_runner.rb\""
-
- def initialize(server, name)
- super(server, name)
- @script_filename = name
- @tempdir = server[:TempDir]
- @cgicmd = "#{CGIRunner} #{server[:CGIInterpreter]}"
- end
-
- def do_GET(req, res)
- data = nil
- status = -1
-
- cgi_in = IO::popen(@cgicmd, "wb")
- cgi_out = Tempfile.new("webrick.cgiout.", @tempdir, mode: IO::BINARY)
- cgi_out.set_encoding("ASCII-8BIT")
- cgi_err = Tempfile.new("webrick.cgierr.", @tempdir, mode: IO::BINARY)
- cgi_err.set_encoding("ASCII-8BIT")
- begin
- cgi_in.sync = true
- meta = req.meta_vars
- meta["SCRIPT_FILENAME"] = @script_filename
- meta["PATH"] = @config[:CGIPathEnv]
- if /mswin|bccwin|mingw/ =~ RUBY_PLATFORM
- meta["SystemRoot"] = ENV["SystemRoot"]
- end
- dump = Marshal.dump(meta)
-
- cgi_in.write("%8d" % cgi_out.path.bytesize)
- cgi_in.write(cgi_out.path)
- cgi_in.write("%8d" % cgi_err.path.bytesize)
- cgi_in.write(cgi_err.path)
- cgi_in.write("%8d" % dump.bytesize)
- cgi_in.write(dump)
-
- if req.body and req.body.bytesize > 0
- cgi_in.write(req.body)
- end
- ensure
- cgi_in.close
- status = $?.exitstatus
- sleep 0.1 if /mswin|bccwin|mingw/ =~ RUBY_PLATFORM
- data = cgi_out.read
- cgi_out.close(true)
- if errmsg = cgi_err.read
- if errmsg.bytesize > 0
- @logger.error("CGIHandler: #{@script_filename}:\n" + errmsg)
- end
- end
- cgi_err.close(true)
- end
-
- if status != 0
- @logger.error("CGIHandler: #{@script_filename} exit with #{status}")
- end
-
- data = "" unless data
- raw_header, body = data.split(/^[\xd\xa]+/, 2)
- raise HTTPStatus::InternalServerError,
- "Premature end of script headers: #{@script_filename}" if body.nil?
-
- begin
- header = HTTPUtils::parse_header(raw_header)
- if /^(\d+)/ =~ header['status'][0]
- res.status = $1.to_i
- header.delete('status')
- end
- if header.has_key?('location')
- # RFC 3875 6.2.3, 6.2.4
- res.status = 302 unless (300...400) === res.status
- end
- if header.has_key?('set-cookie')
- header['set-cookie'].each{|k|
- res.cookies << Cookie.parse_set_cookie(k)
- }
- header.delete('set-cookie')
- end
- header.each{|key, val| res[key] = val.join(", ") }
- rescue => ex
- raise HTTPStatus::InternalServerError, ex.message
- end
- res.body = body
- end
- alias do_POST do_GET
- end
-
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/httpservlet/erbhandler.rb b/ruby_1_9_3/lib/webrick/httpservlet/erbhandler.rb
deleted file mode 100644
index 34b4b9e68b..0000000000
--- a/ruby_1_9_3/lib/webrick/httpservlet/erbhandler.rb
+++ /dev/null
@@ -1,87 +0,0 @@
-#
-# erbhandler.rb -- ERBHandler Class
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou
-# Copyright (c) 2002 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: erbhandler.rb,v 1.25 2003/02/24 19:25:31 gotoyuzo Exp $
-
-require 'webrick/httpservlet/abstract.rb'
-
-require 'erb'
-
-module WEBrick
- module HTTPServlet
-
- ##
- # ERBHandler evaluates an ERB file and returns the result. This handler
- # is automatically used if there are .rhtml files in a directory served by
- # the FileHandler.
- #
- # ERBHandler supports GET and POST methods.
- #
- # The ERB file is evaluated with the local variables +servlet_request+ and
- # +servlet_response+ which are a WEBrick::HTTPRequest and
- # WEBrick::HTTPResponse respectively.
- #
- # Example .rhtml file:
- #
- # Request to <%= servlet_request.request_uri %>
- #
- # Query params <%= servlet_request.query.inspect %>
-
- class ERBHandler < AbstractServlet
-
- ##
- # Creates a new ERBHandler on +server+ that will evaluate and serve the
- # ERB file +name+
-
- def initialize(server, name)
- super(server, name)
- @script_filename = name
- end
-
- ##
- # Handles GET requests
-
- def do_GET(req, res)
- unless defined?(ERB)
- @logger.warn "#{self.class}: ERB not defined."
- raise HTTPStatus::Forbidden, "ERBHandler cannot work."
- end
- begin
- data = open(@script_filename){|io| io.read }
- res.body = evaluate(ERB.new(data), req, res)
- res['content-type'] ||=
- HTTPUtils::mime_type(@script_filename, @config[:MimeTypes])
- rescue StandardError => ex
- raise
- rescue Exception => ex
- @logger.error(ex)
- raise HTTPStatus::InternalServerError, ex.message
- end
- end
-
- ##
- # Handles POST requests
-
- alias do_POST do_GET
-
- private
-
- ##
- # Evaluates +erb+ providing +servlet_request+ and +servlet_response+ as
- # local variables.
-
- def evaluate(erb, servlet_request, servlet_response)
- Module.new.module_eval{
- servlet_request.meta_vars
- servlet_request.query
- erb.result(binding)
- }
- end
- end
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/httpservlet/filehandler.rb b/ruby_1_9_3/lib/webrick/httpservlet/filehandler.rb
deleted file mode 100644
index 8736f5773a..0000000000
--- a/ruby_1_9_3/lib/webrick/httpservlet/filehandler.rb
+++ /dev/null
@@ -1,470 +0,0 @@
-#
-# filehandler.rb -- FileHandler Module
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou
-# Copyright (c) 2003 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: filehandler.rb,v 1.44 2003/06/07 01:34:51 gotoyuzo Exp $
-
-require 'thread'
-require 'time'
-
-require 'webrick/htmlutils'
-require 'webrick/httputils'
-require 'webrick/httpstatus'
-
-module WEBrick
- module HTTPServlet
-
- class DefaultFileHandler < AbstractServlet
- def initialize(server, local_path)
- super(server, local_path)
- @local_path = local_path
- end
-
- def do_GET(req, res)
- st = File::stat(@local_path)
- mtime = st.mtime
- res['etag'] = sprintf("%x-%x-%x", st.ino, st.size, st.mtime.to_i)
-
- if not_modified?(req, res, mtime, res['etag'])
- res.body = ''
- raise HTTPStatus::NotModified
- elsif req['range']
- make_partial_content(req, res, @local_path, st.size)
- raise HTTPStatus::PartialContent
- else
- mtype = HTTPUtils::mime_type(@local_path, @config[:MimeTypes])
- res['content-type'] = mtype
- res['content-length'] = st.size
- res['last-modified'] = mtime.httpdate
- res.body = open(@local_path, "rb")
- end
- end
-
- def not_modified?(req, res, mtime, etag)
- if ir = req['if-range']
- begin
- if Time.httpdate(ir) >= mtime
- return true
- end
- rescue
- if HTTPUtils::split_header_value(ir).member?(res['etag'])
- return true
- end
- end
- end
-
- if (ims = req['if-modified-since']) && Time.parse(ims) >= mtime
- return true
- end
-
- if (inm = req['if-none-match']) &&
- HTTPUtils::split_header_value(inm).member?(res['etag'])
- return true
- end
-
- return false
- end
-
- def make_partial_content(req, res, filename, filesize)
- mtype = HTTPUtils::mime_type(filename, @config[:MimeTypes])
- unless ranges = HTTPUtils::parse_range_header(req['range'])
- raise HTTPStatus::BadRequest,
- "Unrecognized range-spec: \"#{req['range']}\""
- end
- open(filename, "rb"){|io|
- if ranges.size > 1
- time = Time.now
- boundary = "#{time.sec}_#{time.usec}_#{Process::pid}"
- body = ''
- ranges.each{|range|
- first, last = prepare_range(range, filesize)
- next if first < 0
- io.pos = first
- content = io.read(last-first+1)
- body << "--" << boundary << CRLF
- body << "Content-Type: #{mtype}" << CRLF
- body << "Content-Range: bytes #{first}-#{last}/#{filesize}" << CRLF
- body << CRLF
- body << content
- body << CRLF
- }
- raise HTTPStatus::RequestRangeNotSatisfiable if body.empty?
- body << "--" << boundary << "--" << CRLF
- res["content-type"] = "multipart/byteranges; boundary=#{boundary}"
- res.body = body
- elsif range = ranges[0]
- first, last = prepare_range(range, filesize)
- raise HTTPStatus::RequestRangeNotSatisfiable if first < 0
- if last == filesize - 1
- content = io.dup
- content.pos = first
- else
- io.pos = first
- content = io.read(last-first+1)
- end
- res['content-type'] = mtype
- res['content-range'] = "bytes #{first}-#{last}/#{filesize}"
- res['content-length'] = last - first + 1
- res.body = content
- else
- raise HTTPStatus::BadRequest
- end
- }
- end
-
- def prepare_range(range, filesize)
- first = range.first < 0 ? filesize + range.first : range.first
- return -1, -1 if first < 0 || first >= filesize
- last = range.last < 0 ? filesize + range.last : range.last
- last = filesize - 1 if last >= filesize
- return first, last
- end
- end
-
- ##
- # Serves files from a directory
-
- class FileHandler < AbstractServlet
- HandlerTable = Hash.new
-
- ##
- # Allow custom handling of requests for files with +suffix+ by class
- # +handler+
-
- def self.add_handler(suffix, handler)
- HandlerTable[suffix] = handler
- end
-
- ##
- # Remove custom handling of requests for files with +suffix+
-
- def self.remove_handler(suffix)
- HandlerTable.delete(suffix)
- end
-
- ##
- # Creates a FileHandler servlet on +server+ that serves files starting
- # at directory +root+
- #
- # If +options+ is a Hash the following keys are allowed:
- #
- # :AcceptableLanguages:: Array of languages allowed for accept-language
- # :DirectoryCallback:: Allows preprocessing of directory requests
- # :FancyIndexing:: If true, show an index for directories
- # :FileCallback:: Allows preprocessing of file requests
- # :HandlerCallback:: Allows preprocessing of requests
- # :HandlerTable:: Maps file suffixes to file handlers.
- # DefaultFileHandler is used by default but any servlet
- # can be used.
- # :NondisclosureName:: Do not show files matching this array of globs
- # :UserDir:: Directory inside ~user to serve content from for /~user
- # requests. Only works if mounted on /
- #
- # If +options+ is true or false then +:FancyIndexing+ is enabled or
- # disabled respectively.
-
- def initialize(server, root, options={}, default=Config::FileHandler)
- @config = server.config
- @logger = @config[:Logger]
- @root = File.expand_path(root)
- if options == true || options == false
- options = { :FancyIndexing => options }
- end
- @options = default.dup.update(options)
- end
-
- def service(req, res)
- # if this class is mounted on "/" and /~username is requested.
- # we're going to override path informations before invoking service.
- if defined?(Etc) && @options[:UserDir] && req.script_name.empty?
- if %r|^(/~([^/]+))| =~ req.path_info
- script_name, user = $1, $2
- path_info = $'
- begin
- passwd = Etc::getpwnam(user)
- @root = File::join(passwd.dir, @options[:UserDir])
- req.script_name = script_name
- req.path_info = path_info
- rescue
- @logger.debug "#{self.class}#do_GET: getpwnam(#{user}) failed"
- end
- end
- end
- prevent_directory_traversal(req, res)
- super(req, res)
- end
-
- def do_GET(req, res)
- unless exec_handler(req, res)
- set_dir_list(req, res)
- end
- end
-
- def do_POST(req, res)
- unless exec_handler(req, res)
- raise HTTPStatus::NotFound, "`#{req.path}' not found."
- end
- end
-
- def do_OPTIONS(req, res)
- unless exec_handler(req, res)
- super(req, res)
- end
- end
-
- # ToDo
- # RFC2518: HTTP Extensions for Distributed Authoring -- WEBDAV
- #
- # PROPFIND PROPPATCH MKCOL DELETE PUT COPY MOVE
- # LOCK UNLOCK
-
- # RFC3253: Versioning Extensions to WebDAV
- # (Web Distributed Authoring and Versioning)
- #
- # VERSION-CONTROL REPORT CHECKOUT CHECK_IN UNCHECKOUT
- # MKWORKSPACE UPDATE LABEL MERGE ACTIVITY
-
- private
-
- def trailing_pathsep?(path)
- # check for trailing path separator:
- # File.dirname("/aaaa/bbbb/") #=> "/aaaa")
- # File.dirname("/aaaa/bbbb/x") #=> "/aaaa/bbbb")
- # File.dirname("/aaaa/bbbb") #=> "/aaaa")
- # File.dirname("/aaaa/bbbbx") #=> "/aaaa")
- return File.dirname(path) != File.dirname(path+"x")
- end
-
- def prevent_directory_traversal(req, res)
- # Preventing directory traversal on Windows platforms;
- # Backslashes (0x5c) in path_info are not interpreted as special
- # character in URI notation. So the value of path_info should be
- # normalize before accessing to the filesystem.
-
- # dirty hack for filesystem encoding; in nature, File.expand_path
- # should not be used for path normalization. [Bug #3345]
- path = req.path_info.dup.force_encoding(Encoding.find("filesystem"))
- if trailing_pathsep?(req.path_info)
- # File.expand_path removes the trailing path separator.
- # Adding a character is a workaround to save it.
- # File.expand_path("/aaa/") #=> "/aaa"
- # File.expand_path("/aaa/" + "x") #=> "/aaa/x"
- expanded = File.expand_path(path + "x")
- expanded.chop! # remove trailing "x"
- else
- expanded = File.expand_path(path)
- end
- expanded.force_encoding(req.path_info.encoding)
- req.path_info = expanded
- end
-
- def exec_handler(req, res)
- raise HTTPStatus::NotFound, "`#{req.path}' not found" unless @root
- if set_filename(req, res)
- handler = get_handler(req, res)
- call_callback(:HandlerCallback, req, res)
- h = handler.get_instance(@config, res.filename)
- h.service(req, res)
- return true
- end
- call_callback(:HandlerCallback, req, res)
- return false
- end
-
- def get_handler(req, res)
- suffix1 = (/\.(\w+)\z/ =~ res.filename) && $1.downcase
- if /\.(\w+)\.([\w\-]+)\z/ =~ res.filename
- if @options[:AcceptableLanguages].include?($2.downcase)
- suffix2 = $1.downcase
- end
- end
- handler_table = @options[:HandlerTable]
- return handler_table[suffix1] || handler_table[suffix2] ||
- HandlerTable[suffix1] || HandlerTable[suffix2] ||
- DefaultFileHandler
- end
-
- def set_filename(req, res)
- res.filename = @root.dup
- path_info = req.path_info.scan(%r|/[^/]*|)
-
- path_info.unshift("") # dummy for checking @root dir
- while base = path_info.first
- break if base == "/"
- break unless File.directory?(File.expand_path(res.filename + base))
- shift_path_info(req, res, path_info)
- call_callback(:DirectoryCallback, req, res)
- end
-
- if base = path_info.first
- if base == "/"
- if file = search_index_file(req, res)
- shift_path_info(req, res, path_info, file)
- call_callback(:FileCallback, req, res)
- return true
- end
- shift_path_info(req, res, path_info)
- elsif file = search_file(req, res, base)
- shift_path_info(req, res, path_info, file)
- call_callback(:FileCallback, req, res)
- return true
- else
- raise HTTPStatus::NotFound, "`#{req.path}' not found."
- end
- end
-
- return false
- end
-
- def check_filename(req, res, name)
- if nondisclosure_name?(name) || windows_ambiguous_name?(name)
- @logger.warn("the request refers nondisclosure name `#{name}'.")
- raise HTTPStatus::NotFound, "`#{req.path}' not found."
- end
- end
-
- def shift_path_info(req, res, path_info, base=nil)
- tmp = path_info.shift
- base = base || tmp
- req.path_info = path_info.join
- req.script_name << base
- res.filename = File.expand_path(res.filename + base)
- check_filename(req, res, File.basename(res.filename))
- end
-
- def search_index_file(req, res)
- @config[:DirectoryIndex].each{|index|
- if file = search_file(req, res, "/"+index)
- return file
- end
- }
- return nil
- end
-
- def search_file(req, res, basename)
- langs = @options[:AcceptableLanguages]
- path = res.filename + basename
- if File.file?(path)
- return basename
- elsif langs.size > 0
- req.accept_language.each{|lang|
- path_with_lang = path + ".#{lang}"
- if langs.member?(lang) && File.file?(path_with_lang)
- return basename + ".#{lang}"
- end
- }
- (langs - req.accept_language).each{|lang|
- path_with_lang = path + ".#{lang}"
- if File.file?(path_with_lang)
- return basename + ".#{lang}"
- end
- }
- end
- return nil
- end
-
- def call_callback(callback_name, req, res)
- if cb = @options[callback_name]
- cb.call(req, res)
- end
- end
-
- def windows_ambiguous_name?(name)
- return true if /[. ]+\z/ =~ name
- return true if /::\$DATA\z/ =~ name
- return false
- end
-
- def nondisclosure_name?(name)
- @options[:NondisclosureName].each{|pattern|
- if File.fnmatch(pattern, name, File::FNM_CASEFOLD)
- return true
- end
- }
- return false
- end
-
- def set_dir_list(req, res)
- redirect_to_directory_uri(req, res)
- unless @options[:FancyIndexing]
- raise HTTPStatus::Forbidden, "no access permission to `#{req.path}'"
- end
- local_path = res.filename
- list = Dir::entries(local_path).collect{|name|
- next if name == "." || name == ".."
- next if nondisclosure_name?(name)
- next if windows_ambiguous_name?(name)
- st = (File::stat(File.join(local_path, name)) rescue nil)
- if st.nil?
- [ name, nil, -1 ]
- elsif st.directory?
- [ name + "/", st.mtime, -1 ]
- else
- [ name, st.mtime, st.size ]
- end
- }
- list.compact!
-
- if d0 = req.query["N"]; idx = 0
- elsif d0 = req.query["M"]; idx = 1
- elsif d0 = req.query["S"]; idx = 2
- else d0 = "A" ; idx = 0
- end
- d1 = (d0 == "A") ? "D" : "A"
-
- if d0 == "A"
- list.sort!{|a,b| a[idx] <=> b[idx] }
- else
- list.sort!{|a,b| b[idx] <=> a[idx] }
- end
-
- res['content-type'] = "text/html"
-
- res.body = <<-_end_of_html_
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
-<HTML>
- <HEAD><TITLE>Index of #{HTMLUtils::escape(req.path)}</TITLE></HEAD>
- <BODY>
- <H1>Index of #{HTMLUtils::escape(req.path)}</H1>
- _end_of_html_
-
- res.body << "<PRE>\n"
- res.body << " <A HREF=\"?N=#{d1}\">Name</A> "
- res.body << "<A HREF=\"?M=#{d1}\">Last modified</A> "
- res.body << "<A HREF=\"?S=#{d1}\">Size</A>\n"
- res.body << "<HR>\n"
-
- list.unshift [ "..", File::mtime(local_path+"/.."), -1 ]
- list.each{ |name, time, size|
- if name == ".."
- dname = "Parent Directory"
- elsif name.bytesize > 25
- dname = name.sub(/^(.{23})(?:.*)/, '\1..')
- else
- dname = name
- end
- s = " <A HREF=\"#{HTTPUtils::escape(name)}\">#{HTMLUtils::escape(dname)}</A>"
- s << " " * (30 - dname.bytesize)
- s << (time ? time.strftime("%Y/%m/%d %H:%M ") : " " * 22)
- s << (size >= 0 ? size.to_s : "-") << "\n"
- res.body << s
- }
- res.body << "</PRE><HR>"
-
- res.body << <<-_end_of_html_
- <ADDRESS>
- #{HTMLUtils::escape(@config[:ServerSoftware])}<BR>
- at #{req.host}:#{req.port}
- </ADDRESS>
- </BODY>
-</HTML>
- _end_of_html_
- end
-
- end
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/httpservlet/prochandler.rb b/ruby_1_9_3/lib/webrick/httpservlet/prochandler.rb
deleted file mode 100644
index 2be3c854c1..0000000000
--- a/ruby_1_9_3/lib/webrick/httpservlet/prochandler.rb
+++ /dev/null
@@ -1,33 +0,0 @@
-#
-# prochandler.rb -- ProcHandler Class
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou
-# Copyright (c) 2002 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: prochandler.rb,v 1.7 2002/09/21 12:23:42 gotoyuzo Exp $
-
-require 'webrick/httpservlet/abstract.rb'
-
-module WEBrick
- module HTTPServlet
-
- class ProcHandler < AbstractServlet
- def get_instance(server, *options)
- self
- end
-
- def initialize(proc)
- @proc = proc
- end
-
- def do_GET(request, response)
- @proc.call(request, response)
- end
-
- alias do_POST do_GET
- end
-
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/httpstatus.rb b/ruby_1_9_3/lib/webrick/httpstatus.rb
deleted file mode 100644
index 9eee38a40f..0000000000
--- a/ruby_1_9_3/lib/webrick/httpstatus.rb
+++ /dev/null
@@ -1,184 +0,0 @@
-#--
-# httpstatus.rb -- HTTPStatus Class
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou
-# Copyright (c) 2002 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: httpstatus.rb,v 1.11 2003/03/24 20:18:55 gotoyuzo Exp $
-
-module WEBrick
-
- ##
- # This module is used to manager HTTP status codes.
- #
- # See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for more
- # information.
- module HTTPStatus
-
- ##
- # Root of the HTTP status class hierarchy
- class Status < StandardError
- def initialize(*args) # :nodoc:
- args[0] = AccessLog.escape(args[0]) unless args.empty?
- super(*args)
- end
- class << self
- attr_reader :code, :reason_phrase # :nodoc:
- end
-
- # Returns the HTTP status code
- def code() self::class::code end
-
- # Returns the HTTP status description
- def reason_phrase() self::class::reason_phrase end
-
- alias to_i code # :nodoc:
- end
-
- # Root of the HTTP info statuses
- class Info < Status; end
- # Root of the HTTP sucess statuses
- class Success < Status; end
- # Root of the HTTP redirect statuses
- class Redirect < Status; end
- # Root of the HTTP error statuses
- class Error < Status; end
- # Root of the HTTP client error statuses
- class ClientError < Error; end
- # Root of the HTTP server error statuses
- class ServerError < Error; end
-
- class EOFError < StandardError; end
-
- # HTTP status codes and descriptions
- StatusMessage = { # :nodoc:
- 100 => 'Continue',
- 101 => 'Switching Protocols',
- 200 => 'OK',
- 201 => 'Created',
- 202 => 'Accepted',
- 203 => 'Non-Authoritative Information',
- 204 => 'No Content',
- 205 => 'Reset Content',
- 206 => 'Partial Content',
- 300 => 'Multiple Choices',
- 301 => 'Moved Permanently',
- 302 => 'Found',
- 303 => 'See Other',
- 304 => 'Not Modified',
- 305 => 'Use Proxy',
- 307 => 'Temporary Redirect',
- 400 => 'Bad Request',
- 401 => 'Unauthorized',
- 402 => 'Payment Required',
- 403 => 'Forbidden',
- 404 => 'Not Found',
- 405 => 'Method Not Allowed',
- 406 => 'Not Acceptable',
- 407 => 'Proxy Authentication Required',
- 408 => 'Request Timeout',
- 409 => 'Conflict',
- 410 => 'Gone',
- 411 => 'Length Required',
- 412 => 'Precondition Failed',
- 413 => 'Request Entity Too Large',
- 414 => 'Request-URI Too Large',
- 415 => 'Unsupported Media Type',
- 416 => 'Request Range Not Satisfiable',
- 417 => 'Expectation Failed',
- 500 => 'Internal Server Error',
- 501 => 'Not Implemented',
- 502 => 'Bad Gateway',
- 503 => 'Service Unavailable',
- 504 => 'Gateway Timeout',
- 505 => 'HTTP Version Not Supported'
- }
-
- # Maps a status code to the corresponding Status class
- CodeToError = {} # :nodoc:
-
- # Creates a status or error class for each status code and
- # populates the CodeToError map.
- StatusMessage.each{|code, message|
- message.freeze
- var_name = message.gsub(/[ \-]/,'_').upcase
- err_name = message.gsub(/[ \-]/,'')
-
- case code
- when 100...200; parent = Info
- when 200...300; parent = Success
- when 300...400; parent = Redirect
- when 400...500; parent = ClientError
- when 500...600; parent = ServerError
- end
-
- const_set("RC_#{var_name}", code)
- err_class = Class.new(parent)
- err_class.instance_variable_set(:@code, code)
- err_class.instance_variable_set(:@reason_phrase, message)
- const_set(err_name, err_class)
- CodeToError[code] = err_class
- }
-
- ##
- # Returns the description corresponding to the HTTP status +code+
- #
- # WEBrick::HTTPStatus.reason_phrase 404
- # => "Not Found"
- def reason_phrase(code)
- StatusMessage[code.to_i]
- end
-
- ##
- # Is +code+ an informational status?
- def info?(code)
- code.to_i >= 100 and code.to_i < 200
- end
-
- ##
- # Is +code+ a successful status?
- def success?(code)
- code.to_i >= 200 and code.to_i < 300
- end
-
- ##
- # Is +code+ a redirection status?
- def redirect?(code)
- code.to_i >= 300 and code.to_i < 400
- end
-
- ##
- # Is +code+ an error status?
- def error?(code)
- code.to_i >= 400 and code.to_i < 600
- end
-
- ##
- # Is +code+ a client error status?
- def client_error?(code)
- code.to_i >= 400 and code.to_i < 500
- end
-
- ##
- # Is +code+ a server error status?
- def server_error?(code)
- code.to_i >= 500 and code.to_i < 600
- end
-
- ##
- # Returns the status class corresponding to +code+
- #
- # WEBrick::HTTPStatus[302]
- # => WEBrick::HTTPStatus::NotFound
- #
- def self.[](code)
- CodeToError[code]
- end
-
- module_function :reason_phrase
- module_function :info?, :success?, :redirect?, :error?
- module_function :client_error?, :server_error?
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/httputils.rb b/ruby_1_9_3/lib/webrick/httputils.rb
deleted file mode 100644
index f029dacb56..0000000000
--- a/ruby_1_9_3/lib/webrick/httputils.rb
+++ /dev/null
@@ -1,392 +0,0 @@
-#
-# httputils.rb -- HTTPUtils Module
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou
-# Copyright (c) 2002 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: httputils.rb,v 1.34 2003/06/05 21:34:08 gotoyuzo Exp $
-
-require 'socket'
-require 'tempfile'
-
-module WEBrick
- CR = "\x0d"
- LF = "\x0a"
- CRLF = "\x0d\x0a"
-
- module HTTPUtils
-
- def normalize_path(path)
- raise "abnormal path `#{path}'" if path[0] != ?/
- ret = path.dup
-
- ret.gsub!(%r{/+}o, '/') # // => /
- while ret.sub!(%r'/\.(?:/|\Z)', '/'); end # /. => /
- while ret.sub!(%r'/(?!\.\./)[^/]+/\.\.(?:/|\Z)', '/'); end # /foo/.. => /foo
-
- raise "abnormal path `#{path}'" if %r{/\.\.(/|\Z)} =~ ret
- ret
- end
- module_function :normalize_path
-
- #####
-
- DefaultMimeTypes = {
- "ai" => "application/postscript",
- "asc" => "text/plain",
- "avi" => "video/x-msvideo",
- "bin" => "application/octet-stream",
- "bmp" => "image/bmp",
- "class" => "application/octet-stream",
- "cer" => "application/pkix-cert",
- "crl" => "application/pkix-crl",
- "crt" => "application/x-x509-ca-cert",
- #"crl" => "application/x-pkcs7-crl",
- "css" => "text/css",
- "dms" => "application/octet-stream",
- "doc" => "application/msword",
- "dvi" => "application/x-dvi",
- "eps" => "application/postscript",
- "etx" => "text/x-setext",
- "exe" => "application/octet-stream",
- "gif" => "image/gif",
- "htm" => "text/html",
- "html" => "text/html",
- "jpe" => "image/jpeg",
- "jpeg" => "image/jpeg",
- "jpg" => "image/jpeg",
- "lha" => "application/octet-stream",
- "lzh" => "application/octet-stream",
- "mov" => "video/quicktime",
- "mpe" => "video/mpeg",
- "mpeg" => "video/mpeg",
- "mpg" => "video/mpeg",
- "pbm" => "image/x-portable-bitmap",
- "pdf" => "application/pdf",
- "pgm" => "image/x-portable-graymap",
- "png" => "image/png",
- "pnm" => "image/x-portable-anymap",
- "ppm" => "image/x-portable-pixmap",
- "ppt" => "application/vnd.ms-powerpoint",
- "ps" => "application/postscript",
- "qt" => "video/quicktime",
- "ras" => "image/x-cmu-raster",
- "rb" => "text/plain",
- "rd" => "text/plain",
- "rtf" => "application/rtf",
- "sgm" => "text/sgml",
- "sgml" => "text/sgml",
- "tif" => "image/tiff",
- "tiff" => "image/tiff",
- "txt" => "text/plain",
- "xbm" => "image/x-xbitmap",
- "xhtml" => "text/html",
- "xls" => "application/vnd.ms-excel",
- "xml" => "text/xml",
- "xpm" => "image/x-xpixmap",
- "xwd" => "image/x-xwindowdump",
- "zip" => "application/zip",
- }
-
- # Load Apache compatible mime.types file.
- def load_mime_types(file)
- open(file){ |io|
- hash = Hash.new
- io.each{ |line|
- next if /^#/ =~ line
- line.chomp!
- mimetype, ext0 = line.split(/\s+/, 2)
- next unless ext0
- next if ext0.empty?
- ext0.split(/\s+/).each{ |ext| hash[ext] = mimetype }
- }
- hash
- }
- end
- module_function :load_mime_types
-
- def mime_type(filename, mime_tab)
- suffix1 = (/\.(\w+)$/ =~ filename && $1.downcase)
- suffix2 = (/\.(\w+)\.[\w\-]+$/ =~ filename && $1.downcase)
- mime_tab[suffix1] || mime_tab[suffix2] || "application/octet-stream"
- end
- module_function :mime_type
-
- #####
-
- def parse_header(raw)
- header = Hash.new([].freeze)
- field = nil
- raw.each_line{|line|
- case line
- when /^([A-Za-z0-9!\#$%&'*+\-.^_`|~]+):\s*(.*?)\s*\z/om
- field, value = $1, $2
- field.downcase!
- header[field] = [] unless header.has_key?(field)
- header[field] << value
- when /^\s+(.*?)\s*\z/om
- value = $1
- unless field
- raise HTTPStatus::BadRequest, "bad header '#{line}'."
- end
- header[field][-1] << " " << value
- else
- raise HTTPStatus::BadRequest, "bad header '#{line}'."
- end
- }
- header.each{|key, values|
- values.each{|value|
- value.strip!
- value.gsub!(/\s+/, " ")
- }
- }
- header
- end
- module_function :parse_header
-
- def split_header_value(str)
- str.scan(%r'\G((?:"(?:\\.|[^"])+?"|[^",]+)+)
- (?:,\s*|\Z)'xn).flatten
- end
- module_function :split_header_value
-
- def parse_range_header(ranges_specifier)
- if /^bytes=(.*)/ =~ ranges_specifier
- byte_range_set = split_header_value($1)
- byte_range_set.collect{|range_spec|
- case range_spec
- when /^(\d+)-(\d+)/ then $1.to_i .. $2.to_i
- when /^(\d+)-/ then $1.to_i .. -1
- when /^-(\d+)/ then -($1.to_i) .. -1
- else return nil
- end
- }
- end
- end
- module_function :parse_range_header
-
- def parse_qvalues(value)
- tmp = []
- if value
- parts = value.split(/,\s*/)
- parts.each {|part|
- if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
- val = m[1]
- q = (m[2] or 1).to_f
- tmp.push([val, q])
- end
- }
- tmp = tmp.sort_by{|val, q| -q}
- tmp.collect!{|val, q| val}
- end
- return tmp
- end
- module_function :parse_qvalues
-
- #####
-
- def dequote(str)
- ret = (/\A"(.*)"\Z/ =~ str) ? $1 : str.dup
- ret.gsub!(/\\(.)/, "\\1")
- ret
- end
- module_function :dequote
-
- def quote(str)
- '"' << str.gsub(/[\\\"]/o, "\\\1") << '"'
- end
- module_function :quote
-
- #####
-
- class FormData < String
- EmptyRawHeader = [].freeze
- EmptyHeader = {}.freeze
-
- attr_accessor :name, :filename, :next_data
- protected :next_data
-
- def initialize(*args)
- @name = @filename = @next_data = nil
- if args.empty?
- @raw_header = []
- @header = nil
- super("")
- else
- @raw_header = EmptyRawHeader
- @header = EmptyHeader
- super(args.shift)
- unless args.empty?
- @next_data = self.class.new(*args)
- end
- end
- end
-
- def [](*key)
- begin
- @header[key[0].downcase].join(", ")
- rescue StandardError, NameError
- super
- end
- end
-
- def <<(str)
- if @header
- super
- elsif str == CRLF
- @header = HTTPUtils::parse_header(@raw_header.join)
- if cd = self['content-disposition']
- if /\s+name="(.*?)"/ =~ cd then @name = $1 end
- if /\s+filename="(.*?)"/ =~ cd then @filename = $1 end
- end
- else
- @raw_header << str
- end
- self
- end
-
- def append_data(data)
- tmp = self
- while tmp
- unless tmp.next_data
- tmp.next_data = data
- break
- end
- tmp = tmp.next_data
- end
- self
- end
-
- def each_data
- tmp = self
- while tmp
- next_data = tmp.next_data
- yield(tmp)
- tmp = next_data
- end
- end
-
- def list
- ret = []
- each_data{|data|
- ret << data.to_s
- }
- ret
- end
-
- alias :to_ary :list
-
- def to_s
- String.new(self)
- end
- end
-
- def parse_query(str)
- query = Hash.new
- if str
- str.split(/[&;]/).each{|x|
- next if x.empty?
- key, val = x.split(/=/,2)
- key = unescape_form(key)
- val = unescape_form(val.to_s)
- val = FormData.new(val)
- val.name = key
- if query.has_key?(key)
- query[key].append_data(val)
- next
- end
- query[key] = val
- }
- end
- query
- end
- module_function :parse_query
-
- def parse_form_data(io, boundary)
- boundary_regexp = /\A--#{Regexp.quote(boundary)}(--)?#{CRLF}\z/
- form_data = Hash.new
- return form_data unless io
- data = nil
- io.each_line{|line|
- if boundary_regexp =~ line
- if data
- data.chop!
- key = data.name
- if form_data.has_key?(key)
- form_data[key].append_data(data)
- else
- form_data[key] = data
- end
- end
- data = FormData.new
- next
- else
- if data
- data << line
- end
- end
- }
- return form_data
- end
- module_function :parse_form_data
-
- #####
-
- reserved = ';/?:@&=+$,'
- num = '0123456789'
- lowalpha = 'abcdefghijklmnopqrstuvwxyz'
- upalpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
- mark = '-_.!~*\'()'
- unreserved = num + lowalpha + upalpha + mark
- control = (0x0..0x1f).collect{|c| c.chr }.join + "\x7f"
- space = " "
- delims = '<>#%"'
- unwise = '{}|\\^[]`'
- nonascii = (0x80..0xff).collect{|c| c.chr }.join
-
- module_function
-
- def _make_regex(str) /([#{Regexp.escape(str)}])/n end
- def _make_regex!(str) /([^#{Regexp.escape(str)}])/n end
- def _escape(str, regex) str.gsub(regex){ "%%%02X" % $1.ord } end
- def _unescape(str, regex) str.gsub(regex){ $1.hex.chr } end
-
- UNESCAPED = _make_regex(control+space+delims+unwise+nonascii)
- UNESCAPED_FORM = _make_regex(reserved+control+delims+unwise+nonascii)
- NONASCII = _make_regex(nonascii)
- ESCAPED = /%([0-9a-fA-F]{2})/
- UNESCAPED_PCHAR = _make_regex!(unreserved+":@&=+$,")
-
- def escape(str)
- _escape(str, UNESCAPED)
- end
-
- def unescape(str)
- _unescape(str, ESCAPED)
- end
-
- def escape_form(str)
- ret = _escape(str, UNESCAPED_FORM)
- ret.gsub!(/ /, "+")
- ret
- end
-
- def unescape_form(str)
- _unescape(str.gsub(/\+/, " "), ESCAPED)
- end
-
- def escape_path(str)
- result = ""
- str.scan(%r{/([^/]*)}).each{|i|
- result << "/" << _escape(i[0], UNESCAPED_PCHAR)
- }
- return result
- end
-
- def escape8bit(str)
- _escape(str, NONASCII)
- end
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/httpversion.rb b/ruby_1_9_3/lib/webrick/httpversion.rb
deleted file mode 100644
index 5cf0ee400d..0000000000
--- a/ruby_1_9_3/lib/webrick/httpversion.rb
+++ /dev/null
@@ -1,49 +0,0 @@
-#--
-# HTTPVersion.rb -- presentation of HTTP version
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2002 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: httpversion.rb,v 1.5 2002/09/21 12:23:37 gotoyuzo Exp $
-
-module WEBrick
- class HTTPVersion
- include Comparable
-
- attr_accessor :major, :minor
-
- def self.convert(version)
- version.is_a?(self) ? version : new(version)
- end
-
- def initialize(version)
- case version
- when HTTPVersion
- @major, @minor = version.major, version.minor
- when String
- if /^(\d+)\.(\d+)$/ =~ version
- @major, @minor = $1.to_i, $2.to_i
- end
- end
- if @major.nil? || @minor.nil?
- raise ArgumentError,
- format("cannot convert %s into %s", version.class, self.class)
- end
- end
-
- def <=>(other)
- unless other.is_a?(self.class)
- other = self.class.new(other)
- end
- if (ret = @major <=> other.major) == 0
- return @minor <=> other.minor
- end
- return ret
- end
-
- def to_s
- format("%d.%d", @major, @minor)
- end
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/log.rb b/ruby_1_9_3/lib/webrick/log.rb
deleted file mode 100644
index 546e52700b..0000000000
--- a/ruby_1_9_3/lib/webrick/log.rb
+++ /dev/null
@@ -1,136 +0,0 @@
-#--
-# log.rb -- Log Class
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou
-# Copyright (c) 2002 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: log.rb,v 1.26 2002/10/06 17:06:10 gotoyuzo Exp $
-
-module WEBrick
-
- ##
- # A generic logging class
-
- class BasicLog
- # log-level constants
- FATAL, ERROR, WARN, INFO, DEBUG = 1, 2, 3, 4, 5
-
- # log-level, messages above this level will be logged
- attr_accessor :level
-
- ##
- # Initializes a new logger for +log_file+ that outputs messages at +level+
- # or higher. +log_file+ can be a filename, an IO-like object that
- # responds to #<< or nil which outputs to $stderr.
- #
- # If no level is given INFO is chosen by default
-
- def initialize(log_file=nil, level=nil)
- @level = level || INFO
- case log_file
- when String
- @log = open(log_file, "a+")
- @log.sync = true
- @opened = true
- when NilClass
- @log = $stderr
- else
- @log = log_file # requires "<<". (see BasicLog#log)
- end
- end
-
- ##
- # Closes the logger (also closes the log device associated to the logger)
- def close
- @log.close if @opened
- @log = nil
- end
-
- ##
- # Logs +data+ at +level+ if the given level is above the current log
- # level.
-
- def log(level, data)
- if @log && level <= @level
- data += "\n" if /\n\Z/ !~ data
- @log << data
- end
- end
-
- ##
- # Synonym for log(INFO, obj.to_s)
- def <<(obj)
- log(INFO, obj.to_s)
- end
-
- # Shortcut for logging a FATAL message
- def fatal(msg) log(FATAL, "FATAL " << format(msg)); end
- # Shortcut for logging an ERROR message
- def error(msg) log(ERROR, "ERROR " << format(msg)); end
- # Shortcut for logging a WARN message
- def warn(msg) log(WARN, "WARN " << format(msg)); end
- # Shortcut for logging an INFO message
- def info(msg) log(INFO, "INFO " << format(msg)); end
- # Shortcut for logging a DEBUG message
- def debug(msg) log(DEBUG, "DEBUG " << format(msg)); end
-
- # Will the logger output FATAL messages?
- def fatal?; @level >= FATAL; end
- # Will the logger output ERROR messages?
- def error?; @level >= ERROR; end
- # Will the logger output WARN messages?
- def warn?; @level >= WARN; end
- # Will the logger output INFO messages?
- def info?; @level >= INFO; end
- # Will the logger output DEBUG messages?
- def debug?; @level >= DEBUG; end
-
- private
-
- ##
- # Formats +arg+ for the logger
- #
- # * If +arg+ is an Exception, it will format the error message and
- # the back trace.
- # * If +arg+ responds to #to_str, it will return it.
- # * Otherwise it will return +arg+.inspect.
- def format(arg)
- if arg.is_a?(Exception)
- "#{arg.class}: #{arg.message}\n\t" <<
- arg.backtrace.join("\n\t") << "\n"
- elsif arg.respond_to?(:to_str)
- arg.to_str
- else
- arg.inspect
- end
- end
- end
-
- ##
- # A logging class that prepends a timestamp to each message.
-
- class Log < BasicLog
- # Format of the timestamp which is applied to each logged line. The
- # default is <tt>"[%Y-%m-%d %H:%M:%S]"</tt>
- attr_accessor :time_format
-
- ##
- # Same as BasicLog#initialize
- #
- # You can set the timestamp format through #time_format
- def initialize(log_file=nil, level=nil)
- super(log_file, level)
- @time_format = "[%Y-%m-%d %H:%M:%S]"
- end
-
- ##
- # Same as BasicLog#log
- def log(level, data)
- tmp = Time.now.strftime(@time_format)
- tmp << " " << data
- super(level, tmp)
- end
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/server.rb b/ruby_1_9_3/lib/webrick/server.rb
deleted file mode 100644
index 30f4dc3143..0000000000
--- a/ruby_1_9_3/lib/webrick/server.rb
+++ /dev/null
@@ -1,218 +0,0 @@
-#
-# server.rb -- GenericServer Class
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2000, 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou
-# Copyright (c) 2002 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: server.rb,v 1.62 2003/07/22 19:20:43 gotoyuzo Exp $
-
-require 'thread'
-require 'socket'
-require 'webrick/config'
-require 'webrick/log'
-
-module WEBrick
-
- class ServerError < StandardError; end
-
- class SimpleServer
- def SimpleServer.start
- yield
- end
- end
-
- ##
- # A generic module for daemonizing a process
-
- class Daemon
-
- ##
- # Performs the standard operations for daemonizing a process. Runs a
- # block, if given.
-
- def Daemon.start
- exit!(0) if fork
- Process::setsid
- exit!(0) if fork
- Dir::chdir("/")
- File::umask(0)
- STDIN.reopen("/dev/null")
- STDOUT.reopen("/dev/null", "w")
- STDERR.reopen("/dev/null", "w")
- yield if block_given?
- end
- end
-
- class GenericServer
- attr_reader :status, :config, :logger, :tokens, :listeners
-
- def initialize(config={}, default=Config::General)
- @config = default.dup.update(config)
- @status = :Stop
- @config[:Logger] ||= Log::new
- @logger = @config[:Logger]
-
- @tokens = SizedQueue.new(@config[:MaxClients])
- @config[:MaxClients].times{ @tokens.push(nil) }
-
- webrickv = WEBrick::VERSION
- rubyv = "#{RUBY_VERSION} (#{RUBY_RELEASE_DATE}) [#{RUBY_PLATFORM}]"
- @logger.info("WEBrick #{webrickv}")
- @logger.info("ruby #{rubyv}")
-
- @listeners = []
- unless @config[:DoNotListen]
- if @config[:Listen]
- warn(":Listen option is deprecated; use GenericServer#listen")
- end
- listen(@config[:BindAddress], @config[:Port])
- if @config[:Port] == 0
- @config[:Port] = @listeners[0].addr[1]
- end
- end
- end
-
- def [](key)
- @config[key]
- end
-
- def listen(address, port)
- @listeners += Utils::create_listeners(address, port, @logger)
- end
-
- def start(&block)
- raise ServerError, "already started." if @status != :Stop
- server_type = @config[:ServerType] || SimpleServer
-
- server_type.start{
- @logger.info \
- "#{self.class}#start: pid=#{$$} port=#{@config[:Port]}"
- call_callback(:StartCallback)
-
- thgroup = ThreadGroup.new
- @status = :Running
- while @status == :Running
- begin
- if svrs = IO.select(@listeners, nil, nil, 2.0)
- svrs[0].each{|svr|
- @tokens.pop # blocks while no token is there.
- if sock = accept_client(svr)
- sock.do_not_reverse_lookup = config[:DoNotReverseLookup]
- th = start_thread(sock, &block)
- th[:WEBrickThread] = true
- thgroup.add(th)
- else
- @tokens.push(nil)
- end
- }
- end
- rescue Errno::EBADF, IOError => ex
- # if the listening socket was closed in GenericServer#shutdown,
- # IO::select raise it.
- rescue Exception => ex
- msg = "#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}"
- @logger.error msg
- end
- end
-
- @logger.info "going to shutdown ..."
- thgroup.list.each{|th| th.join if th[:WEBrickThread] }
- call_callback(:StopCallback)
- @logger.info "#{self.class}#start done."
- @status = :Stop
- }
- end
-
- def stop
- if @status == :Running
- @status = :Shutdown
- end
- end
-
- def shutdown
- stop
- @listeners.each{|s|
- if @logger.debug?
- addr = s.addr
- @logger.debug("close TCPSocket(#{addr[2]}, #{addr[1]})")
- end
- begin
- s.shutdown
- rescue Errno::ENOTCONN
- # when `Errno::ENOTCONN: Socket is not connected' on some platforms,
- # call #close instead of #shutdown.
- # (ignore @config[:ShutdownSocketWithoutClose])
- s.close
- else
- unless @config[:ShutdownSocketWithoutClose]
- s.close
- end
- end
- }
- @listeners.clear
- end
-
- def run(sock)
- @logger.fatal "run() must be provided by user."
- end
-
- private
-
- def accept_client(svr)
- sock = nil
- begin
- sock = svr.accept
- sock.sync = true
- Utils::set_non_blocking(sock)
- Utils::set_close_on_exec(sock)
- rescue Errno::ECONNRESET, Errno::ECONNABORTED,
- Errno::EPROTO, Errno::EINVAL => ex
- rescue Exception => ex
- msg = "#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}"
- @logger.error msg
- end
- return sock
- end
-
- def start_thread(sock, &block)
- Thread.start{
- begin
- Thread.current[:WEBrickSocket] = sock
- begin
- addr = sock.peeraddr
- @logger.debug "accept: #{addr[3]}:#{addr[1]}"
- rescue SocketError
- @logger.debug "accept: <address unknown>"
- raise
- end
- call_callback(:AcceptCallback, sock)
- block ? block.call(sock) : run(sock)
- rescue Errno::ENOTCONN
- @logger.debug "Errno::ENOTCONN raised"
- rescue ServerError => ex
- msg = "#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}"
- @logger.error msg
- rescue Exception => ex
- @logger.error ex
- ensure
- @tokens.push(nil)
- Thread.current[:WEBrickSocket] = nil
- if addr
- @logger.debug "close: #{addr[3]}:#{addr[1]}"
- else
- @logger.debug "close: <address unknown>"
- end
- sock.close
- end
- }
- end
-
- def call_callback(callback_name, *args)
- if cb = @config[callback_name]
- cb.call(*args)
- end
- end
- end # end of GenericServer
-end
diff --git a/ruby_1_9_3/lib/webrick/ssl.rb b/ruby_1_9_3/lib/webrick/ssl.rb
deleted file mode 100644
index b3cc7aaf01..0000000000
--- a/ruby_1_9_3/lib/webrick/ssl.rb
+++ /dev/null
@@ -1,127 +0,0 @@
-#
-# ssl.rb -- SSL/TLS enhancement for GenericServer
-#
-# Copyright (c) 2003 GOTOU Yuuzou All rights reserved.
-#
-# $Id$
-
-require 'webrick'
-require 'openssl'
-
-module WEBrick
- module Config
- svrsoft = General[:ServerSoftware]
- osslv = ::OpenSSL::OPENSSL_VERSION.split[1]
- SSL = {
- :ServerSoftware => "#{svrsoft} OpenSSL/#{osslv}",
- :SSLEnable => false,
- :SSLCertificate => nil,
- :SSLPrivateKey => nil,
- :SSLClientCA => nil,
- :SSLExtraChainCert => nil,
- :SSLCACertificateFile => nil,
- :SSLCACertificatePath => nil,
- :SSLCertificateStore => nil,
- :SSLVerifyClient => ::OpenSSL::SSL::VERIFY_NONE,
- :SSLVerifyDepth => nil,
- :SSLVerifyCallback => nil, # custom verification
- :SSLTimeout => nil,
- :SSLOptions => nil,
- :SSLStartImmediately => true,
- # Must specify if you use auto generated certificate.
- :SSLCertName => nil,
- :SSLCertComment => "Generated by Ruby/OpenSSL"
- }
- General.update(SSL)
- end
-
- module Utils
- def create_self_signed_cert(bits, cn, comment)
- rsa = OpenSSL::PKey::RSA.new(bits){|p, n|
- case p
- when 0; $stderr.putc "." # BN_generate_prime
- when 1; $stderr.putc "+" # BN_generate_prime
- when 2; $stderr.putc "*" # searching good prime,
- # n = #of try,
- # but also data from BN_generate_prime
- when 3; $stderr.putc "\n" # found good prime, n==0 - p, n==1 - q,
- # but also data from BN_generate_prime
- else; $stderr.putc "*" # BN_generate_prime
- end
- }
- cert = OpenSSL::X509::Certificate.new
- cert.version = 2
- cert.serial = 1
- name = OpenSSL::X509::Name.new(cn)
- cert.subject = name
- cert.issuer = name
- cert.not_before = Time.now
- cert.not_after = Time.now + (365*24*60*60)
- cert.public_key = rsa.public_key
-
- ef = OpenSSL::X509::ExtensionFactory.new(nil,cert)
- ef.issuer_certificate = cert
- cert.extensions = [
- ef.create_extension("basicConstraints","CA:FALSE"),
- ef.create_extension("keyUsage", "keyEncipherment"),
- ef.create_extension("subjectKeyIdentifier", "hash"),
- ef.create_extension("extendedKeyUsage", "serverAuth"),
- ef.create_extension("nsComment", comment),
- ]
- aki = ef.create_extension("authorityKeyIdentifier",
- "keyid:always,issuer:always")
- cert.add_extension(aki)
- cert.sign(rsa, OpenSSL::Digest::SHA1.new)
-
- return [ cert, rsa ]
- end
- module_function :create_self_signed_cert
- end
-
- class GenericServer
- def ssl_context
- @ssl_context ||= nil
- end
-
- undef listen
- def listen(address, port)
- listeners = Utils::create_listeners(address, port, @logger)
- if @config[:SSLEnable]
- unless ssl_context
- @ssl_context = setup_ssl_context(@config)
- @logger.info("\n" + @config[:SSLCertificate].to_text)
- end
- listeners.collect!{|svr|
- ssvr = ::OpenSSL::SSL::SSLServer.new(svr, ssl_context)
- ssvr.start_immediately = @config[:SSLStartImmediately]
- ssvr
- }
- end
- @listeners += listeners
- end
-
- def setup_ssl_context(config)
- unless config[:SSLCertificate]
- cn = config[:SSLCertName]
- comment = config[:SSLCertComment]
- cert, key = Utils::create_self_signed_cert(1024, cn, comment)
- config[:SSLCertificate] = cert
- config[:SSLPrivateKey] = key
- end
- ctx = OpenSSL::SSL::SSLContext.new
- ctx.key = config[:SSLPrivateKey]
- ctx.cert = config[:SSLCertificate]
- ctx.client_ca = config[:SSLClientCA]
- ctx.extra_chain_cert = config[:SSLExtraChainCert]
- ctx.ca_file = config[:SSLCACertificateFile]
- ctx.ca_path = config[:SSLCACertificatePath]
- ctx.cert_store = config[:SSLCertificateStore]
- ctx.verify_mode = config[:SSLVerifyClient]
- ctx.verify_depth = config[:SSLVerifyDepth]
- ctx.verify_callback = config[:SSLVerifyCallback]
- ctx.timeout = config[:SSLTimeout]
- ctx.options = config[:SSLOptions]
- ctx
- end
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/utils.rb b/ruby_1_9_3/lib/webrick/utils.rb
deleted file mode 100644
index 157c530cc9..0000000000
--- a/ruby_1_9_3/lib/webrick/utils.rb
+++ /dev/null
@@ -1,241 +0,0 @@
-#
-# utils.rb -- Miscellaneous utilities
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou
-# Copyright (c) 2002 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: utils.rb,v 1.10 2003/02/16 22:22:54 gotoyuzo Exp $
-
-require 'socket'
-require 'fcntl'
-begin
- require 'etc'
-rescue LoadError
- nil
-end
-
-module WEBrick
- module Utils
- ##
- # Sets IO operations on +io+ to be non-blocking
- def set_non_blocking(io)
- flag = File::NONBLOCK
- if defined?(Fcntl::F_GETFL)
- flag |= io.fcntl(Fcntl::F_GETFL)
- end
- io.fcntl(Fcntl::F_SETFL, flag)
- end
- module_function :set_non_blocking
-
- ##
- # Sets the close on exec flag for +io+
- def set_close_on_exec(io)
- if defined?(Fcntl::FD_CLOEXEC)
- io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
- end
- end
- module_function :set_close_on_exec
-
- ##
- # Changes the process's uid and gid to the ones of +user+
- def su(user)
- if defined?(Etc)
- pw = Etc.getpwnam(user)
- Process::initgroups(user, pw.gid)
- Process::Sys::setgid(pw.gid)
- Process::Sys::setuid(pw.uid)
- else
- warn("WEBrick::Utils::su doesn't work on this platform")
- end
- end
- module_function :su
-
- ##
- # The server hostname
- def getservername
- host = Socket::gethostname
- begin
- Socket::gethostbyname(host)[0]
- rescue
- host
- end
- end
- module_function :getservername
-
- ##
- # Creates TCP server sockets bound to +address+:+port+ and returns them.
- #
- # It will create IPV4 and IPV6 sockets on all interfaces.
- def create_listeners(address, port, logger=nil)
- unless port
- raise ArgumentError, "must specify port"
- end
- res = Socket::getaddrinfo(address, port,
- Socket::AF_UNSPEC, # address family
- Socket::SOCK_STREAM, # socket type
- 0, # protocol
- Socket::AI_PASSIVE) # flag
- last_error = nil
- sockets = []
- res.each{|ai|
- begin
- logger.debug("TCPServer.new(#{ai[3]}, #{port})") if logger
- sock = TCPServer.new(ai[3], port)
- port = sock.addr[1] if port == 0
- Utils::set_close_on_exec(sock)
- sockets << sock
- rescue => ex
- logger.warn("TCPServer Error: #{ex}") if logger
- last_error = ex
- end
- }
- raise last_error if sockets.empty?
- return sockets
- end
- module_function :create_listeners
-
- ##
- # Characters used to generate random strings
- RAND_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
- "0123456789" +
- "abcdefghijklmnopqrstuvwxyz"
-
- ##
- # Generates a random string of length +len+
- def random_string(len)
- rand_max = RAND_CHARS.bytesize
- ret = ""
- len.times{ ret << RAND_CHARS[rand(rand_max)] }
- ret
- end
- module_function :random_string
-
- ###########
-
- require "thread"
- require "timeout"
- require "singleton"
-
- ##
- # Class used to manage timeout handlers across multiple threads.
- #
- # Timeout handlers should be managed by using the class methods which are
- # synchronized.
- #
- # id = TimeoutHandler.register(10, Timeout::Error)
- # begin
- # sleep 20
- # puts 'foo'
- # ensure
- # TimeoutHandler.cancel(id)
- # end
- #
- # will raise Timeout::Error
- #
- # id = TimeoutHandler.register(10, Timeout::Error)
- # begin
- # sleep 5
- # puts 'foo'
- # ensure
- # TimeoutHandler.cancel(id)
- # end
- #
- # will print 'foo'
- #
- class TimeoutHandler
- include Singleton
-
- ##
- # Mutex used to synchronize access across threads
- TimeoutMutex = Mutex.new # :nodoc:
-
- ##
- # Registers a new timeout handler
- #
- # +time+:: Timeout in seconds
- # +exception+:: Exception to raise when timeout elapsed
- def TimeoutHandler.register(seconds, exception)
- TimeoutMutex.synchronize{
- instance.register(Thread.current, Time.now + seconds, exception)
- }
- end
-
- ##
- # Cancels the timeout handler +id+
- def TimeoutHandler.cancel(id)
- TimeoutMutex.synchronize{
- instance.cancel(Thread.current, id)
- }
- end
-
- def initialize
- @timeout_info = Hash.new
- Thread.start{
- while true
- now = Time.now
- @timeout_info.each{|thread, ary|
- ary.dup.each{|info|
- time, exception = *info
- interrupt(thread, info.object_id, exception) if time < now
- }
- }
- sleep 0.5
- end
- }
- end
-
- ##
- # Interrupts the timeout handler +id+ and raises +exception+
- def interrupt(thread, id, exception)
- TimeoutMutex.synchronize{
- if cancel(thread, id) && thread.alive?
- thread.raise(exception, "execution timeout")
- end
- }
- end
-
- ##
- # Registers a new timeout handler
- #
- # +time+:: Timeout in seconds
- # +exception+:: Exception to raise when timeout elapsed
- def register(thread, time, exception)
- @timeout_info[thread] ||= Array.new
- @timeout_info[thread] << [time, exception]
- return @timeout_info[thread].last.object_id
- end
-
- ##
- # Cancels the timeout handler +id+
- def cancel(thread, id)
- if ary = @timeout_info[thread]
- ary.delete_if{|info| info.object_id == id }
- if ary.empty?
- @timeout_info.delete(thread)
- end
- return true
- end
- return false
- end
- end
-
- ##
- # Executes the passed block and raises +exception+ if execution takes more
- # than +seconds+.
- #
- # If +seconds+ is zero or nil, simply executes the block
- def timeout(seconds, exception=Timeout::Error)
- return yield if seconds.nil? or seconds.zero?
- # raise ThreadError, "timeout within critical session" if Thread.critical
- id = TimeoutHandler.register(seconds, exception)
- begin
- yield(seconds)
- ensure
- TimeoutHandler.cancel(id)
- end
- end
- module_function :timeout
- end
-end
diff --git a/ruby_1_9_3/lib/webrick/version.rb b/ruby_1_9_3/lib/webrick/version.rb
deleted file mode 100644
index a49090828d..0000000000
--- a/ruby_1_9_3/lib/webrick/version.rb
+++ /dev/null
@@ -1,13 +0,0 @@
-#--
-# version.rb -- version and release date
-#
-# Author: IPR -- Internet Programming with Ruby -- writers
-# Copyright (c) 2000 TAKAHASHI Masayoshi, GOTOU YUUZOU
-# Copyright (c) 2003 Internet Programming with Ruby writers. All rights
-# reserved.
-#
-# $IPR: version.rb,v 1.74 2003/07/22 19:20:43 gotoyuzo Exp $
-
-module WEBrick
- VERSION = "1.3.1"
-end
diff --git a/ruby_1_9_3/lib/xmlrpc/README.rdoc b/ruby_1_9_3/lib/xmlrpc/README.rdoc
deleted file mode 100644
index 2faed28cb9..0000000000
--- a/ruby_1_9_3/lib/xmlrpc/README.rdoc
+++ /dev/null
@@ -1,300 +0,0 @@
-= XMLRPC for Ruby
-
-== Author and Copyright
-
-Copyright (C) 2001-2004 by Michael Neumann (mailto:mneumann@ntecs.de)
-
-Released under the same term of license as Ruby.
-
-== Overview
-
-XMLRPC is a lightweight protocol that enables remote procedure calls over
-HTTP. It is defined at http://www.xmlrpc.com.
-
-XMLRPC allows you to create simple distributed computing solutions that span
-computer languages. Its distinctive feature is its simplicity compared to
-other approaches like SOAP and CORBA.
-
-The Ruby standard library package 'xmlrpc' enables you to create a server that
-implements remote procedures and a client that calls them. Very little code
-is required to achieve either of these.
-
-== Example
-
-Try the following code. It calls a standard demonstration remote procedure.
-
- require 'xmlrpc/client'
- require 'pp'
-
- server = XMLRPC::Client.new2("http://xmlrpc-c.sourceforge.net/api/sample.php")
- result = server.call("sample.sumAndDifference", 5, 3)
- pp result
-
-== Documentation
-
-See http://www.ntecs.de/projects/xmlrpc4r. There is plenty of detail there to
-use the client and implement a server.
-
-== Features of XMLRPC for Ruby
-
-* Extensions
- * Introspection
- * multiCall
- * optionally nil values and integers larger than 32 Bit
-
-* Server
- * Standalone XML-RPC server
- * CGI-based (works with FastCGI)
- * Apache mod_ruby server
- * WEBrick servlet
-
-* Client
- * synchronous/asynchronous calls
- * Basic HTTP-401 Authentification
- * HTTPS protocol (SSL)
-
-* Parsers
- * NQXML (NQXMLStreamParser, NQXMLTreeParser)
- * Expat (XMLStreamParser, XMLTreeParser)
- * REXML (REXMLStreamParser)
- * xml-scan (XMLScanStreamParser)
- * Fastest parser is Expat's XMLStreamParser!
-
-* General
- * possible to choose between XMLParser module (Expat wrapper) and REXML/NQXML (pure Ruby) parsers
- * Marshalling Ruby objects to Hashs and reconstruct them later from a Hash
- * SandStorm component architecture Client interface
-
-== Howto
-
-=== Client
-
- require "xmlrpc/client"
-
- # Make an object to represent the XML-RPC server.
- server = XMLRPC::Client.new( "xmlrpc-c.sourceforge.net", "/api/sample.php")
-
- # Call the remote server and get our result
- result = server.call("sample.sumAndDifference", 5, 3)
-
- sum = result["sum"]
- difference = result["difference"]
-
- puts "Sum: #{sum}, Difference: #{difference}"
-
-=== Client with XML-RPC fault-structure handling
-
-There are two possible ways, of handling a fault-structure:
-
-==== by catching a XMLRPC::FaultException exception
-
- require "xmlrpc/client"
-
- # Make an object to represent the XML-RPC server.
- server = XMLRPC::Client.new( "xmlrpc-c.sourceforge.net", "/api/sample.php")
-
- begin
- # Call the remote server and get our result
- result = server.call("sample.sumAndDifference", 5, 3)
-
- sum = result["sum"]
- difference = result["difference"]
-
- puts "Sum: #{sum}, Difference: #{difference}"
-
- rescue XMLRPC::FaultException => e
- puts "Error: "
- puts e.faultCode
- puts e.faultString
- end
-
-==== by calling "call2" which returns a boolean
-
- require "xmlrpc/client"
-
- # Make an object to represent the XML-RPC server.
- server = XMLRPC::Client.new( "xmlrpc-c.sourceforge.net", "/api/sample.php")
-
- # Call the remote server and get our result
- ok, result = server.call2("sample.sumAndDifference", 5, 3)
-
- if ok
- sum = result["sum"]
- difference = result["difference"]
-
- puts "Sum: #{sum}, Difference: #{difference}"
- else
- puts "Error: "
- puts result.faultCode
- puts result.faultString
- end
-
-=== Client using Proxy
-
-You can create a +Proxy+ object onto which you can call methods. This way it
-looks nicer. Both forms, _call_ and _call2_ are supported through _proxy_ and
-<i>proxy2</i>. You can additionally give arguments to the Proxy, which will be
-given to each XML-RPC call using that Proxy.
-
- require "xmlrpc/client"
-
- # Make an object to represent the XML-RPC server.
- server = XMLRPC::Client.new( "xmlrpc-c.sourceforge.net", "/api/sample.php")
-
- # Create a Proxy object
- sample = server.proxy("sample")
-
- # Call the remote server and get our result
- result = sample.sumAndDifference(5,3)
-
- sum = result["sum"]
- difference = result["difference"]
-
- puts "Sum: #{sum}, Difference: #{difference}"
-
-=== CGI-based Server
-
-There are also two ways to define handler, the first is
-like C/PHP, the second like Java, of course both ways
-can be mixed:
-
-==== C/PHP-like (handler functions)
-
- require "xmlrpc/server"
-
- s = XMLRPC::CGIServer.new
-
- s.add_handler("sample.sumAndDifference") do |a,b|
- { "sum" => a + b, "difference" => a - b }
- end
-
- s.serve
-
-==== Java-like (handler classes)
-
- require "xmlrpc/server"
-
- s = XMLRPC::CGIServer.new
-
- class MyHandler
- def sumAndDifference(a, b)
- { "sum" => a + b, "difference" => a - b }
- end
- end
-
- # NOTE: Security Hole (read below)!!!
- s.add_handler("sample", MyHandler.new)
- s.serve
-
-
-To return a fault-structure you have to raise an FaultException e.g.:
-
- raise XMLRPC::FaultException.new(3, "division by Zero")
-
-===== Security Note
-
-From Brian Candler:
-
- Above code sample has an extremely nasty security hole, in that you can now call
- any method of 'MyHandler' remotely, including methods inherited from Object
- and Kernel! For example, in the client code, you can use
-
- puts server.call("sample.send","`","ls")
-
- (backtick being the method name for running system processes). Needless to
- say, 'ls' can be replaced with something else.
-
- The version which binds proc objects (or the version presented below in the next section)
- doesn't have this problem, but people may be tempted to use the second version because it's
- so nice and 'Rubyesque'. I think it needs a big red disclaimer.
-
-
-From Michael:
-
-A solution is to undef insecure methods or to use (({XMLRPC::iPIMethods})) as shown below:
-
- class MyHandler
- def sumAndDifference(a, b)
- { "sum" => a + b, "difference" => a - b }
- end
- end
-
- # ... server initialization ...
-
- s.add_handler(XMLRPC::iPIMethods("sample"), MyHandler.new)
-
- # ...
-
-This adds only public instance methods explicitly declared in class MyHandler
-(and not those inherited from any other class).
-
-==== With interface declarations
-
-Code sample from the book Ruby Developer's Guide:
-
- require "xmlrpc/server"
-
- class Num
- INTERFACE = XMLRPC::interface("num") {
- meth 'int add(int, int)', 'Add two numbers', 'add'
- meth 'int div(int, int)', 'Divide two numbers'
- }
-
- def add(a, b) a + b end
- def div(a, b) a / b end
- end
-
-
- s = XMLRPC::CGIServer.new
- s.add_handler(Num::INTERFACE, Num.new)
- s.serve
-
-=== Standalone server
-
-Same as CGI-based server, only that the line
-
- server = XMLRPC::CGIServer.new
-
-must be changed to
-
- server = XMLRPC::Server.new(8080)
-
-if you want a server listening on port 8080.
-The rest is the same.
-
-=== Choosing a different XML Parser or XML Writer
-
-The examples above all use the default parser (which is now since 1.8
-REXMLStreamParser) and a default XML writer. If you want to use a different
-XML parser, then you have to call the <i>set_parser</i> method of
-<tt>XMLRPC::Client</tt> instances or instances of subclasses of
-<tt>XMLRPC::BasicServer</tt> or by editing xmlrpc/config.rb.
-
-Client Example:
-
- # ...
- server = XMLRPC::Client.new( "xmlrpc-c.sourceforge.net", "/api/sample.php")
- server.set_parser(XMLRPC::XMLParser::XMLParser.new)
- # ...
-
-Server Example:
-
- # ...
- s = XMLRPC::CGIServer.new
- s.set_parser(XMLRPC::XMLParser::XMLStreamParser.new)
- # ...
-
-or:
-
- # ...
- server = XMLRPC::Server.new(8080)
- server.set_parser(XMLRPC::XMLParser::NQXMLParser.new)
- # ...
-
-
-Note that XMLStreamParser is incredible faster (and uses less memory) than any
-other parser and scales well for large documents. For example for a 0.5 MB XML
-document with many tags, XMLStreamParser is ~350 (!) times faster than
-NQXMLTreeParser and still ~18 times as fast as XMLTreeParser.
-
-You can change the XML-writer by calling method <i>set_writer</i>.
diff --git a/ruby_1_9_3/lib/xmlrpc/README.txt b/ruby_1_9_3/lib/xmlrpc/README.txt
deleted file mode 100644
index ade842d8b1..0000000000
--- a/ruby_1_9_3/lib/xmlrpc/README.txt
+++ /dev/null
@@ -1,31 +0,0 @@
-= XMLRPC for Ruby, Standard Library Documentation
-
-== Overview
-
-XMLRPC is a lightweight protocol that enables remote procedure calls over
-HTTP. It is defined at http://www.xmlrpc.com.
-
-XMLRPC allows you to create simple distributed computing solutions that span
-computer languages. Its distinctive feature is its simplicity compared to
-other approaches like SOAP and CORBA.
-
-The Ruby standard library package 'xmlrpc' enables you to create a server that
-implements remote procedures and a client that calls them. Very little code
-is required to achieve either of these.
-
-== Example
-
-Try the following code. It calls a standard demonstration remote procedure.
-
- require 'xmlrpc/client'
- require 'pp'
-
- server = XMLRPC::Client.new2("http://xmlrpc-c.sourceforge.net/api/sample.php")
- result = server.call("sample.sumAndDifference", 5, 3)
- pp result
-
-== Documentation
-
-See http://www.ntecs.de/projects/xmlrpc4r. There is plenty of detail there to
-use the client and implement a server.
-
diff --git a/ruby_1_9_3/lib/xmlrpc/base64.rb b/ruby_1_9_3/lib/xmlrpc/base64.rb
deleted file mode 100644
index bfa8c0a2d5..0000000000
--- a/ruby_1_9_3/lib/xmlrpc/base64.rb
+++ /dev/null
@@ -1,81 +0,0 @@
-=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$
-=end
diff --git a/ruby_1_9_3/lib/xmlrpc/client.rb b/ruby_1_9_3/lib/xmlrpc/client.rb
deleted file mode 100644
index 968292b077..0000000000
--- a/ruby_1_9_3/lib/xmlrpc/client.rb
+++ /dev/null
@@ -1,625 +0,0 @@
-=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$
-
-=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("m0")
- end
- end
-
- def do_rpc(request, async=false)
- header = {
- "User-Agent" => USER_AGENT,
- "Content-Type" => "text/xml; charset=utf-8",
- "Content-Length" => request.bytesize.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.bytesize == 0
- raise "Wrong size. Was #{data.bytesize}, should be #{expected}"
- elsif expected != "<unknown>" and expected.to_i != data.bytesize and resp["Transfer-Encoding"].nil?
- raise "Wrong size. Was #{data.bytesize}, 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
-
diff --git a/ruby_1_9_3/lib/xmlrpc/config.rb b/ruby_1_9_3/lib/xmlrpc/config.rb
deleted file mode 100644
index 34c3bbaf1b..0000000000
--- a/ruby_1_9_3/lib/xmlrpc/config.rb
+++ /dev/null
@@ -1,40 +0,0 @@
-#
-# $Id$
-# 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
-
diff --git a/ruby_1_9_3/lib/xmlrpc/create.rb b/ruby_1_9_3/lib/xmlrpc/create.rb
deleted file mode 100644
index 7aa0873590..0000000000
--- a/ruby_1_9_3/lib/xmlrpc/create.rb
+++ /dev/null
@@ -1,289 +0,0 @@
-#
-# Creates XML-RPC call/response documents
-#
-# Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de)
-#
-# $Id$
-#
-
-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!(/&/, '&amp;')
- cleaned.gsub!(/</, '&lt;')
- cleaned.gsub!(/>/, '&gt;')
- 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, Bignum
- # XML-RPC's int is 32bit int, and Fixnum also may be beyond 32bit
- 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 Symbol
- @writer.tag("string", param.to_s)
-
- when String
- @writer.tag("string", param)
-
- when NilClass
- if Config::ENABLE_NIL_CREATE
- @writer.ele("nil")
- else
- raise "Wrong type NilClass. Not allowed!"
- end
-
- when Float
- raise "Wrong value #{param}. Not allowed!" unless param.finite?
- @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
-
diff --git a/ruby_1_9_3/lib/xmlrpc/datetime.rb b/ruby_1_9_3/lib/xmlrpc/datetime.rb
deleted file mode 100644
index d6c80a2cb9..0000000000
--- a/ruby_1_9_3/lib/xmlrpc/datetime.rb
+++ /dev/null
@@ -1,142 +0,0 @@
-=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)
- self.to_a == Array(o) rescue false
- end
-
-end
-
-
-end # module XMLRPC
-
-
-=begin
-= History
- $Id$
-=end
diff --git a/ruby_1_9_3/lib/xmlrpc/httpserver.rb b/ruby_1_9_3/lib/xmlrpc/httpserver.rb
deleted file mode 100644
index a9605efa7a..0000000000
--- a/ruby_1_9_3/lib/xmlrpc/httpserver.rb
+++ /dev/null
@@ -1,178 +0,0 @@
-#
-# 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$
-#
-
-
-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
- io << http_resp(500, "Internal Server Error")
- end
-
-end # class HttpServer
-
diff --git a/ruby_1_9_3/lib/xmlrpc/marshal.rb b/ruby_1_9_3/lib/xmlrpc/marshal.rb
deleted file mode 100644
index d121828312..0000000000
--- a/ruby_1_9_3/lib/xmlrpc/marshal.rb
+++ /dev/null
@@ -1,76 +0,0 @@
-#
-# Marshalling of XML-RPC methodCall and methodResponse
-#
-# Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de)
-#
-# $Id$
-#
-
-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
-
diff --git a/ruby_1_9_3/lib/xmlrpc/parser.rb b/ruby_1_9_3/lib/xmlrpc/parser.rb
deleted file mode 100644
index eb3c9b3441..0000000000
--- a/ruby_1_9_3/lib/xmlrpc/parser.rb
+++ /dev/null
@@ -1,812 +0,0 @@
-#
-# Parser for XML-RPC call and response
-#
-# Copyright (C) 2001, 2002, 2003 by Michael Neumann (mneumann@ntecs.de)
-#
-# $Id$
-#
-
-
-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
-
- def initialize(faultCode, faultString)
- @faultCode = faultCode
- @faultString = faultString
- super(@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 =~ /^([a-zA-Z_]\w*)$/
- }
- 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)
- 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
-
diff --git a/ruby_1_9_3/lib/xmlrpc/server.rb b/ruby_1_9_3/lib/xmlrpc/server.rb
deleted file mode 100644
index b7215385ad..0000000000
--- a/ruby_1_9_3/lib/xmlrpc/server.rb
+++ /dev/null
@@ -1,778 +0,0 @@
-=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
- rescue
- # 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.bytesize != 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.bytesize.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.bytesize != 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.bytesize.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
- signals = %w[INT TERM HUP] & Signal.list.keys
- 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.bytesize != length
- raise WEBrick::HTTPStatus::BadRequest
- end
-
- resp = process(data)
- if resp.nil? or resp.bytesize <= 0
- raise WEBrick::HTTPStatus::InternalServerError
- end
-
- response.status = 200
- response['Content-Length'] = resp.bytesize
- response['Content-Type'] = "text/xml; charset=utf-8"
- response.body = resp
- end
-end
-
-
-end # module XMLRPC
-
-
-=begin
-= History
- $Id$
-=end
-
diff --git a/ruby_1_9_3/lib/xmlrpc/utils.rb b/ruby_1_9_3/lib/xmlrpc/utils.rb
deleted file mode 100644
index b86509cb3a..0000000000
--- a/ruby_1_9_3/lib/xmlrpc/utils.rb
+++ /dev/null
@@ -1,165 +0,0 @@
-#
-# 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$
-#
-
-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.to_s, 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.to_s, 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
-
diff --git a/ruby_1_9_3/lib/yaml.rb b/ruby_1_9_3/lib/yaml.rb
deleted file mode 100644
index ff9e1a6344..0000000000
--- a/ruby_1_9_3/lib/yaml.rb
+++ /dev/null
@@ -1,76 +0,0 @@
-##
-# The YAML module allows you to use one of the two YAML engines that ship with
-# ruby. By default Psych is used but the old and unmaintained Syck may be
-# chosen.
-#
-# See Psych or Syck for usage and documentation.
-#
-# To set the YAML engine to syck:
-#
-# YAML::ENGINE.yamler = 'syck'
-#
-# To set the YAML engine back to psych:
-#
-# YAML::ENGINE.yamler = 'psych'
-
-module YAML
- class EngineManager # :nodoc:
- attr_reader :yamler
-
- def initialize
- @yamler = nil
- end
-
- def syck?
- 'syck' == @yamler
- end
-
- def yamler= engine
- raise(ArgumentError, "bad engine") unless %w{syck psych}.include?(engine)
-
- require engine unless (engine == 'syck' ? Syck : Psych).const_defined?(:VERSION)
-
- Object.class_eval <<-eorb, __FILE__, __LINE__ + 1
- remove_const 'YAML'
- YAML = #{engine.capitalize}
- remove_method :to_yaml
- alias :to_yaml :#{engine}_to_yaml
- eorb
-
- @yamler = engine
- engine
- end
- end
-
- ##
- # Allows changing the current YAML engine. See YAML for details.
-
- ENGINE = YAML::EngineManager.new
-end
-
-if defined?(Psych)
- engine = 'psych'
-elsif defined?(Syck)
- engine = 'syck'
-else
- begin
- require 'psych'
- engine = 'psych'
- rescue LoadError
- warn "#{caller[0]}:"
- warn "It seems your ruby installation is missing psych (for YAML output)."
- warn "To eliminate this warning, please install libyaml and reinstall your ruby."
- require 'syck'
- engine = 'syck'
- end
-end
-
-module Syck
- ENGINE = YAML::ENGINE
-end
-
-module Psych
- ENGINE = YAML::ENGINE
-end
-
-YAML::ENGINE.yamler = engine
diff --git a/ruby_1_9_3/lib/yaml/dbm.rb b/ruby_1_9_3/lib/yaml/dbm.rb
deleted file mode 100644
index 07441f53ad..0000000000
--- a/ruby_1_9_3/lib/yaml/dbm.rb
+++ /dev/null
@@ -1,214 +0,0 @@
-require 'yaml'
-require 'dbm'
-
-module YAML
-
-# YAML + DBM = YDBM
-#
-# YAML::DBM provides the same interface as ::DBM.
-#
-# However, while DBM only allows strings for both keys and values,
-# this library allows one to use most Ruby objects for values
-# by first converting them to YAML. Keys must be strings.
-#
-# Conversion to and from YAML is performed automatically.
-#
-# See the documentation for ::DBM and ::YAML for more information.
-class DBM < ::DBM
- VERSION = "0.1"
-
- # Return value associated with +key+ from database.
- #
- # Returns +nil+ if there is no such +key+.
- def []( key )
- fetch( key )
- end
-
- # :call-seq:
- # []=( key, value )
- #
- # Set +key+ to +value+ in database.
- #
- # +value+ will be converted to YAML before storage.
- def []=( key, val )
- store( key, val )
- end
-
- # :call-seq:
- # fetch( key, ifnone = nil )
- # fetch( key, &block )
- #
- # Return value associated with +key+.
- #
- # If there is no value for +key+ and no block is given, returns +ifnone+.
- #
- # Otherwise, calls block passing in the given +key+.
- def fetch( keystr, ifnone = nil )
- begin
- val = super( keystr )
- return YAML.load( val ) if String === val
- rescue IndexError
- end
- if block_given?
- yield keystr
- else
- ifnone
- end
- end
-
- # Deprecated, used YAML::DBM#key instead.
- def index( keystr )
- super( keystr.to_yaml )
- end
-
- # Returns an array containing the values associated with the given keys.
- def values_at( *keys )
- keys.collect { |k| fetch( k ) }
- end
-
- # Deletes value from database associated with +key+.
- #
- # Returns value or +nil+.
- def delete( key )
- v = super( key )
- if String === v
- v = YAML.load( v )
- end
- v
- end
-
- # Calls the given block once for each +key+, +value+ pair in the database.
- # Deletes all entries for which the block returns true.
- #
- # Returns +self+.
- def delete_if # :yields: [key, value]
- del_keys = keys.dup
- del_keys.delete_if { |k| yield( k, fetch( k ) ) == false }
- del_keys.each { |k| delete( k ) }
- self
- end
-
- # Converts the contents of the database to an in-memory Hash, then calls
- # Hash#reject with the specified code block, returning a new Hash.
- def reject
- hsh = self.to_hash
- hsh.reject { |k,v| yield k, v }
- end
-
- # Calls the given block once for each +key+, +value+ pair in the database.
- #
- # Returns +self+.
- def each_pair # :yields: [key, value]
- keys.each { |k| yield k, fetch( k ) }
- self
- end
-
- # Calls the given block for each value in database.
- #
- # Returns +self+.
- def each_value # :yields: value
- super { |v| yield YAML.load( v ) }
- self
- end
-
- # Returns an array of values from the database.
- def values
- super.collect { |v| YAML.load( v ) }
- end
-
- # Returns true if specified value is found in the database.
- def has_value?( val )
- each_value { |v| return true if v == val }
- return false
- end
-
- # Returns a Hash (not a DBM database) created by using each value in the
- # database as a key, with the corresponding key as its value.
- #
- # Note that all values in the hash will be Strings, but the keys will be
- # actual objects.
- def invert
- h = {}
- keys.each { |k| h[ self.fetch( k ) ] = k }
- h
- end
-
- # Replaces the contents of the database with the contents of the specified
- # object. Takes any object which implements the each_pair method, including
- # Hash and DBM objects.
- def replace( hsh )
- clear
- update( hsh )
- end
-
- # Removes a [key, value] pair from the database, and returns it.
- # If the database is empty, returns +nil+.
- #
- # The order in which values are removed/returned is not guaranteed.
- def shift
- a = super
- a[1] = YAML.load( a[1] ) if a
- a
- end
-
- # :call-seq:
- # select( &block )
- # select( *keys )
- #
- # If a block is provided, returns a new array containing [key, value] pairs
- # for which the block returns true.
- #
- # Otherwise, same as #values_at
- def select( *keys )
- if block_given?
- self.keys.collect { |k| v = self[k]; [k, v] if yield k, v }.compact
- else
- values_at( *keys )
- end
- end
-
- # :call-seq:
- # store( key, value )
- #
- #Stores +value+ in database with +key+ as the index. +value+ is converted
- #to YAML before being stored.
- #
- #Returns +value+
- def store( key, val )
- super( key, val.to_yaml )
- val
- end
-
- # Updates the database with multiple values from the specified object.
- # Takes any object which implements the each_pair method, including
- # Hash and DBM objects.
- #
- # Returns +self+.
- def update( hsh )
- hsh.keys.each do |k|
- self.store( k, hsh.fetch( k ) )
- end
- self
- end
-
- # Converts the contents of the database to an array of [key, value] arrays,
- # and returns it.
- def to_a
- a = []
- keys.each { |k| a.push [ k, self.fetch( k ) ] }
- a
- end
-
-
- # Converts the contents of the database to an in-memory Hash object, and
- # returns it.
- def to_hash
- h = {}
- keys.each { |k| h[ k ] = self.fetch( k ) }
- h
- end
-
- alias :each :each_pair
-end
-
-end
diff --git a/ruby_1_9_3/lib/yaml/store.rb b/ruby_1_9_3/lib/yaml/store.rb
deleted file mode 100644
index 82d6ee1aaa..0000000000
--- a/ruby_1_9_3/lib/yaml/store.rb
+++ /dev/null
@@ -1,86 +0,0 @@
-#
-# YAML::Store
-#
-require 'yaml'
-require 'pstore'
-
-# YAML::Store provides the same functionality as PStore, except it uses YAML
-# to dump objects instead of Marshal.
-#
-# == Example
-#
-# require 'yaml/store'
-#
-# Person = Struct.new :first_name, :last_name
-#
-# people = [Person.new("Bob", "Smith"), Person.new("Mary", "Johnson")]
-#
-# store = YAML::Store.new "test.store"
-#
-# store.transaction do
-# store["people"] = people
-# store["greeting"] = { "hello" => "world" }
-# end
-#
-# After running the above code, the contents of "test.store" will be:
-#
-# ---
-# people:
-# - !ruby/struct:Person
-# first_name: Bob
-# last_name: Smith
-# - !ruby/struct:Person
-# first_name: Mary
-# last_name: Johnson
-# greeting:
-# hello: world
-
-class YAML::Store < PStore
-
- # :call-seq:
- # initialize( file_name, yaml_opts = {} )
- #
- # Creates a new YAML::Store object, which will store data in +file_name+.
- # If the file does not already exist, it will be created.
- #
- #
- # Options passed in through +yaml_opts+ will be used when converting the
- # store to YAML via Hash#to_yaml().
- def initialize( *o )
- @opt = {}
- if String === o.first
- super(o.shift)
- end
- if o.last.is_a? Hash
- @opt.update(o.pop)
- end
- end
-
- # :stopdoc:
-
- def dump(table)
- @table.to_yaml(@opt)
- end
-
- def load(content)
- table = YAML.load(content)
- if table == false
- {}
- else
- table
- end
- end
-
- def marshal_dump_supports_canonical_option?
- false
- end
-
- EMPTY_MARSHAL_DATA = {}.to_yaml
- EMPTY_MARSHAL_CHECKSUM = Digest::MD5.digest(EMPTY_MARSHAL_DATA)
- def empty_marshal_data
- EMPTY_MARSHAL_DATA
- end
- def empty_marshal_checksum
- EMPTY_MARSHAL_CHECKSUM
- end
-end